answer
stringlengths 17
10.2M
|
|---|
package org.opendaylight.yangtools.util;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.util.concurrent.AtomicDouble;
/**
* Class that calculates and tracks time duration statistics.
*
* @author Thomas Pantelis
*/
public class DurationStatsTracker {
private final AtomicLong totalDurations = new AtomicLong();
private final AtomicLong longestDuration = new AtomicLong();
private volatile long timeOfLongestDuration;
private final AtomicLong shortestDuration = new AtomicLong(Long.MAX_VALUE);
private volatile long timeOfShortestDuration;
private final AtomicDouble averageDuration = new AtomicDouble();
/**
* Add a duration to track.
*
* @param duration the duration in nanoseconds.
*/
public void addDuration(long duration) {
double currentAve = averageDuration.get();
long currentTotal = totalDurations.get();
long newTotal = currentTotal + 1;
// Calculate moving cumulative average.
double newAve = currentAve * (double)currentTotal / (double)newTotal + (double)duration / (double)newTotal;
averageDuration.compareAndSet(currentAve, newAve);
totalDurations.compareAndSet(currentTotal, newTotal);
long longest = longestDuration.get();
if( duration > longest ) {
if(longestDuration.compareAndSet( longest, duration )) {
timeOfLongestDuration = System.currentTimeMillis();
}
}
long shortest = shortestDuration.get();
if( duration < shortest ) {
if(shortestDuration.compareAndSet( shortest, duration )) {
timeOfShortestDuration = System.currentTimeMillis();
}
}
}
/**
* Returns the total number of tracked durations.
*/
public long getTotalDurations() {
return totalDurations.get();
}
/**
* Returns the longest duration in nanoseconds.
*/
public long getLongestDuration() {
return longestDuration.get();
}
/**
* Returns the shortest duration in nanoseconds.
*/
public long getShortestDuration() {
long shortest = shortestDuration.get();
return shortest < Long.MAX_VALUE ? shortest : 0;
}
/**
* Returns the average duration in nanoseconds.
*/
public double getAverageDuration() {
return averageDuration.get();
}
/**
* Returns the time stamp of the longest duration.
*/
public long getTimeOfLongestDuration() {
return timeOfLongestDuration;
}
/**
* Returns the time stamp of the shortest duration.
*/
public long getTimeOfShortestDuration() {
return timeOfShortestDuration;
}
/**
* Resets all statistics back to their defaults.
*/
public void reset() {
totalDurations.set(0);
longestDuration.set(0);
timeOfLongestDuration = 0;
shortestDuration.set(Long.MAX_VALUE);
timeOfShortestDuration = 0;
averageDuration.set(0.0);
}
/**
* Returns the average duration as a displayable String with units, e.g. "12.34 ms".
*/
public String getDisplayableAverageDuration() {
return formatDuration(getAverageDuration(), 0);
}
/**
* Returns the shortest duration as a displayable String with units and the date/time at
* which it occurred, e.g. "12.34 ms at 08/02/2014 12:30:24".
*/
public String getDisplayableShortestDuration() {
return formatDuration(getShortestDuration(), getTimeOfShortestDuration());
}
/**
* Returns the longest duration as a displayable String with units and the date/time at
* which it occurred, e.g. "12.34 ms at 08/02/2014 12:30:24".
*/
public String getDisplayableLongestDuration() {
return formatDuration(getLongestDuration(), getTimeOfLongestDuration());
}
private String formatDuration(double duration, long timeStamp) {
TimeUnit unit = chooseUnit((long)duration);
double value = duration / NANOSECONDS.convert(1, unit);
return timeStamp > 0 ?
String.format("%.4g %s at %3$tD %3$tT", value, abbreviate(unit), new Date(timeStamp)) :
String.format("%.4g %s", value, abbreviate(unit));
}
private static TimeUnit chooseUnit(long nanos) {
if(SECONDS.convert(nanos, NANOSECONDS) > 0) {
return SECONDS;
}
if(MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
return MILLISECONDS;
}
if(MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
return MICROSECONDS;
}
return NANOSECONDS;
}
private static String abbreviate(TimeUnit unit) {
switch(unit) {
case NANOSECONDS:
return "ns";
case MICROSECONDS:
return "\u03bcs";
case MILLISECONDS:
return "ms";
case SECONDS:
return "s";
default:
return "";
}
}
}
|
package org.cinchapi.concourse.server.storage.db;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import org.cinchapi.concourse.annotate.PackagePrivate;
import org.cinchapi.concourse.server.io.Byteable;
import org.cinchapi.concourse.server.model.PrimaryKey;
import org.cinchapi.concourse.server.model.Text;
import org.cinchapi.concourse.server.model.Value;
import org.cinchapi.concourse.server.storage.Action;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* A wrapper around a collection of Revisions that provides in-memory indices to
* allow efficient reads. All the Revisions in the Record must have the same
* locator. They must also have the same key if the Revision is partial.
*
* @author jnelson
* @param <L> - the locator type
* @param <K> - the key type
* @param <V> - value type
*/
@PackagePrivate
@ThreadSafe
@SuppressWarnings("unchecked")
abstract class Record<L extends Byteable & Comparable<L>, K extends Byteable & Comparable<K>, V extends Byteable & Comparable<V>> {
/**
* Return a PrimaryRecord for {@code primaryKey}.
*
* @param primaryKey
* @return the PrimaryRecord
*/
public static PrimaryRecord createPrimaryRecord(PrimaryKey record) {
return new PrimaryRecord(record, null);
}
/**
* Return a partial PrimaryRecord for {@code key} in {@record}.
*
* @param primaryKey
* @param key
* @return the PrimaryRecord.
*/
public static PrimaryRecord createPrimaryRecordPartial(PrimaryKey record,
Text key) {
return new PrimaryRecord(record, key);
}
/**
* Return a SearchRecord for {@code key}.
*
* @param key
* @return the SearchRecord
*/
public static SearchRecord createSearchRecord(Text key) {
return new SearchRecord(key, null);
}
/**
* Return a partial SearchRecord for {@code term} in {@code key}.
*
* @param key
* @param term
* @return the partial SearchRecord
*/
public static SearchRecord createSearchRecordPartial(Text key, Text term) {
return new SearchRecord(key, term);
}
/**
* Return a SeconaryRecord for {@code key}.
*
* @param key
* @return the SecondaryRecord
*/
public static SecondaryRecord createSecondaryRecord(Text key) {
return new SecondaryRecord(key, null);
}
/**
* Return a partial SecondaryRecord for {@code value} in {@code key}.
*
* @param key
* @param value
* @return the SecondaryRecord
*/
public static SecondaryRecord createSecondaryRecordPartial(Text key,
Value value) {
return new SecondaryRecord(key, value);
}
/**
* The master lock for {@link #write} and {@link #read}. DO NOT use this
* lock directly.
*/
private final ReentrantReadWriteLock master = new ReentrantReadWriteLock();
/**
* An exclusive lock that permits only one writer and no reader. Use this
* lock to ensure that no read occurs while data is being appended to the
* Record.
*/
private final WriteLock write = master.writeLock();
/**
* A shared lock that permits many readers and no writer. Use this lock to
* ensure that no data append occurs while a read is happening within the
* Record.
*/
protected final ReadLock read = master.readLock();
/**
* The index is used to efficiently determine the set of values currently
* mapped from a key. The subclass should specify the appropriate type of
* key sorting via the returned type for {@link #mapType()}.
*/
protected final transient Map<K, Set<V>> present = mapType();
/**
* This index is used to efficiently handle historical reads. Given a
* revision (e.g key/value pair), and historical timestamp, we can count the
* number of times that the value appears <em>beforehand</em> at determine
* if the mapping existed or not.
*/
protected final transient HashMap<K, List<Revision<L, K, V>>> history = Maps
.newHashMap();
/**
* The version of the Record's most recently appended {@link Revision}.
*/
private transient long version = 0;
/**
* The locator used to identify this Record.
*/
private final L locator;
/**
* The key used to identify this Record. This value is {@code null} unless
* {@link #partial} equals {@code true}.
*/
@Nullable
private final K key;
/**
* Indicates that this Record is partial and only contains Revisions for a
* specific {@link #key}.
*/
private final boolean partial;
/**
* This set is returned when a key does not map to any values so that the
* caller can transparently interact without performing checks or
* compromising data consisentcy. This is a member variable (as opposed to
* static constant) that is mocked in the constructor because it has a
* generic type argument.
*/
private final Set<V> emptyValues = new EmptyValueSet();
/**
* Construct a new instance.
*
* @param locator
* @param key
*/
protected Record(L locator, @Nullable K key) {
this.locator = locator;
this.key = key;
this.partial = key == null ? false : true;
}
/**
* Append {@code revision} to the record by updating the in-memory indices.
* The {@code revision} must have:
* <ul>
* <li>a higher version than that of this Record</li>
* <li>a locator equal to that of this Record</li>
* <li>a key equal to that of this Record if this Record is partial</li>
* </ul>
*
* @param revision
*/
public void append(Revision<L, K, V> revision) {
write.lock();
try {
// NOTE: We only need to enforce the monotonic increasing constraint
// for PrimaryRecords because Secondary and Search records will be
// populated from Blocks that were sorted based primarily on
// non-version factors.
Preconditions
.checkArgument((this instanceof PrimaryRecord && revision
.getVersion() >= version) || true, "Cannot "
+ "append %s because its version(%s) is lower "
+ "than the Record's current version(%s). The",
revision, revision.getVersion(), version);
Preconditions.checkArgument(revision.getLocator().equals(locator),
"Cannot append %s because it does not belong "
+ "to this Record", revision);
// NOTE: The check below is ignored for a partial SearchRecord
// instance because they 'key' is the entire search query, but we
// append Revisions for each term in the query
Preconditions.checkArgument(
(partial && revision.getKey().equals(key)) || !partial
|| this instanceof SearchRecord,
"Cannot append %s because it does not "
+ "belong to This Record", revision);
// NOTE: The check below is ignored for a SearchRecord instance
// because it will legitimately appear that "duplicate" data has
// been added if similar data is added to the same key in a record
// at different times (i.e. adding John Doe and Johnny Doe to the
// "name")
Preconditions.checkArgument(this instanceof SearchRecord
|| isOffset(revision), "Cannot append "
+ "%s because it represents an action "
+ "involving a key, value and locator that has not "
+ "been offset.", revision);
// Update present index
Set<V> values = present.get(revision.getKey());
if(values == null) {
values = Sets.<V> newLinkedHashSet();
present.put(revision.getKey(), values);
}
if(revision.getType() == Action.ADD) {
values.add(revision.getValue());
}
else {
values.remove(revision.getValue());
if(values.isEmpty()) {
present.remove(revision.getKey());
}
}
// Update history index
List<Revision<L, K, V>> revisions = history.get(revision.getKey());
if(revisions == null) {
revisions = Lists.newArrayList();
history.put(revision.getKey(), revisions);
}
revisions.add(revision);
// Update metadata
version = Math.max(version, revision.getVersion());
}
finally {
write.unlock();
}
}
@Override
public boolean equals(Object obj) {
if(obj.getClass() == this.getClass()) {
Record<L, K, V> other = (Record<L, K, V>) obj;
return locator.equals(other.locator)
&& (partial ? key.equals(other.key) : true);
}
return false;
}
/**
* Return the Record's version, which is equal to the largest version of an
* appended Revision.
*
* @return the version
*/
public long getVersion() {
return version;
}
@Override
public int hashCode() {
return partial ? Objects.hash(locator, key) : locator.hashCode();
}
/**
* Return {@code true} if this record is partial.
*
* @return {@link #partial}
*/
public boolean isPartial() {
return partial;
}
@Override
public String toString() {
return getClass().getSimpleName() + " " + (partial ? key + " IN " : "")
+ locator;
}
/**
* Lazily retrieve an unmodifiable view of the current set of values mapped
* from {@code key}.
*
* @param key
* @return the set of mapped values for {@code key}
*/
protected Set<V> get(K key) {
read.lock();
try {
return present.containsKey(key) ? Collections
.unmodifiableSet(present.get(key)) : emptyValues;
}
finally {
read.unlock();
}
}
/**
* Lazily retrieve the historical set of values for {@code key} at
* {@code timestamp}.
*
* @param key
* @param timestamp
* @return the set of mapped values for {@code key} at {@code timestamp}.
*/
protected Set<V> get(K key, long timestamp) {
read.lock();
try {
Set<V> values = emptyValues;
if(history.containsKey(key)) {
values = Sets.newLinkedHashSet();
Iterator<Revision<L, K, V>> it = history.get(key).iterator();
while (it.hasNext()) {
Revision<L, K, V> revision = it.next();
if(revision.getVersion() <= timestamp) {
if(revision.getType() == Action.ADD) {
values.add(revision.getValue());
}
else {
values.remove(revision.getValue());
}
}
else {
break;
}
}
}
return values;
}
finally {
read.unlock();
}
}
/**
* Initialize the appropriate data structure for the {@link #present}.
*
* @return the initialized mappings
*/
protected abstract Map<K, Set<V>> mapType();
/**
* Return {@code true} if the action associated with {@code revision}
* offsets the last action for an equal revision.
*
* @param revision
* @return {@code true} if the revision if offset.
*/
private boolean isOffset(Revision<L, K, V> revision) {
return (revision.getType() == Action.ADD && !get(revision.getKey())
.contains(revision.getValue()))
|| (revision.getType() == Action.REMOVE && get(
revision.getKey()).contains(revision.getValue()));
}
/**
* An empty Set of type V that cannot be modified, but won't throw
* exceptions. This returned in instances when a key does not map to any
* values so that the caller can interact with the Set normally without
* performing validity checks and while preserving data consistency.
*
* @author jnelson
*/
private final class EmptyValueSet implements Set<V> {
@Override
public boolean add(V e) {
return false;
}
@Override
public boolean addAll(Collection<? extends V> c) {
return false;
}
@Override
public void clear() {}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public Iterator<V> iterator() {
return Collections.emptyIterator();
}
@Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public int size() {
return 0;
}
@Override
public Object[] toArray() {
return null;
}
@Override
public <T> T[] toArray(T[] a) {
return null;
}
}
}
|
package com.yahoo.container.logging;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
/**
* Produces compact output format for prelude logs
*
* @author Bob Travis
*/
public class LogFormatter extends Formatter {
/** date format objects */
static SimpleDateFormat ddMMMyyyy;
static DateFormat dfMMM;
static SimpleDateFormat yyyyMMdd;
static {
ddMMMyyyy = new SimpleDateFormat("[dd/MMM/yyyy:HH:mm:ss Z]", Locale.US);
ddMMMyyyy.setTimeZone(TimeZone.getTimeZone("UTC"));
dfMMM = new SimpleDateFormat("MMM", Locale.US);
dfMMM.setTimeZone(TimeZone.getTimeZone("UTC"));
yyyyMMdd = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]", Locale.US);
yyyyMMdd.setTimeZone(TimeZone.getTimeZone("UTC"));
}
/** Whether to strip down the message to only the message or not */
private boolean messageOnly = false;
/** Controls which of the available timestamp formats is used in all log records
*/
private static final int timestampFormat = 2; // 0=millis, 1=mm/dd/yyyy, 2=yyyy-mm-dd
/**
* Standard constructor
*/
public LogFormatter() {}
/**
* Make it possible to log stripped messages
*/
public void messageOnly (boolean messageOnly) {
this.messageOnly = messageOnly;
}
public String format(LogRecord record) {
// if we don't want any other stuff we just return the message
if (messageOnly) {
return formatMessage(record);
}
String rawMsg = record.getMessage();
boolean isLogMsg =
rawMsg.charAt(0) == 'L'
&& rawMsg.charAt(1) == 'O'
&& rawMsg.charAt(2) == 'G'
&& rawMsg.charAt(3) == ':';
String nameInsert =
(!isLogMsg)
? record.getLevel().getName() + ": "
: "";
return (timeStamp(record)
+ nameInsert
+ formatMessage(record)
+ "\n"
);
}
/**
* Public support methods
*/
/**
* Static insertDate method will insert date fragments into a string
* based on '%x' pattern elements. Equivalents in SimpleDateFormatter patterns,
* with examples:
* <ul>
* <li>%Y YYYY 2003
* <li>%m MM 08
* <li>%x MMM Aug
* <li>%d dd 25
* <li>%H HH 14
* <li>%M mm 30
* <li>%S ss 35
* <li>%s SSS 123
* <li>%Z Z -0400
* </ul>
*Others:
* <ul>
* <li>%T Long.toString(time)
* <li>%% %
* </ul>
*/
public static String insertDate(String pattern, long time) {
DateFormat df = new SimpleDateFormat("yyyy.MM.dd:HH:mm:ss.SSS Z", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date(time);
String datetime = df.format(date);
StringBuilder result = new StringBuilder();
int i=0;
while (i < pattern.length()) {
int j = pattern.indexOf('%',i);
if (j == -1 || j >= pattern.length()-1) { // done
result.append(pattern.substring(i)); // copy rest of pattern and quit
break;
}
result.append(pattern.substring(i, j));
switch (pattern.charAt(j+1)) {
case 'Y':
result.append(datetime.substring(0,4)); // year
break;
case 'm':
result.append(datetime.substring(5,7)); // month
break;
case 'd':
result.append(datetime.substring(8,10)); // day of month
break;
case 'H':
result.append(datetime.substring(11,13)); // hour
break;
case 'M':
result.append(datetime.substring(14,16)); // minute
break;
case 'S':
result.append(datetime.substring(17,19)); // second
break;
case 's':
result.append(datetime.substring(20,23)); // thousanths
break;
case 'Z':
result.append(datetime.substring(24)); // time zone string
break;
case 'T':
result.append(Long.toString(time)); //time in Millis
break;
case 'x':
result.append(capitalize(dfMMM.format(date)));
break;
case '%':
result.append("%%");
break;
default:
result.append("%"); // copy pattern escape and move on
j--; // only want to bump by one position....
break;
}
i = j+2;
}
return result.toString();
}
/**
* Private methods: timeStamp(LogRecord)
*/
private String timeStamp(LogRecord record) {
Date date = new Date(record.getMillis());
String stamp;
switch (timestampFormat) {
case 0:
stamp = Long.toString(record.getMillis());
break;
case 1:
stamp = ddMMMyyyy.format(date);
break;
case 2:
default:
stamp = yyyyMMdd.format(date);
break;
}
return stamp;
}
/** Return the given string with the first letter in upper case */
private static String capitalize(String string) {
if (Character.isUpperCase(string.charAt(0))) return string;
return Character.toUpperCase(string.charAt(0)) + string.substring(1);
}
}
|
package com.yahoo.prelude.query.parser;
import com.yahoo.prelude.IndexFacts;
import com.yahoo.prelude.query.*;
import com.yahoo.search.query.parser.ParserEnvironment;
import java.util.ArrayList;
import java.util.List;
import static com.yahoo.prelude.query.parser.Token.Kind.*;
/**
* Base class for parsers of the query languages which can be used
* for structured queries (types ANY, ALL and ADVANCED).
*
* @author Steinar Knutsen
* @author bratseth
*/
abstract class StructuredParser extends AbstractParser {
protected StructuredParser(ParserEnvironment environment) {
super(environment);
}
protected abstract Item handleComposite(boolean topLevel);
protected Item compositeItem() {
int position = tokens.getPosition();
Item item = null;
try {
tokens.skipMultiple(PLUS);
if (!tokens.skip(LBRACE)) {
return null;
}
item = handleComposite(false);
tokens.skip(RBRACE);
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
/** Sets the submodes used for url parsing. Override this to influence when such submodes are used. */
protected void setSubmodeFromIndex(String indexName, IndexFacts.Session indexFacts) {
submodes.setFromIndex(indexName, indexFacts);
}
protected Item indexableItem() {
int position = tokens.getPosition();
Item item = null;
try {
String indexName = indexPrefix();
setSubmodeFromIndex(indexName, indexFacts);
item = number();
if (item == null) {
item = phrase(indexName);
}
if (item == null && indexName != null) {
if (wordsAhead()) {
item = phrase(indexName);
}
}
submodes.reset();
int weight = -1;
if (item != null) {
weight = weightSuffix();
}
if (indexName != null && item != null) {
item.setIndexName(indexName);
}
if (weight != -1 && item != null) {
item.setWeight(weight);
}
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
// scan forward for terms while ignoring noise
private boolean wordsAhead() {
while (tokens.hasNext()) {
if (tokens.currentIsNoIgnore(SPACE)) {
return false;
}
if (tokens.currentIsNoIgnore(NUMBER)
|| tokens.currentIsNoIgnore(WORD)) {
return true;
}
tokens.skipNoIgnore();
}
return false;
}
// wordsAhead and nothingAhead... uhm... so similar...
private boolean nothingAhead(boolean skip) {
int position = tokens.getPosition();
try {
boolean quoted = false;
while (tokens.hasNext()) {
if (tokens.currentIsNoIgnore(QUOTE)) {
tokens.skipMultiple(QUOTE);
quoted = !quoted;
} else {
if (!quoted && tokens.currentIsNoIgnore(SPACE)) {
return true;
}
if (tokens.currentIsNoIgnore(NUMBER)
|| tokens.currentIsNoIgnore(WORD)) {
return false;
}
tokens.skipNoIgnore();
}
}
return true;
} finally {
if (!skip) {
tokens.setPosition(position);
}
}
}
private String indexPrefix() {
int position = tokens.getPosition();
String item = null;
try {
List<Token> firstWord = new ArrayList<>();
List<Token> secondWord = new ArrayList<>();
tokens.skip(LSQUAREBRACKET);
if ( ! tokens.currentIs(WORD) && ! tokens.currentIs(NUMBER) && ! tokens.currentIs(UNDERSCORE)) {
return null;
}
firstWord.add(tokens.next());
while (tokens.currentIsNoIgnore(UNDERSCORE)
|| tokens.currentIsNoIgnore(WORD)
|| tokens.currentIsNoIgnore(NUMBER)) {
firstWord.add(tokens.next());
}
while (tokens.currentIsNoIgnore(DOT)) {
secondWord.add(tokens.next());
if (tokens.currentIsNoIgnore(WORD) || tokens.currentIsNoIgnore(NUMBER)) {
secondWord.add(tokens.next());
} else {
return null;
}
while (tokens.currentIsNoIgnore(UNDERSCORE)
|| tokens.currentIsNoIgnore(WORD)
|| tokens.currentIsNoIgnore(NUMBER)) {
secondWord.add(tokens.next());
}
}
if ( ! tokens.skipNoIgnore(COLON))
return null;
item = concatenate(firstWord) + concatenate(secondWord);
item = indexFacts.getCanonicName(item);
if ( ! indexFacts.isIndex(item)) { // Only if this really is an index
// Marker for the finally block
item = null;
return null;
} else {
if (nothingAhead(false)) {
// correct index syntax, correct name, but followed by noise. Let's skip this.
nothingAhead(true);
position = tokens.getPosition();
item = indexPrefix();
}
}
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
private String concatenate(List<Token> tokens) {
StringBuilder s = new StringBuilder();
for (Token t : tokens) {
s.append(t.toString());
}
return s.toString();
}
/** Returns the specified term weight, or -1 if there is no weight suffix */
private int weightSuffix() {
int position = tokens.getPosition();
int item = -1;
try {
if (!tokens.skipNoIgnore(EXCLAMATION)) {
return -1;
}
item = 150;
if (tokens.currentIsNoIgnore(NUMBER)) {
try {
item = Integer.parseInt(tokens.next().toString());
} catch (NumberFormatException e) {
item = -1;
}
} else {
while (tokens.currentIsNoIgnore(EXCLAMATION)) {
item += 50;
tokens.skipNoIgnore();
}
}
return item;
} finally {
if (item == -1) {
tokens.setPosition(position);
}
}
}
private boolean endOfNumber() {
return tokens.currentIsNoIgnore(SPACE)
|| tokens.currentIsNoIgnore(RSQUAREBRACKET)
|| tokens.currentIsNoIgnore(SEMICOLON)
|| tokens.currentIsNoIgnore(RBRACE)
|| tokens.currentIsNoIgnore(EOF)
|| tokens.currentIsNoIgnore(EXCLAMATION);
}
private String decimalPart() {
int position = tokens.getPosition();
boolean consumed = false;
try {
if (!tokens.skipNoIgnore(DOT)) return "";
if (tokens.currentIsNoIgnore(NUMBER)) {
consumed = true;
return "." + tokens.next().toString();
}
return "";
} finally {
if ( ! consumed)
tokens.setPosition(position);
}
}
private IntItem number() {
int position = tokens.getPosition();
IntItem item = null;
try {
item = numberRange();
tokens.skip(LSQUAREBRACKET);
if (item == null)
tokens.skipNoIgnore(SPACE);
// TODO: Better definition of start and end of numeric items
if (item == null && tokens.currentIsNoIgnore(MINUS) && (tokens.currentNoIgnore(1).kind == NUMBER)) {
tokens.skipNoIgnore();
Token t = tokens.next();
item = new IntItem("-" + t.toString() + decimalPart(), true);
item.setOrigin(t.substring);
} else if (item == null && tokens.currentIs(NUMBER)) {
Token t = tokens.next();
item = new IntItem(t.toString() + decimalPart(), true);
item.setOrigin(t.substring);
}
if (item == null) {
item = numberSmaller();
}
if (item == null) {
item = numberGreater();
}
if (item != null && ! endOfNumber()) {
item = null;
}
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
private IntItem numberRange() {
int position = tokens.getPosition();
IntItem item = null;
try {
Token initial = tokens.next();
if (initial.kind != LSQUAREBRACKET) return null;
String rangeStart = "";
boolean negative = tokens.skip(MINUS);
if (tokens.currentIs(NUMBER)) {
rangeStart = (negative ? "-" : "") + tokens.next().toString() + decimalPart();
}
if (!tokens.skip(SEMICOLON)) return null;
String rangeEnd = "";
negative = tokens.skip(MINUS);
if (tokens.currentIs(NUMBER)) {
rangeEnd = (negative ? "-" : "") + tokens.next().toString() + decimalPart();
}
String range = "[" + rangeStart + ";" + rangeEnd;
if (tokens.skip(SEMICOLON)) {
negative = tokens.skip(MINUS);
if (tokens.currentIs(NUMBER)) {
String rangeLimit = (negative ? "-" : "") + tokens.next().toString();
range += ";" + rangeLimit;
}
}
tokens.skip(RSQUAREBRACKET);
item = new IntItem(range + "]", true);
item.setOrigin(new Substring(initial.substring.start, tokens.currentNoIgnore().substring.start,
initial.getSubstring().getSuperstring())); // XXX: Unsafe end?
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
private IntItem numberSmaller() {
int position = tokens.getPosition();
IntItem item = null;
try {
Token initial = tokens.next();
if (initial.kind != SMALLER) return null;
boolean negative = tokens.skipNoIgnore(MINUS);
if ( ! tokens.currentIs(NUMBER)) return null;
item = new IntItem("<" + (negative ? "-" : "") + tokens.next() + decimalPart(), true);
item.setOrigin(new Substring(initial.substring.start, tokens.currentNoIgnore().substring.start,
initial.getSubstring().getSuperstring())); // XXX: Unsafe end?
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
private IntItem numberGreater() {
int position = tokens.getPosition();
IntItem item = null;
try {
Token initial = tokens.next();
if (initial.kind != GREATER) return null;
boolean negative = tokens.skipNoIgnore(MINUS);
if ( ! tokens.currentIs(NUMBER)) return null;
item = new IntItem(">" + (negative ? "-" : "") + tokens.next() + decimalPart(), true);
item.setOrigin(new Substring(initial.substring.start, tokens.currentNoIgnore().substring.start,
initial.getSubstring().getSuperstring())); // XXX: Unsafe end?
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
/**
* Words for phrases also permits numerals as words
*
* @param quoted whether we are consuming text within quoted
* @param insidePhrase whether we are consuming additional items for an existing phrase
*/
private Item phraseWord(String indexName, boolean quoted, boolean insidePhrase) {
int position = tokens.getPosition();
Item item = null;
try {
item = word(indexName, quoted);
if (item == null && tokens.currentIs(NUMBER)) {
Token t = tokens.next();
if (insidePhrase) {
item = new WordItem(t, true);
} else {
item = new IntItem(t.toString(), true);
((TermItem) item).setOrigin(t.substring);
}
}
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
/**
* Returns a WordItem if this is a non CJK query,
* a WordItem or SegmentItem if this is a CJK query,
* null if the current item is not a word
*
* @param quoted whether this token is inside quotes
*/
protected Item word(String indexName, boolean quoted) {
int position = tokens.getPosition();
Item item = null;
try {
if ( ! tokens.currentIs(WORD)
&& ((!tokens.currentIs(NUMBER) && !tokens.currentIs(MINUS)
&& !tokens.currentIs(UNDERSCORE)) || (!submodes.url && !submodes.site))) {
return null;
}
Token word = tokens.next();
if (submodes.url) {
item = new WordItem(word, true);
} else {
item = segment(indexName, word, quoted);
}
if (submodes.url || submodes.site) {
StringBuilder buffer = null;
Token token = tokens.currentNoIgnore();
while (token.kind == WORD || token.kind == NUMBER || token.kind == MINUS || token.kind == UNDERSCORE) {
if (buffer == null) {
buffer = getStringContents(item);
}
buffer.append(token);
tokens.skipNoIgnore();
token = tokens.currentNoIgnore();
}
if (buffer != null) {
Substring termSubstring = ((BlockItem) item).getOrigin();
Substring substring = new Substring(termSubstring.start, token.substring.start, termSubstring.getSuperstring()); // XXX: Unsafe end?
String str = buffer.toString();
item = new WordItem(str, "", true, substring);
}
}
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
private StringBuilder getStringContents(Item item) {
if (item instanceof TermItem) {
return new StringBuilder(
((TermItem) item).stringValue());
} else if (item instanceof SegmentItem) {
return new StringBuilder(
((SegmentItem) item).getRawWord());
} else {
throw new RuntimeException("Parser bug. Unexpected item type, send stack trace in a bug ticket to the Vespa team.");
}
}
/**
* An phrase or word, either marked by quotes or by non-spaces between
* words or by a combination.
*
* @param indexName the index name which preceeded this phrase, or null if none
* @return a word if there's only one word, a phrase if there is
* several quoted or non-space-separated words, or null otherwise
*/
private Item phrase(String indexName) {
int position = tokens.getPosition();
Item item = null;
try {
item = phraseBody(indexName);
return item;
} finally {
if (item == null) {
tokens.setPosition(position);
}
}
}
/** Returns a word, a phrase, or another composite */
private Item phraseBody(String indexName) {
boolean quoted = false;
CompositeItem composite = null;
Item firstWord = null;
boolean starAfterFirst = false;
boolean starBeforeFirst;
if (tokens.skipMultiple(QUOTE)) {
quoted = !quoted;
}
boolean addStartOfHostMarker = addStartMarking();
braceLevelURL = 0;
do {
starBeforeFirst = tokens.skip(STAR);
if (tokens.skipMultiple(QUOTE)) {
quoted = !quoted;
}
Item word = phraseWord(indexName, quoted, (firstWord != null) || (composite != null));
if (word == null) {
if (tokens.skipMultiple(QUOTE)) {
quoted = !quoted;
}
if (quoted && tokens.hasNext()) {
tokens.skipNoIgnore();
continue;
} else {
break;
}
} else if (quoted && word instanceof PhraseSegmentItem) {
((PhraseSegmentItem) word).setExplicit(true);
}
if (composite != null) {
composite.addItem(word);
connectLastTermsIn(composite);
} else if (firstWord != null) {
if (submodes.site || submodes.url) {
UriItem uriItem = new UriItem();
if (submodes.site)
uriItem.setEndAnchorDefault(true);
composite = uriItem;
}
else {
if (quoted || indexFacts.getIndex(indexName).getPhraseSegmenting())
composite = new PhraseItem();
else
composite = new AndItem();
}
if ( (quoted || submodes.site || submodes.url) && composite instanceof PhraseItem) {
((PhraseItem)composite).setExplicit(true);
}
if (addStartOfHostMarker) {
composite.addItem(MarkerWordItem.createStartOfHost());
}
if (firstWord instanceof IntItem) {
IntItem asInt = (IntItem) firstWord;
firstWord = new WordItem(asInt.stringValue(), asInt.getIndexName(),
true, asInt.getOrigin());
}
composite.addItem(firstWord);
composite.addItem(word);
connectLastTermsIn(composite);
} else if (word instanceof PhraseItem) {
composite = (PhraseItem)word;
} else {
firstWord = word;
starAfterFirst = tokens.skipNoIgnore(STAR);
}
if (!quoted && tokens.currentIs(QUOTE)) {
break;
}
boolean atWord = skipToNextPhraseWord(quoted);
if (!atWord && tokens.skipMultipleNoIgnore(QUOTE)) {
quoted = !quoted;
}
if (!atWord && !quoted) {
break;
}
if (quoted && tokens.skipMultiple(QUOTE)) {
break;
}
} while (tokens.hasNext());
braceLevelURL = 0;
if (composite != null) {
if (addEndMarking()) {
composite.addItem(MarkerWordItem.createEndOfHost());
}
return composite;
} else if (firstWord != null && submodes.site) {
if (starAfterFirst && !addStartOfHostMarker) {
return firstWord;
} else {
composite = new PhraseItem();
((PhraseItem)composite).setExplicit(true);
if (addStartOfHostMarker) {
composite.addItem(MarkerWordItem.createStartOfHost());
}
if (firstWord instanceof IntItem) {
IntItem asInt = (IntItem) firstWord;
firstWord = new WordItem(asInt.stringValue(), asInt.getIndexName(), true, asInt.getOrigin());
}
composite.addItem(firstWord);
if (!starAfterFirst) {
composite.addItem(MarkerWordItem.createEndOfHost());
}
return composite;
}
} else {
if (firstWord != null && firstWord instanceof TermItem && (starAfterFirst || starBeforeFirst)) {
// prefix, suffix or substring
TermItem firstTerm = (TermItem) firstWord;
if (starAfterFirst) {
if (starBeforeFirst) {
return new SubstringItem(firstTerm.stringValue(), true);
} else {
return new PrefixItem(firstTerm.stringValue(), true);
}
} else {
return new SuffixItem(firstTerm.stringValue(), true);
}
}
return firstWord;
}
}
private void connectLastTermsIn(CompositeItem composite) {
int items = composite.items().size();
if (items < 2) return;
Item nextToLast = composite.items().get(items - 2);
if (nextToLast instanceof AndSegmentItem) {
var subItems = ((AndSegmentItem) nextToLast).items();
nextToLast = subItems.get(subItems.size() - 1);
}
if ( ! (nextToLast instanceof TermItem)) return;
Item last = composite.items().get(items - 1);
if (last instanceof AndSegmentItem) {
last = ((AndSegmentItem) last).items().get(0);
}
if (last instanceof TaggableItem) {
TermItem t1 = (TermItem) nextToLast;
t1.setConnectivity(last, 1);
}
}
private boolean addStartMarking() {
if (submodes.explicitAnchoring() && tokens.currentIs(HAT)) {
tokens.skip();
return true;
}
return false;
}
private boolean addEndMarking() {
if (submodes.explicitAnchoring() && tokens.currentIs(DOLLAR)) {
tokens.skip();
return true;
} else if (submodes.site && tokens.currentIs(STAR)) {
tokens.skip();
return false;
} else if (submodes.site && !tokens.currentIs(DOT)) {
return true;
}
return false;
}
/**
* Skips one or multiple phrase separators
*
* @return true if the item we land at after skipping zero or more is
* a phrase word
*/
private boolean skipToNextPhraseWord(boolean quoted) {
boolean skipped = false;
do {
skipped = false;
if (submodes.url) {
if (tokens.currentIsNoIgnore(RBRACE)) {
braceLevelURL
}
if (tokens.currentIsNoIgnore(LBRACE)) {
braceLevelURL++;
}
if (tokens.hasNext() && !tokens.currentIsNoIgnore(SPACE) && braceLevelURL >= 0) {
tokens.skip();
skipped = true;
}
} else if (submodes.site) {
if (tokens.hasNext() && !tokens.currentIsNoIgnore(SPACE)
&& !tokens.currentIsNoIgnore(STAR)
&& !tokens.currentIsNoIgnore(HAT)
&& !tokens.currentIsNoIgnore(DOLLAR)
&& !tokens.currentIsNoIgnore(RBRACE)) {
tokens.skip();
skipped = true;
}
} else {
if (tokens.skipMultipleNoIgnore(DOT)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(COMMA)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(PLUS)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(MINUS)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(UNDERSCORE)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(HAT)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(DOLLAR)) {
skipped = true;
}
;
if (tokens.skipMultipleNoIgnore(STAR)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(COLON)) {
skipped = true;
}
if (quoted) {
if (tokens.skipMultipleNoIgnore(RBRACE)) {
skipped = true;
}
if (tokens.skipMultipleNoIgnore(LBRACE)) {
skipped = true;
}
}
if (tokens.skipMultipleNoIgnore(NOISE)) {
skipped = true;
}
}
} while (skipped && !tokens.currentIsNoIgnore(WORD)
&& !tokens.currentIsNoIgnore(NUMBER) && !URLModeWordChar());
return tokens.currentIsNoIgnore(WORD)
|| tokens.currentIsNoIgnore(NUMBER) || URLModePhraseChar();
}
private boolean URLModeWordChar() {
if (!submodes.url) {
return false;
}
return tokens.currentIsNoIgnore(UNDERSCORE)
|| tokens.currentIsNoIgnore(MINUS);
}
private boolean URLModePhraseChar() {
if (!submodes.url) {
return false;
}
return !(tokens.currentIsNoIgnore(RBRACE)
|| tokens.currentIsNoIgnore(SPACE));
}
}
|
package com.yahoo.prelude.statistics;
import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.concurrent.CopyOnWriteHashMap;
import com.yahoo.container.Server;
import com.yahoo.container.protect.Error;
import com.yahoo.jdisc.Metric;
import com.yahoo.log.LogLevel;
import com.yahoo.metrics.simple.MetricSettings;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.processing.request.CompoundName;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Coverage;
import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.PhaseNames;
import com.yahoo.statistics.Callback;
import com.yahoo.statistics.Counter;
import com.yahoo.statistics.Handle;
import com.yahoo.statistics.Value;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import static com.yahoo.container.protect.Error.*;
/**
* <p>A searcher to gather statistics such as queries completed and query latency. There
* may be more than 1 StatisticsSearcher in the Searcher chain, each identified by a
* Searcher ID. The statistics accumulated by all StatisticsSearchers are stored
* in the singleton StatisticsManager object. </p>
* <p>
* TODO: Fix events to handle more than one of these searchers properly.
*
* @author Gene Meyers
* @author Steinar Knutsen
* @author bergum
*/
@Before(PhaseNames.RAW_QUERY)
public class StatisticsSearcher extends Searcher {
private static final CompoundName IGNORE_QUERY = new CompoundName("metrics.ignore");
private static final String MAX_QUERY_LATENCY_METRIC = "max_query_latency";
private static final String EMPTY_RESULTS_METRIC = "empty_results";
private static final String HITS_PER_QUERY_METRIC = "hits_per_query";
private static final String TOTALHITS_PER_QUERY_METRIC = "totalhits_per_query";
private static final String FAILED_QUERIES_METRIC = "failed_queries";
private static final String MEAN_QUERY_LATENCY_METRIC = "mean_query_latency";
private static final String QUERY_LATENCY_METRIC = "query_latency";
private static final String QUERIES_METRIC = "queries";
private static final String ACTIVE_QUERIES_METRIC = "active_queries";
private static final String PEAK_QPS_METRIC = "peak_qps";
private static final String COVERAGE_METRIC = "coverage_per_query";
private static final String DEGRADED_METRIC = "degraded_queries";
private final Counter queries; // basic counter
private final Counter failedQueries; // basic counter
private final Counter nullQueries; // basic counter
private final Counter illegalQueries; // basic counter
private final Value queryLatency; // mean pr 5 min
private final Value queryLatencyBuckets;
private final Value maxQueryLatency; // separate to avoid name mangling
@SuppressWarnings("unused") // all the work is done by the callback
private final Value activeQueries; // raw measure every 5 minutes
private final Value peakQPS; // peak 1s QPS
private final Counter emptyResults; // number of results containing no concrete hits
private final Value hitsPerQuery; // mean number of hits per query
private final PeakQpsReporter peakQpsReporter;
// Naming of enums are reflected directly in metric dimensions and should not be changed as they are public API
private enum DegradedReason { match_phase, adaptive_timeout, timeout, non_ideal_state }
private Metric metric;
private Map<String, Metric.Context> chainContexts = new CopyOnWriteHashMap<>();
private Map<String, Metric.Context> statePageOnlyContexts = new CopyOnWriteHashMap<>();
private Map<String, Map<DegradedReason, Metric.Context>> degradedReasonContexts = new CopyOnWriteHashMap<>();
private java.util.Timer scheduler = new java.util.Timer(true);
// Callback to measure queries in flight every five minutes
private class ActivitySampler implements Callback {
public void run(Handle h, boolean firstRun) {
if (firstRun) {
metric.set(ACTIVE_QUERIES_METRIC, 0, null);
return;
}
// TODO Server.get() is to be removed
int searchQueriesInFlight = Server.get().searchQueriesInFlight();
((Value) h).put(searchQueriesInFlight);
metric.set(ACTIVE_QUERIES_METRIC, searchQueriesInFlight, null);
}
}
private class PeakQpsReporter extends java.util.TimerTask {
private long prevMaxQPSTime = System.currentTimeMillis();
private long queriesForQPS = 0;
private Metric.Context metricContext = null;
public void setContext(Metric.Context metricContext) {
if (this.metricContext == null) {
synchronized(this) {
this.metricContext = metricContext;
}
}
}
@Override
public void run() {
long now = System.currentTimeMillis();
synchronized (this) {
if (metricContext == null) return;
flushPeakQps(now);
}
}
private void flushPeakQps(long now) {
double ms = (double) (now - prevMaxQPSTime);
final double value = ((double)queriesForQPS) / (ms / 1000.0);
peakQPS.put(value);
metric.set(PEAK_QPS_METRIC, value, metricContext);
prevMaxQPSTime = now;
queriesForQPS = 0;
}
void countQuery() {
synchronized (this) {
++queriesForQPS;
}
}
}
public StatisticsSearcher(com.yahoo.statistics.Statistics manager, Metric metric, MetricReceiver metricReceiver) {
this.peakQpsReporter = new PeakQpsReporter();
this.metric = metric;
queries = new Counter(QUERIES_METRIC, manager, false);
failedQueries = new Counter(FAILED_QUERIES_METRIC, manager, false);
nullQueries = new Counter("null_queries", manager, false);
illegalQueries = new Counter("illegal_queries", manager, false);
queryLatency = new Value(MEAN_QUERY_LATENCY_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMean(true).setNameExtension(false));
maxQueryLatency = new Value(MAX_QUERY_LATENCY_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMax(true).setNameExtension(false));
queryLatencyBuckets = Value.buildValue(QUERY_LATENCY_METRIC, manager, null);
activeQueries = new Value(ACTIVE_QUERIES_METRIC, manager, new Value.Parameters().setLogRaw(true).setCallback(new ActivitySampler()));
peakQPS = new Value(PEAK_QPS_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMax(true).setNameExtension(false));
hitsPerQuery = new Value(HITS_PER_QUERY_METRIC, manager, new Value.Parameters().setLogRaw(false).setLogMean(true).setNameExtension(false));
emptyResults = new Counter(EMPTY_RESULTS_METRIC, manager, false);
metricReceiver.declareGauge(QUERY_LATENCY_METRIC, Optional.empty(), new MetricSettings.Builder().histogram(true).build());
scheduler.schedule(peakQpsReporter, 1000, 1000);
}
@Override
public void deconstruct() {
scheduler.cancel();
}
private void qps(Metric.Context metricContext) {
peakQpsReporter.setContext(metricContext);
peakQpsReporter.countQuery();
}
private Metric.Context getChainMetricContext(String chainName) {
Metric.Context context = chainContexts.get(chainName);
if (context == null) {
Map<String, String> dimensions = new HashMap<>();
dimensions.put("chain", chainName);
context = this.metric.createContext(dimensions);
chainContexts.put(chainName, context);
}
return context;
}
private Metric.Context getDegradedMetricContext(String chainName, Coverage coverage) {
Map<DegradedReason, Metric.Context> reasons = degradedReasonContexts.get(chainName);
if (reasons == null) {
reasons = new HashMap<>(4);
for (DegradedReason reason : DegradedReason.values() ) {
Map<String, String> dimensions = new HashMap<>();
dimensions.put("chain", chainName);
dimensions.put("reason", reason.toString());
Metric.Context context = this.metric.createContext(dimensions);
reasons.put(reason, context);
}
degradedReasonContexts.put(chainName, reasons);
}
return reasons.get(getMostImportantDegradeReason(coverage));
}
private DegradedReason getMostImportantDegradeReason(Coverage coverage) {
if (coverage.isDegradedByMatchPhase()) {
return DegradedReason.match_phase;
}
if (coverage.isDegradedByTimeout()) {
return DegradedReason.timeout;
}
if (coverage.isDegradedByAdapativeTimeout()) {
return DegradedReason.adaptive_timeout;
}
return DegradedReason.non_ideal_state;
}
/**
* Generate statistics for the query passing through this Searcher
* 1) Add 1 to total query count
* 2) Add response time to total response time (time from entry to return)
* 3) .....
*/
public Result search(com.yahoo.search.Query query, Execution execution) {
if (query.properties().getBoolean(IGNORE_QUERY,false)) {
return execution.search(query);
}
Metric.Context metricContext = getChainMetricContext(execution.chain().getId().stringValue());
incrQueryCount(metricContext);
logQuery(query);
long start = System.currentTimeMillis(); // Start time, in millisecs.
qps(metricContext);
Result result;
//handle exceptions thrown below in searchers
try {
result = execution.search(query); // Pass on down the chain
} catch (Exception e) {
incrErrorCount(null, metricContext);
throw e;
}
long end = System.currentTimeMillis(); // Start time, in millisecs.
long latency = end - start;
if (latency >= 0) {
addLatency(latency, metricContext);
} else {
getLogger().log(LogLevel.WARNING,
"Apparently negative latency measure, start: " + start
+ ", end: " + end + ", for query: " + query.toString());
}
if (result.hits().getError() != null) {
incrErrorCount(result, metricContext);
incrementStatePageOnlyErrors(result);
}
Coverage queryCoverage = result.getCoverage(false);
if (queryCoverage.isDegraded()) {
Metric.Context degradedContext = getDegradedMetricContext(execution.chain().getId().stringValue(), queryCoverage);
metric.add(DEGRADED_METRIC, 1, degradedContext);
}
int hitCount = result.getConcreteHitCount();
hitsPerQuery.put((double) hitCount);
metric.set(COVERAGE_METRIC, (double) queryCoverage.getResultPercentage(), metricContext);
metric.set(HITS_PER_QUERY_METRIC, (double) hitCount, metricContext);
metric.set(TOTALHITS_PER_QUERY_METRIC, (double) result.getTotalHitCount(), metricContext);
if (hitCount == 0) {
emptyResults.increment();
metric.add(EMPTY_RESULTS_METRIC, 1, metricContext);
}
// Update running averages
//setAverages();
return result;
}
private void logQuery(com.yahoo.search.Query query) {
// Don't parse the query if it's not necessary for the logging Query.toString triggers parsing
if (getLogger().isLoggable(Level.FINER)) {
getLogger().finer("Query: " + query.toString());
}
}
private void addLatency(long latency, Metric.Context metricContext) {
//myStats.addLatency(latency);
queryLatency.put(latency);
metric.set(QUERY_LATENCY_METRIC, latency, metricContext);
metric.set(MEAN_QUERY_LATENCY_METRIC, latency, metricContext);
maxQueryLatency.put(latency);
metric.set(MAX_QUERY_LATENCY_METRIC, latency, metricContext);
queryLatencyBuckets.put(latency);
}
private void incrQueryCount(Metric.Context metricContext) {
//myStats.incrQueryCnt();
queries.increment();
metric.add(QUERIES_METRIC, 1, metricContext);
}
private void incrErrorCount(Result result, Metric.Context metricContext) {
failedQueries.increment();
metric.add(FAILED_QUERIES_METRIC, 1, metricContext);
if (result == null) // the chain threw an exception
metric.add("error.unhandled_exception", 1, metricContext);
else if (result.hits().getErrorHit().hasOnlyErrorCode(Error.NULL_QUERY.code))
nullQueries.increment();
else if (result.hits().getErrorHit().hasOnlyErrorCode(Error.ILLEGAL_QUERY.code))
illegalQueries.increment();
}
/**
* Creates error metric for StateHandler only. These metrics are only exposed on /state/v1/metrics page
* and not forwarded to the log file.
*
* @param result The result to check for errors
*/
private void incrementStatePageOnlyErrors(Result result) {
if (result == null) return;
ErrorHit error = result.hits().getErrorHit();
if (error == null) return;
for (ErrorMessage m : error.errors()) {
int code = m.getCode();
Metric.Context c = getDimensions(m.getSource());
if (code == TIMEOUT.code) {
metric.add("error.timeout", 1, c);
} else if (code == NO_BACKENDS_IN_SERVICE.code) {
metric.add("error.backends_oos", 1, c);
} else if (code == ERROR_IN_PLUGIN.code) {
metric.add("error.plugin_failure", 1, c);
} else if (code == BACKEND_COMMUNICATION_ERROR.code) {
metric.add("error.backend_communication_error", 1, c);
} else if (code == EMPTY_DOCUMENTS.code) {
metric.add("error.empty_document_summaries", 1, c);
} else if (code == ILLEGAL_QUERY.code) {
metric.add("error.illegal_query", 1, c);
} else if (code == INVALID_QUERY_PARAMETER.code) {
metric.add("error.invalid_query_parameter", 1, c);
} else if (code == INTERNAL_SERVER_ERROR.code) {
metric.add("error.internal_server_error", 1, c);
} else if (code == SERVER_IS_MISCONFIGURED.code) {
metric.add("error.misconfigured_server", 1, c);
} else if (code == INVALID_QUERY_TRANSFORMATION.code) {
metric.add("error.invalid_query_transformation", 1, c);
} else if (code == RESULT_HAS_ERRORS.code) {
metric.add("error.result_with_errors", 1, c);
} else if (code == UNSPECIFIED.code) {
metric.add("error.unspecified", 1, c);
}
}
}
private Metric.Context getDimensions(String source) {
Metric.Context context = statePageOnlyContexts.get(source == null ? "" : source);
if (context == null) {
Map<String, String> dims = new HashMap<>();
if (source != null) {
dims.put("source", source);
}
context = this.metric.createContext(dims);
statePageOnlyContexts.put(source == null ? "" : source, context);
}
// TODO add other relevant metric dimensions
// Would be nice to have chain as a dimension as
// we can separate errors from different chains
return context;
}
}
|
package com.yahoo.search.dispatch.rpc;
import com.yahoo.prelude.Pong;
import com.yahoo.prelude.fastsearch.DocumentDatabase;
import com.yahoo.prelude.fastsearch.VespaBackEndSearcher;
import com.yahoo.processing.request.CompoundName;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.cluster.ClusterMonitor;
import com.yahoo.search.dispatch.Dispatcher;
import com.yahoo.search.dispatch.FillInvoker;
import com.yahoo.search.dispatch.InvokerFactory;
import com.yahoo.search.dispatch.SearchInvoker;
import com.yahoo.search.dispatch.searchcluster.Node;
import com.yahoo.search.dispatch.searchcluster.PingFactory;
import com.yahoo.search.dispatch.searchcluster.SearchCluster;
import java.util.Optional;
import java.util.concurrent.Callable;
/**
* @author ollivir
*/
public class RpcInvokerFactory extends InvokerFactory implements PingFactory {
/** Unless turned off this will fill summaries by dispatching directly to search nodes over RPC when possible */
private final static CompoundName dispatchSummaries = new CompoundName("dispatch.summaries");
private final RpcResourcePool rpcResourcePool;
private final boolean dispatchWithProtobuf;
public RpcInvokerFactory(RpcResourcePool rpcResourcePool, SearchCluster searchCluster, boolean dispatchWithProtobuf) {
super(searchCluster);
this.rpcResourcePool = rpcResourcePool;
this.dispatchWithProtobuf = dispatchWithProtobuf;
}
@Override
protected Optional<SearchInvoker> createNodeSearchInvoker(VespaBackEndSearcher searcher, Query query, Node node) {
return Optional.of(new RpcSearchInvoker(searcher, node, rpcResourcePool));
}
@Override
public Optional<FillInvoker> createFillInvoker(VespaBackEndSearcher searcher, Result result) {
Query query = result.getQuery();
boolean summaryNeedsQuery = searcher.summaryNeedsQuery(query);
boolean useProtoBuf = query.properties().getBoolean(Dispatcher.dispatchProtobuf, dispatchWithProtobuf);
return ((query.properties().getBoolean(dispatchSummaries, true) || !useProtoBuf) && ! summaryNeedsQuery)
? Optional.of(new RpcFillInvoker(rpcResourcePool, searcher.getDocumentDatabase(query)))
: Optional.of(new RpcProtobufFillInvoker(rpcResourcePool, searcher.getDocumentDatabase(query), searcher.getServerId(), summaryNeedsQuery));
}
// for testing
public FillInvoker createFillInvoker(DocumentDatabase documentDb) {
return new RpcFillInvoker(rpcResourcePool, documentDb);
}
public void release() {
rpcResourcePool.release();
}
@Override
public Callable<Pong> createPinger(Node node, ClusterMonitor<Node> monitor) {
return new RpcPing(node, monitor, rpcResourcePool);
}
}
|
package org.arakhne.afc.math.geometry.d3.continuous;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.arakhne.afc.math.AbstractMathTestCase;
import org.arakhne.afc.math.geometry.d3.Point3D;
import org.junit.Test;
@SuppressWarnings("static-method")
public class Path3fTest extends AbstractMathTestCase {
/** Testing the intersection between the path and an AlignedBox3f
*/
@Test
public void intersectsAlignedBox() {
Path3f r = new Path3f();
r.moveTo(0f, 0f, 0f);
r.lineTo(1f, 1f, 1f);
r.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
r.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
r.closePath();
AlignedBox3f aB = new AlignedBox3f(new Point3f(0f,0f,0f),new Point3f(2f,2f,2f));
AlignedBox3f aB2 = new AlignedBox3f(new Point3f(-1f,-1f,-1f),new Point3f(-2f,-2f,-2f));
assertTrue(r.intersects(aB));
assertFalse(r.intersects(aB2));
}
@Test
public void intersectsPath() {
Path3f r = new Path3f();
r.moveTo(0f, 0f, 0f);
r.lineTo(1f, 1f, 1f);
r.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
r.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
r.closePath();
Transform3D t = new Transform3D();
Path3f rTrans = new Path3f();
rTrans.moveTo(0f, 0f, 0f);
rTrans.lineTo(-12f, 19f, 0f);
rTrans.closePath();
assertTrue(r.intersects(r));
assertTrue(rTrans.intersects(r));
t.makeTranslationMatrix(10, 10, 10);
rTrans.transform(t);
//System.out.println(rTrans.toString());
assertFalse(rTrans.intersects(r));
}
@Test
public void intersectsSphere() {
Path3f r = new Path3f();
r.moveTo(0f, 0f, 0f);
r.lineTo(1f, 1f, 1f);
r.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
r.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
r.closePath();
AbstractSphere3F sfere = new Sphere3f(new Point3f(0.5f,0.5f,0.5f),5f);
assertTrue(r.intersects(sfere));
AbstractSphere3F sfere2 = new Sphere3f(new Point3f(20f,20f,20f),0.001);
assertFalse(r.intersects(sfere2));
}
@Test
public void intersectsSegment() {
Path3f r = new Path3f();
r.moveTo(0f, 0f, 0f);
r.lineTo(1f, 1f, 1f);
r.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
r.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
r.closePath();
AbstractSegment3F segm = new Segment3f(1,0,1,0,0,0);
AbstractSegment3F s = new Segment3f(1,0,0,0,0,1);
AbstractSegment3F segm2 = new Segment3f(new Point3f(20f,20f,20f),new Point3f(30f,30f,30f));
AbstractSegment3F s2 = new Segment3f(-1,-1,-1,8,-4,1);
assertTrue(r.intersects(segm));
assertFalse(r.intersects(s));
assertFalse(r.intersects(segm2));
assertTrue(r.intersects(s2));
}
@Test
public void intersectsTriangle() {
throw new UnsupportedOperationException();
}
@Test
public void intersectsOrientedBox() {
Path3f r = new Path3f();
r.moveTo(0f, 0f, 0f);
r.lineTo(1f, 1f, 1f);
r.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
r.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
r.closePath();
OrientedBox3f aB = new OrientedBox3f(new Point3f(0f,0f,0f),new Vector3f(2f,0f,0f),new Vector3f(0f,2f,0f),2f,2f,2f);
OrientedBox3f aB2 = new OrientedBox3f(new Point3f(-1f,-1f,-1f),new Vector3f(-2f,0f,0f),new Vector3f(0f,-2f,0f),1f,1f,1f);
assertTrue(r.intersects(aB));
assertFalse(r.intersects(aB2));
}
@Test
public void intersectsPlane3D() {
Path3f r = new Path3f();
r.moveTo(0f, 0f, 0f);
r.lineTo(1f, 1f, 1f);
r.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
r.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
r.closePath();
Plane3D<AbstractPlane4F> plane = new Plane4f(new Vector3f(1f,1f,1f),new Point3f(0.5f,0.5,0.5));
Plane3D<AbstractPlane4F> plane2 = new Plane4f(new Vector3f(1f,1f,1f),new Point3f(20f,20f,20f));
assertTrue(r.intersects(plane));
assertFalse(r.intersects(plane2));
}
@Test
public void isPolyline() {
throw new UnsupportedOperationException();
}
@Test
public void containsDoubleDoubleDouble() {
throw new UnsupportedOperationException();
}
@Test
public void equals() {
Path3f p = new Path3f();
p.moveTo(0f, 0f, 0f);
p.lineTo(1f, 1f, 1f);
p.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
p.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
p.closePath();
Path3f p3 = p.clone();
Path3f p2 = new Path3f(p);
assertTrue(p2.toString().equals(p.toString()));
assertTrue(p3.toString().equals(p.toString()));
assertTrue(p3.toString().equals(p2.toString()));
assertTrue(p3.equals(p));
assertTrue(p2.equals(p3));
assertTrue(p.equals(p2));
}
@Test
public void removeDoubleDoubleDouble() {
throw new UnsupportedOperationException();
}
@Test
public void containsPoint3D() {
throw new UnsupportedOperationException();
}
@Test
public void toStringTest() {
Path3f p = new Path3f();
p.moveTo(0, 0, 0);
p.lineTo(1, 1, 1);
p.quadTo(3, 0, 0, 4, 3, 0.5);
p.curveTo(5, -1, 0, 6, 5, 0, 7, -5, 0);
p.closePath();
assertTrue(p.toString().equals(
"[0.0, 0.0, 0.0, " //$NON-NLS-1$
+ "1.0, 1.0, 1.0, " //$NON-NLS-1$
+ "3.0, 0.0, 0.0, 4.0, 3.0, 0.5, " //$NON-NLS-1$
+ "5.0, -1.0, 0.0, 6.0, 5.0, 0.0, 7.0, -5.0, 0.0]")); //$NON-NLS-1$
}
@Test
public void isEmptyAndClear() {
Path3f p = new Path3f();
assertTrue(p.isEmpty());
p.moveTo(0f, 0f, 0f);
p.lineTo(1f, 1f, 1f);
p.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
p.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
p.closePath();
assertFalse(p.isEmpty());
p.clear();
assertTrue(p.isEmpty());
}
@Test
public void cloneTest() {
Path3f p = new Path3f();
p.moveTo(0f, 0f, 0f);
p.lineTo(1f, 1f, 1f);
p.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
p.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
p.closePath();
Path3f p2 = p.clone();
assertTrue(p.equals(p2));
assertTrue(p2.equals(p));
}
@Test
public void getClosestPointTo() {
throw new UnsupportedOperationException();
}
@Test
public void getFarthestPointTo() {
throw new UnsupportedOperationException();
}
@Test
public void toBoundingBox() {
throw new UnsupportedOperationException();
}
@Test
public void distanceSquared() {
throw new UnsupportedOperationException();
}
@Test
public void distanceL1() {
throw new UnsupportedOperationException();
}
@Test
public void distanceLinf() {
throw new UnsupportedOperationException();
}
@Test
public void transform() {
throw new UnsupportedOperationException();
}
@Test
public void translate() {
throw new UnsupportedOperationException();
}
@Test
public void createTransformedShape() {
throw new UnsupportedOperationException();
}
@Test
public void add() {
throw new UnsupportedOperationException();
}
@Test
public void removeLast() {
throw new UnsupportedOperationException();
}
@Test
public void setLastPoint() {
throw new UnsupportedOperationException();
}
@Test
public void sizeTest() {
throw new UnsupportedOperationException();
}
@Test
public void toDoubleArrayTest() {
throw new UnsupportedOperationException();
}
@Test
public void toPointArrayTest() {
Path3f p = new Path3f();
p.moveTo(0f, 0f, 0f);
p.lineTo(1f, 1f, 1f);
p.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
p.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
p.closePath();
Point3D [] array = p.toPointArray();
assertTrue(array[0].equals(new Point3f(0,0,0)));
assertTrue(array[1].equals(new Point3f(1,1,1)));
assertTrue(array[2].equals(new Point3f(3,0,0)));
assertTrue(array[3].equals(new Point3f(4,3,0.5)));
assertTrue(array[4].equals(new Point3f(5,-1,0)));
assertTrue(array[5].equals(new Point3f(6,5,0)));
assertTrue(array[6].equals(new Point3f(7,-5,0)));
}
@Test
public void getPointAt() {
Path3f p = new Path3f();
p.moveTo(0f, 0f, 0f);
p.lineTo(1f, 1f, 1f);
p.quadTo(3f, 0f, 0f, 4f, 3f, 0.5);
p.curveTo(5f, -1f, 0f, 6f, 5f, 0f, 7f, -5f, 0f);
p.closePath();
assertTrue(p.getPointAt(0).equals(new Point3f(0,0,0)));
assertTrue(p.getPointAt(1).equals(new Point3f(1,1,1)));
assertTrue(p.getPointAt(2).equals(new Point3f(3,0,0)));
assertTrue(p.getPointAt(3).equals(new Point3f(4,3,0.5)));
assertTrue(p.getPointAt(4).equals(new Point3f(5,-1,0)));
assertTrue(p.getPointAt(5).equals(new Point3f(6,5,0)));
assertTrue(p.getPointAt(6).equals(new Point3f(7,-5,0)));
}
@Test
public void getCurrentPoint() {
throw new UnsupportedOperationException();
}
}
|
package org.lemurproject.galago.core.retrieval.query;
import gnu.trove.map.hash.TObjectByteHashMap;
import gnu.trove.map.hash.TObjectDoubleHashMap;
import gnu.trove.map.hash.TObjectLongHashMap;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
/**
* Currently the parameters that are attached to query Nodes are not quite the
* same implementation as the generic Parameters object. We intend to fold these
* classes together at some point in the future, most likely making this one a
* subclass of the Parameters object.
*
* For now, however, they are separate.
*
*
* @author sjh
*/
public class NodeParameters implements Serializable {
private static enum Type {
STRING, LONG, DOUBLE, MAP, BOOLEAN, LIST
}
private HashMap<String, Type> keyMapping = new HashMap<>();
private HashMap<String, String> stringMap = null;
private TObjectByteHashMap<String> boolMap = null;
private TObjectLongHashMap<String> longMap = null;
private TObjectDoubleHashMap<String> doubleMap = null;
private static final long serialVersionUID = 4553653651892088433L;
public static NodeParameters create() { return new NodeParameters(); }
public NodeParameters() {
// do nothing
}
public NodeParameters(boolean def) {
set("default", def);
}
public NodeParameters(long def) {
set("default", def);
}
public NodeParameters(double def) {
set("default", def);
}
public NodeParameters(String def) {
set("default", def);
}
public Set<String> getKeySet() {
return keyMapping.keySet();
}
public Type getKeyType(String key) {
return this.keyMapping.get(key);
}
public boolean containsKey(String key) {
return this.keyMapping.containsKey(key);
}
public NodeParameters set(String key, boolean value) {
ensureKeyType(key, Type.BOOLEAN);
if (boolMap == null) {
boolMap = new TObjectByteHashMap<>();
}
boolMap.put(key, (value ? (byte) 1 : (byte) 0));
return this;
}
public NodeParameters set(String key, long value) {
ensureKeyType(key, Type.LONG);
if (longMap == null) {
longMap = new TObjectLongHashMap<>();
}
longMap.put(key, value);
return this;
}
public NodeParameters set(String key, double value) {
ensureKeyType(key, Type.DOUBLE);
if (doubleMap == null) {
doubleMap = new TObjectDoubleHashMap<>();
}
doubleMap.put(key, value);
return this;
}
public NodeParameters set(String key, String value) {
ensureKeyType(key, Type.STRING);
if (stringMap == null) {
stringMap = new HashMap<>();
}
stringMap.put(key, value);
return this;
}
public boolean getBoolean(String key) {
checkKeyType(key, Type.BOOLEAN);
return (boolMap.get(key) != 0);
}
public long getLong(String key) {
checkKeyType(key, Type.LONG);
return longMap.get(key);
}
public double getDouble(String key) {
// special case - allow longs to be cast to doubles.
if (keyMapping.containsKey(key)) {
if (keyMapping.get(key).equals(Type.LONG)) {
return getLong(key);
}
}
checkKeyType(key, Type.DOUBLE);
return doubleMap.get(key);
}
public String getString(String key) {
checkKeyType(key, Type.STRING);
return stringMap.get(key);
}
public boolean get(String key, boolean def) {
if (keyMapping.containsKey(key)) {
return getBoolean(key);
} else {
return def;
}
}
public long get(String key, long def) {
if (keyMapping.containsKey(key)) {
return getLong(key);
} else {
return def;
}
}
public double get(String key, double def) {
if (keyMapping.containsKey(key)) {
return getDouble(key);
} else {
return def;
}
}
public String get(String key, String def) {
if (keyMapping.containsKey(key)) {
return getString(key);
} else {
return def;
}
}
/**
* Special get function - does not throw exceptions for missing keys.
*/
public String getAsString(String key) {
// assert keyMapping.containsKey(key) : "Key " + key + " not found in NodeParameters.";
if (keyMapping.containsKey(key)) {
switch (keyMapping.get(key)) {
case BOOLEAN:
return Boolean.toString(boolMap.get(key) != 0);
case LONG:
return Long.toString(longMap.get(key));
case DOUBLE:
return Double.toString(doubleMap.get(key));
case STRING:
return stringMap.get(key);
}
}
return null;
}
public String getAsSimpleString(String key) {
if (keyMapping.containsKey(key)) {
switch (keyMapping.get(key)) {
case BOOLEAN:
return Boolean.toString(boolMap.get(key) != 0);
case LONG:
return Long.toString(longMap.get(key));
case DOUBLE:
BigDecimal bd = new BigDecimal(doubleMap.get(key));
bd = bd.round(new MathContext(3));
return bd.toString();
case STRING:
return stringMap.get(key);
}
}
return null;
}
public void remove(String key) {
if (keyMapping.containsKey(key)) {
switch (keyMapping.get(key)) {
case BOOLEAN:
boolMap.remove(key);
break;
case LONG:
longMap.remove(key);
break;
case DOUBLE:
doubleMap.remove(key);
break;
case STRING:
stringMap.remove(key);
break;
default:
throw new IllegalArgumentException("Key somehow has an illegal type: " + keyMapping.get(key));
}
keyMapping.remove(key);
}
}
@Override
public NodeParameters clone() {
NodeParameters duplicate = new NodeParameters();
if (keyMapping != null) {
duplicate.keyMapping = new HashMap<>(this.keyMapping);
}
if (boolMap != null) {
duplicate.boolMap = new TObjectByteHashMap<>(boolMap);
}
if (longMap != null) {
duplicate.longMap = new TObjectLongHashMap<>(longMap);
}
if (doubleMap != null) {
duplicate.doubleMap = new TObjectDoubleHashMap<>(doubleMap);
}
if (stringMap != null) {
duplicate.stringMap = new HashMap<>(this.stringMap);
}
return duplicate;
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(!(o instanceof NodeParameters)) {
return false;
}
NodeParameters other = (NodeParameters) o;
return Objects.equals(this.keyMapping, other.keyMapping) &&
Objects.equals(this.boolMap, other.boolMap) &&
Objects.equals(this.longMap, other.longMap) &&
Objects.equals(this.stringMap, other.stringMap) &&
Objects.equals(this.doubleMap, other.doubleMap);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
// ensure default is the first value
if (keyMapping.containsKey("default")) {
String value = getAsString("default");
value = escapeAsNecessary(value, keyMapping.get("default") == Type.STRING);
sb.append(":").append(value);
}
// sort remaining keys alphabetically.
ArrayList<String> keys = new ArrayList<>(keyMapping.keySet());
Collections.sort(keys);
for (String key : keys) {
// need to ensure "default" is not double written.
if (!key.equals("default")) {
String value = getAsString(key);
value = escapeAsNecessary(value, keyMapping.get(key) == Type.STRING);
key = escapeAsNecessary(key, false);
sb.append(":").append(key).append("=").append(value);
}
}
return sb.toString();
}
public String toSimpleString(Set<String> ignoreParams, String operator) {
StringBuilder sb = new StringBuilder();
if (keyMapping.containsKey("default")) {
String value = getAsSimpleString("default");
value = escapeAsNecessary(value, keyMapping.get("default") == Type.STRING);
if (operator.equals("extents") || operator.equals("counts")) {
sb.append(value);
} else {
sb.append(":").append(value);
}
}
// sort remaining keys alphabetically.
ArrayList<String> keys = new ArrayList<>(keyMapping.keySet());
Collections.sort(keys);
for (String key : keys) {
// need to ensure "default" is not double written.
if (key.equals("combine")) {
String value = getAsSimpleString(key);
value = escapeAsNecessary(value, keyMapping.get(key) == Type.STRING); //double value
key = escapeAsNecessary(key, false);
sb.append(":").append(key).append("=").append(value);
} else if (!key.equals("default") && !ignoreParams.contains(key)) {
if (!key.matches("-?[0-9]+")) { //key is an integer
String value = getAsSimpleString(key);
value = escapeAsNecessary(value, keyMapping.get(key) == Type.STRING); //double value
key = escapeAsNecessary(key, false);
sb.append(":").append(key).append("=").append(value);
}
}
}
return sb.toString();
}
public ArrayList<String> collectCombineWeightList() {
ArrayList<String> combineWeightList = new ArrayList<>();
ArrayList<String> keys = new ArrayList<>(keyMapping.keySet());
//Collections.sort(keys);
Collections.sort(keys, new Comparator<String>() {
public int compare(String s1, String s2) {
if (!s1.matches("-?[0-9]+") || !s2.matches("-?[0-9]+")) {
return s1.compareTo(s2);
} else {
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
}
});
for (String key : keys) {
// need to ensure "default" is not double written.
if (!key.equals("default")) {
String value = getAsSimpleString(key);
value = escapeAsNecessary(value, keyMapping.get(key) == Type.STRING); //double value
key = escapeAsNecessary(key, false);
if (key.matches("-?[0-9]+")) { //key is an Integer
combineWeightList.add(value);
}
}
}
return combineWeightList;
}
public void parseSet(String key, String value) {
// decode value:
// boolean: true | false
if (value.equals("true") || value.equals("false")) {
boolean b = Boolean.parseBoolean(value);
this.set(key, b);
} else {
try {
// if the value contains a . -- could be double
if (value.contains(".")) {
double d = Double.parseDouble(value);
this.set(key, d);
} else {
// otherwise could be a long
long l = Long.parseLong(value);
this.set(key, l);
}
} catch (NumberFormatException e) {
// if it's not numeric or boolean - it's a string
this.set(key, value);
}
}
}
private void ensureKeyType(String key, Type t) {
checkKeyType(key, t);
keyMapping.put(key, t);
}
private void checkKeyType(String key, Type t) {
if (keyMapping.containsKey(key)) {
if (keyMapping.get(key) != t) {
throw new IllegalArgumentException("Key " + key + " exists as a " + keyMapping.get(key).name());
}
}
}
// escaping functions - used in toString()
public boolean needsToBeEscaped(String text, boolean typeProtection) {
// if the text is a string -- we may need to quote it:
if (typeProtection) {
if (text.equals(Boolean.toString(true))
|| text.equals(Boolean.toString(false))) {
return true;
}
if(text.contains("-") || text.contains(".") || text.contains("e")) {
return true;
}
}
// A parameter value needs to be escaped if it contains: ':' '=' '('
return (text.contains(":") || text.contains("=")
|| text.contains("(") || text.contains("@")
|| text.contains("\"") || text.contains("'"));
}
public String escapeAsNecessary(String text, boolean typeProtection) {
if (!needsToBeEscaped(text, typeProtection)) {
return text;
} else {
String[] preferredDelimiters = {"/", "|", "\\", "
for (String delimiter : preferredDelimiters) {
if (!text.contains(delimiter)) {
return "@" + delimiter + text + delimiter;
}
}
// give up
return text;
}
}
public boolean isString(String key) {
return this.keyMapping.containsKey(key) && this.keyMapping.get(key) == Type.STRING;
}
public boolean isBoolean(String key) {
return this.keyMapping.containsKey(key) && this.keyMapping.get(key) == Type.BOOLEAN;
}
public boolean isDouble(String key) {
return this.keyMapping.containsKey(key) && this.keyMapping.get(key) == Type.DOUBLE;
}
public boolean isLong(String key) {
return this.keyMapping.containsKey(key) && this.keyMapping.get(key) == Type.LONG;
}
}
|
package fr.treeptik.cloudunit.controller;
import java.util.List;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import fr.treeptik.cloudunit.exception.CheckException;
import fr.treeptik.cloudunit.exception.ServiceException;
import fr.treeptik.cloudunit.model.Metric;
import fr.treeptik.cloudunit.service.DockerService;
import fr.treeptik.cloudunit.service.MonitoringService;
@RestController
@RequestMapping("/monitoring")
public class MonitoringController {
private Logger logger = LoggerFactory.getLogger(MonitoringController.class);
@Inject
private MonitoringService monitoringService;
@Inject
private DockerService dockerService;
/**
* Is a wrapper to cAdvisor API
*
* @return
* @throws fr.treeptik.cloudunit.exception.ServiceException
* @throws fr.treeptik.cloudunit.exception.CheckException
*/
@RequestMapping(value = "/api/machine", method = RequestMethod.GET)
public void infoMachine(HttpServletRequest request, HttpServletResponse response)
throws ServiceException, CheckException {
String responseFromCAdvisor = monitoringService.getJsonMachineFromCAdvisor();
try {
response.getWriter().write(responseFromCAdvisor);
response.flushBuffer();
} catch (Exception e) {
logger.error("error during write and flush response", responseFromCAdvisor);
}
}
/**
* * Is a wrapper to cAdvisor API
*
* @param containerName
* @throws ServiceException
* @throws CheckException
*/
@RequestMapping(value = "/api/containers/docker/{containerName}", method = RequestMethod.GET)
public void infoContainer(HttpServletRequest request, HttpServletResponse response,
@PathVariable String containerName) throws ServiceException, CheckException {
try {
String containerId = dockerService.getContainerId(containerName);
String responseFromCAdvisor = monitoringService.getJsonFromCAdvisor(containerId);
if (logger.isDebugEnabled()) {
logger.debug("containerId=" + containerId);
logger.debug("responseFromCAdvisor=" + responseFromCAdvisor);
}
response.getWriter().write(responseFromCAdvisor);
response.flushBuffer();
} catch (Exception e) {
logger.error("error during write and flush response", containerName);
}
}
@RequestMapping(value = "/metrics/{serverName}")
public List<Metric> findAllByServer(@PathVariable("serverName") String serverName) {
return monitoringService.findByServer(serverName);
}
/**
* Return the position into the architecture of the service
* @return
*/
@RequestMapping("/location")
public ResponseEntity<String> getServiceLocation(@Value("#{environment.CU_KIBANA_DOMAIN}") String location) {
if (location != null && !location.startsWith("https")) {
location = "https://" + location;
}
return ResponseEntity.ok(location);
}
}
|
package de.factoryfx.factory.atrribute;
import com.fasterxml.jackson.annotation.JsonCreator;
import de.factoryfx.data.Data;
import de.factoryfx.data.attribute.ReferenceAttribute;
import de.factoryfx.data.util.LanguageText;
import de.factoryfx.data.validation.Validation;
import de.factoryfx.data.validation.ValidationError;
import de.factoryfx.data.validation.ValidationResult;
import de.factoryfx.factory.FactoryBase;
import java.util.List;
/**
* Attribute with factory
* @param <L> liveobject created form the factory
* @param <F> factory
*/
public class FactoryReferenceAttribute<L, F extends FactoryBase<? extends L,?>> extends ReferenceAttribute<F,FactoryReferenceAttribute<L, F>> {
private static final Validation requiredValidation = value -> {
boolean error = value == null;
return new ValidationResult(error, new LanguageText().en("required parameter").de("Pflichtparameter"));
};
@JsonCreator
@SuppressWarnings("unchecked")
protected FactoryReferenceAttribute(F value) {
super(value);
}
public FactoryReferenceAttribute(Class<F> clazz) {
this();
setup(clazz);
}
@SuppressWarnings("unchecked")
public FactoryReferenceAttribute() {
super();
}
@Override
public boolean internal_required() {
return !nullable;
}
public L instance(){
if (get()==null){
return null;
}
return get().internalFactory().instance();
}
@Override
public FactoryReferenceAttribute<L, F> setupUnsafe(Class clazz){
return super.setupUnsafe(clazz);
}
@Override
public FactoryReferenceAttribute<L, F> setup(Class<F> clazz){
return super.setup(clazz);
}
private boolean nullable;
public FactoryReferenceAttribute<L, F> nullable(){
nullable=true;
return this;
}
@Override
public List<ValidationError> internal_validate(Data parent) {
if (!nullable){
this.validation(requiredValidation);// to minimise object creations
}
return super.internal_validate(parent);
}
}
|
package org.fao.fenix.commons.msd.dto.full;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.fao.fenix.commons.annotations.Description;
import org.fao.fenix.commons.annotations.Label;
import org.fao.fenix.commons.msd.dto.JSONEntity;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
public class OjPeriod extends JSONEntity implements Serializable {
@JsonProperty
@Label(en="Date from")
@Description(en="Start point of time delimiting a time interval.")
private Date from;
@JsonProperty
@Label(en="Date to")
@Description(en="End point of time delimiting a time interval.")
private Date to;
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
}
|
package com.yahoo.vespa.filedistribution;
import com.google.common.util.concurrent.SettableFuture;
import com.yahoo.config.FileReference;
import com.yahoo.log.LogLevel;
import com.yahoo.vespa.config.ConnectionPool;
import com.yahoo.vespa.defaults.Defaults;
import java.io.File;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
/**
* Handles downloads of files (file references only for now)
*
* @author hmusum
*/
public class FileDownloader {
private final static Logger log = Logger.getLogger(FileDownloader.class.getName());
private final File downloadDirectory;
private final Duration timeout;
private final FileReferenceDownloader fileReferenceDownloader;
public FileDownloader(ConnectionPool connectionPool) {
this(connectionPool,
new File(Defaults.getDefaults().underVespaHome("var/db/vespa/filedistribution")),
new File(Defaults.getDefaults().underVespaHome("tmp")),
Duration.ofMinutes(15));
}
FileDownloader(ConnectionPool connectionPool, File downloadDirectory, File tmpDirectory, Duration timeout) {
this.downloadDirectory = downloadDirectory;
this.timeout = timeout;
this.fileReferenceDownloader = new FileReferenceDownloader(downloadDirectory, tmpDirectory, connectionPool, timeout);
}
public Optional<File> getFile(FileReference fileReference) {
try {
return getFutureFile(fileReference).get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
return Optional.empty();
}
}
private Future<Optional<File>> getFutureFile(FileReference fileReference) {
Objects.requireNonNull(fileReference, "file reference cannot be null");
File directory = new File(downloadDirectory, fileReference.value());
log.log(LogLevel.DEBUG, "Checking if there is a file in '" + directory.getAbsolutePath() + "' ");
Optional<File> file = getFileFromFileSystem(fileReference, directory);
if (file.isPresent()) {
SettableFuture<Optional<File>> future = SettableFuture.create();
future.set(file);
return future;
} else {
log.log(LogLevel.INFO, "File reference '" + fileReference.value() + "' not found in " +
directory.getAbsolutePath() + ", starting download");
return queueForAsyncDownload(fileReference, timeout);
}
}
// Start downloading, but there is no Future used get file being downloaded
public void queueForAsyncDownload(List<FileReference> fileReferences) {
fileReferences.forEach(fileReference -> {
if (fileReferenceDownloader.isDownloading(fileReference)) {
log.log(LogLevel.DEBUG, "Already downloading '" + fileReference.value() + "'");
} else {
queueForAsyncDownload(fileReference);
}
});
}
void receiveFile(FileReferenceData fileReferenceData) {
fileReferenceDownloader.receiveFile(fileReferenceData);
}
double downloadStatus(FileReference fileReference) {
return fileReferenceDownloader.downloadStatus(fileReference.value());
}
public Map<FileReference, Double> downloadStatus() {
return fileReferenceDownloader.downloadStatus();
}
File downloadDirectory() {
return downloadDirectory;
}
private Optional<File> getFileFromFileSystem(FileReference fileReference, File directory) {
File[] files = directory.listFiles();
if (directory.exists() && directory.isDirectory() && files != null && files.length > 0) {
File file = files[0];
if (!file.exists()) {
throw new RuntimeException("File with reference '" + fileReference.value() + "' does not exist");
} else if (!file.canRead()) {
throw new RuntimeException("File with reference '" + fileReference.value() + "'exists, but unable to read it");
} else {
fileReferenceDownloader.setDownloadStatus(fileReference, 1.0);
return Optional.of(file);
}
}
return Optional.empty();
}
private synchronized Future<Optional<File>> queueForAsyncDownload(FileReference fileReference, Duration timeout) {
Future<Optional<File>> inProgress = fileReferenceDownloader.addDownloadListener(fileReference, () -> getFile(fileReference));
if (inProgress != null) {
log.log(LogLevel.DEBUG, "Already downloading '" + fileReference.value() + "'");
return inProgress;
}
Future<Optional<File>> future = queueForAsyncDownload(fileReference);
log.log(LogLevel.INFO, "Queued '" + fileReference.value() + "' for download with timeout " + timeout);
return future;
}
private Future<Optional<File>> queueForAsyncDownload(FileReference fileReference) {
FileReferenceDownload fileReferenceDownload = new FileReferenceDownload(fileReference, SettableFuture.create());
fileReferenceDownloader.addToDownloadQueue(fileReferenceDownload);
return fileReferenceDownload.future();
}
public FileReferenceDownloader fileReferenceDownloader() {
return fileReferenceDownloader;
}
}
|
package org.fedorahosted.flies.webtrans.client;
import java.util.ArrayList;
import net.customware.gwt.presenter.client.EventBus;
import org.fedorahosted.flies.webtrans.client.events.TransMemoryCopyEvent;
import org.fedorahosted.flies.webtrans.client.ui.HighlightingLabel;
import org.fedorahosted.flies.webtrans.shared.model.TransMemory;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
public class TransMemoryView extends Composite implements TransMemoryPresenter.Display {
private static final int CELL_PADDING = 5;
private static final int HEADER_ROW = 0;
private static final int SOURCE_COL = 0;
private static final int TARGET_COL = 1;
private static final int SIMILARITY_COL = 2;
private static final int ACTION_COL = 3;
private static TransMemoryViewUiBinder uiBinder = GWT
.create(TransMemoryViewUiBinder.class);
interface TransMemoryViewUiBinder extends
UiBinder<Widget, TransMemoryView> {
}
@UiField
TextBox tmTextBox;
@UiField
CheckBox phraseButton;
@UiField
Button searchButton;
@UiField
Button clearButton;
@UiField
FlexTable resultTable;
@Inject
private EventBus eventBus;
private final WebTransMessages messages;
@Inject
public TransMemoryView(final WebTransMessages messages) {
this.messages = messages;
initWidget( uiBinder.createAndBindUi(this));
phraseButton.setText( messages.tmPhraseButtonLabel() );
clearButton.setText( messages.tmClearButtonLabel() );
searchButton.setText( messages.tmSearchButtonLabel() );
}
@UiHandler("tmTextBox")
void onTmTextBoxKeyUp(KeyUpEvent event) {
if( event.getNativeKeyCode() == KeyCodes.KEY_ENTER ) {
searchButton.click();
}
}
@UiHandler("clearButton")
void onClearButtonClicked(ClickEvent event) {
tmTextBox.setText("");
clearResults();
}
@Override
public HasValue<Boolean> getExactButton() {
return phraseButton;
}
@Override
public Button getSearchButton() {
return searchButton;
}
public TextBox getTmTextBox() {
return tmTextBox;
}
@Override
public Widget asWidget() {
return this;
}
@Override
public void startProcessing() {
clearResults();
resultTable.setWidget(0, 0, new Label("Loading..."));
}
@Override
public void stopProcessing() {
}
@Override
public void createTable(ArrayList<TransMemory> memories) {
clearResults();
addColumn("Source", SOURCE_COL);
addColumn("Target", TARGET_COL);
addColumn("Similarity", SIMILARITY_COL);
addColumn("Action", ACTION_COL);
int row = HEADER_ROW;
for(final TransMemory memory: memories) {
++row;
final String sourceMessage = memory.getSource();
final String targetMessage = memory.getMemory();
// final String sourceComment = memory.getSourceComment();
// final String targetComment = memory.getTargetComment();
final String docID = memory.getDocID();
// final float score = memory.getRelevanceScore();
final int similarity = memory.getSimilarityPercent();
resultTable.setWidget(row, SOURCE_COL, new HighlightingLabel(sourceMessage));
resultTable.setWidget(row, TARGET_COL, new HighlightingLabel(targetMessage));
resultTable.setText(row, SIMILARITY_COL, similarity + "%");
final Anchor copyLink = new Anchor("Copy");
copyLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
eventBus.fireEvent(new TransMemoryCopyEvent(sourceMessage, targetMessage));
Log.info("TransMemoryCopyEvent event is sent. (" + targetMessage + ")");
}
});
resultTable.setWidget(row, ACTION_COL, copyLink);
// comments are presently disabled on the server side
// String suppInfo = "Source Comment: " + sourceComment + " "
// + "Target Comment: " + targetComment + " "
// + "Document Name: " + docID;
String suppInfo = "Document Name: " + docID;
// Use ToolTips for supplementary info.
resultTable.getWidget(row, SOURCE_COL).setTitle(suppInfo);
resultTable.getWidget(row, TARGET_COL).setTitle(suppInfo);
resultTable.getWidget(row, ACTION_COL).setTitle("Copy \"" + targetMessage + "\" to the editor.");
}
resultTable.setCellPadding(CELL_PADDING);
}
private void addColumn(String columnHeading, int pos) {
Label widget = new Label(columnHeading);
widget.setWidth("100%");
widget.addStyleName("TransMemoryTableColumnHeader");
resultTable.setWidget(HEADER_ROW, pos, widget);
}
public void clearResults() {
resultTable.removeAllRows();
}
}
|
package org.thinkinghub.gateway.oauth.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thinkinghub.gateway.oauth.bean.GatewayResponse;
import org.thinkinghub.gateway.oauth.entity.AuthenticationHistory;
import org.thinkinghub.gateway.oauth.entity.ServiceStatus;
import org.thinkinghub.gateway.oauth.queue.QueuableTask;
import org.thinkinghub.gateway.oauth.repository.AuthenticationHistoryRepository;
import org.thinkinghub.gateway.oauth.service.QueueService;
import com.github.scribejava.core.model.OAuth2AccessToken;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class GatewayEventsHandler {
@Autowired
private AuthenticationHistoryRepository authenticationHistoryRepository;
@Autowired
private QueueService queueService;
@EventListener
public void onAccessTokenRetrived(AccessTokenRetrievedEvent event) {
OAuth2AccessToken accessToken = event.getToken();
log.info("Got the Access Token!");
log.info("(if your curious it looks like this: " + accessToken + ", 'rawResponse'='"
+ accessToken.getRawResponse() + "')");
}
@EventListener
public void onStartingOAuthProcess(StartingOAuthProcessEvent event) {
AuthenticationHistory ah = new AuthenticationHistory();
ah.setServiceType(event.getService());
ah.setState(event.getState());
ah.setUser(event.getUser());
ah.setCallback(event.getCallback());
ah.setServiceStatus(ServiceStatus.INPROGRESS);
authenticationHistoryRepository.save(ah);
}
@EventListener
public void onOAuthProviderCallbackReceived(OAuthProviderCallbackReceivedEvent event) {
ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
sra.setAttribute("service", event.getService(), RequestAttributes.SCOPE_REQUEST);
}
@EventListener
public void onOAuthProcessFinished(OAuthProcessFinishedEvent event) {
AuthenticationHistory ah = authenticationHistoryRepository.findByState(event.getState());
GatewayResponse response = event.getResponse();
logAuthHistory(ah, response);
}
private void logAuthHistory(AuthenticationHistory ah, GatewayResponse response) {
ah.setServiceStatus(ServiceStatus.SUCCESS);
ah.setRawResponse(response.getRawResponse());
queueService.put(new QueuableTask() {
@Override
public void execute() {
authenticationHistoryRepository.save(ah);
}
});
}
}
|
package gov.usgs.cida.gcmrcservices.column;
import gov.usgs.cida.gcmrcservices.jsl.data.BedSedimentSpec;
import gov.usgs.cida.gcmrcservices.jsl.data.ParameterCode;
import gov.usgs.cida.gcmrcservices.jsl.data.ParameterSpec;
import gov.usgs.cida.gcmrcservices.jsl.data.QWDataSpec;
import gov.usgs.cida.gcmrcservices.jsl.data.SpecOptions;
import gov.usgs.cida.nude.column.Column;
import gov.usgs.cida.nude.column.SimpleColumn;
import gov.usgs.cida.nude.out.mapping.ColumnToXmlMapping;
import gov.usgs.webservices.jdbc.spec.Spec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author dmsibley
*/
public class ColumnMetadata {
private static final Logger log = LoggerFactory.getLogger(ColumnMetadata.class);
protected final String pcode;
protected final ParameterCode parameterCode;
protected final String columnTitle;
protected final List<SpecEntry> specEntries;
public ColumnMetadata(String pcode, String columnTitle, SpecEntry... specs) {
this.pcode = pcode;
this.parameterCode = ParameterCode.parseParameterCode(pcode);
this.columnTitle = columnTitle;
List<SpecEntry> se = new ArrayList<SpecEntry>();
if (null != specs && 0 < specs.length) {
se.addAll(Arrays.asList(specs));
}
this.specEntries = Collections.unmodifiableList(se);
}
/**
* Give a pCode if not a download, give descriptive names if is.
* @param station
* @param isDownload
* @return
*/
public ColumnToXmlMapping getMapping(String station, boolean isDownload) {
return getMapping(station, isDownload, null);
}
private static String hashString(String message, Integer places) {
String result = null;
if (null != message) {
String algorithm = "SHA-256";
String encoding = "UTF-8";
try {
MessageDigest sha = MessageDigest.getInstance(algorithm);
sha.update(message.getBytes(encoding));
byte[] digest = sha.digest();
result = Hex.encodeHexString(digest);
} catch (NoSuchAlgorithmException e) {
log.error("Could not get " + algorithm + " Algorithm");
} catch (UnsupportedEncodingException ex) {
log.error("Could not get " + encoding + " Encoding");
}
if (null == result) {
result = "" + message.hashCode();
}
if (null != places) {
result = result.substring(0, places);
}
}
return result;
}
public static String createColumnName(String station, ParameterCode parameterCode) {
String result = null;
String ancillaryColumn = null;
ParameterCode tempParameterCode = null;
if (parameterCode.sampleMethod.startsWith("iceAffected") ||
parameterCode.sampleMethod.startsWith("notes")) {
tempParameterCode = ParameterCode.parseParameterCode("inst!" + parameterCode.groupName);
}
else {
tempParameterCode = parameterCode;
}
switch (parameterCode.sampleMethod)
{
case "iceAffected":
ancillaryColumn = ParameterSpec.C_ICE_AFFECTED;
break;
case "notes":
ancillaryColumn = ParameterSpec.C_NOTES;
break;
default:
ancillaryColumn = "";
break;
}
result = "S" + hashString(station, 5) + "P" + hashString(tempParameterCode.toString(), 5) + ancillaryColumn;
return result;
}
/**
* Give a pCode if not a download, give descriptive names if is.
* @param station
* @param isDownload
* @param customName
* @return
*/
public ColumnToXmlMapping getMapping(String station, boolean isDownload, String customName) {
ColumnToXmlMapping result = null;
String inName = createColumnName(station, this.parameterCode);
String outName = getDefaultOutName(station, isDownload);
String cleanCustomName = StringUtils.trimToNull(customName);
if (null != cleanCustomName) {
outName = StringUtils.replace(cleanCustomName, "*default*", outName);
}
result = new ColumnToXmlMapping(inName, outName);
return result;
}
protected String getDefaultOutName(String station, boolean isDownload) {
String result = null;
String tag = this.pcode;
if (isDownload) {
tag = this.columnTitle;
}
result = tag + "-" + station;
return result;
}
public List<SpecEntry> getSpecEntries() {
return this.specEntries;
}
public Column getColumn(String station) {
Column result = null;
result = new SimpleColumn(pcode + "-" + station);
return result;
}
public Column getInternalColumn(String station) {
Column result = null;
result = new SimpleColumn(createColumnName(station, this.parameterCode));
return result;
}
public String getPCode() {
return this.pcode;
}
public static class SpecEntry {
public static enum SpecType {
PARAM,
LABDATA,
BEDMATERIAL;
}
public final ParameterCode parameterCode;
public final SpecType specType;
public SpecEntry(ParameterCode parameterCode, SpecType specType) {
this.parameterCode = parameterCode;
this.specType = specType;
}
public Column getColumn(String station) {
Column result = null;
result = new SimpleColumn(createColumnName(station, this.parameterCode));
return result;
}
public Spec getSpec(String station, SpecOptions specOptions) {
Spec result = null;
switch (this.specType) {
case PARAM:
result = new ParameterSpec(station, this.parameterCode, specOptions);
break;
case LABDATA:
result = new QWDataSpec(station, this.parameterCode, specOptions);
break;
case BEDMATERIAL:
result = new BedSedimentSpec(station, this.parameterCode, specOptions);
break;
}
return result;
}
}
}
|
package edu.uci.python.nodes.call;
import com.oracle.truffle.api.*;
import com.oracle.truffle.api.frame.*;
import com.oracle.truffle.api.nodes.*;
import com.oracle.truffle.api.utilities.*;
import edu.uci.python.nodes.*;
import edu.uci.python.runtime.*;
import edu.uci.python.runtime.builtin.*;
import edu.uci.python.runtime.datatype.*;
import edu.uci.python.runtime.function.*;
import edu.uci.python.runtime.object.*;
import edu.uci.python.runtime.standardtype.*;
public abstract class CallDispatchBoxedNode extends CallDispatchNode {
public CallDispatchBoxedNode(String calleeName) {
super(calleeName);
}
protected abstract Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments);
protected final Object executeCallAndRewrite(CallDispatchBoxedNode next, VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
replace(next);
return next.executeCall(frame, primaryObj, arguments);
}
protected static CallDispatchBoxedNode create(PythonContext context, PythonBasicObject primary, PythonCallable callee, PNode calleeNode) {
UninitializedDispatchBoxedNode next = new UninitializedDispatchBoxedNode(context, callee.getName(), calleeNode);
/**
* Treat generator as slow path for now.
*/
if (callee instanceof PGeneratorFunction) {
return new GenericDispatchBoxedNode(callee.getName(), calleeNode);
}
if (callee instanceof PFunction) {
return new DispatchFunctionNode(primary, (PFunction) callee, next);
} else if (callee instanceof PBuiltinFunction) {
return new DispatchBuiltinFunctionNode(primary, (PBuiltinFunction) callee, next);
} else if (callee instanceof PythonBuiltinClass && primary instanceof PythonModule) {
return new DispatchBuiltinConstructorNode(primary, (PythonBuiltinClass) callee, next);
} else if (callee instanceof PMethod) {
return new DispatchMethodNode(primary, (PMethod) callee, next);
}
throw new UnsupportedOperationException("Unsupported callee type " + callee);
}
/**
* The primary could be:
* <p>
* 1. The global {@link PythonModule}. <br>
* 3. A {@link PythonModule}. <br>
* 2. A {@link PythonClass}.
*
*/
public static final class DispatchFunctionNode extends CallDispatchBoxedNode {
@Child protected CallNode callNode;
@Child protected CallDispatchBoxedNode nextNode;
private final PythonBasicObject cachedPrimary;
private final Assumption dispatchStable;
private final MaterializedFrame declarationFrame;
public DispatchFunctionNode(PythonBasicObject primary, PFunction callee, CallDispatchBoxedNode next) {
super(callee.getName());
callNode = Truffle.getRuntime().createCallNode(callee.getCallTarget());
nextNode = next;
cachedPrimary = primary;
dispatchStable = primary.getStableAssumption();
declarationFrame = callee.getDeclarationFrame();
assert primary instanceof PythonModule || primary instanceof PythonClass;
}
@Override
protected Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
if (primaryObj == cachedPrimary) {
try {
dispatchStable.check();
PArguments arg = new PArguments(null, declarationFrame, arguments);
return callNode.call(frame.pack(), arg);
} catch (InvalidAssumptionException ex) {
return executeCallAndRewrite(nextNode, frame, primaryObj, arguments);
}
}
return nextNode.executeCall(frame, primaryObj, arguments);
}
}
/**
* The primary could be:
* <p>
* 1. The global {@link PythonModule}. <br>
* 2. A built-in {@link PythonModule}. <br>
* 3. A built-in {@link PythonBuiltinClass}.
*
*/
public static final class DispatchBuiltinFunctionNode extends CallDispatchBoxedNode {
@Child protected CallNode callNode;
@Child protected CallDispatchBoxedNode nextNode;
protected final Assumption dispatchStable;
public DispatchBuiltinFunctionNode(PythonBasicObject primary, PBuiltinFunction callee, UninitializedDispatchBoxedNode next) {
super(callee.getName());
callNode = Truffle.getRuntime().createCallNode(callee.getCallTarget());
nextNode = next;
Assumption globalStable = primary.getStableAssumption();
Assumption builtinStable = next.context.getBuiltins().getStableAssumption();
dispatchStable = new UnionAssumption("global and builtin", globalStable, builtinStable);
assert primary instanceof PythonModule || primary instanceof PythonBuiltinClass;
}
@Override
protected Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
try {
dispatchStable.check();
PArguments arg = new PArguments(PNone.NONE, null, arguments);
return callNode.call(frame.pack(), arg);
} catch (InvalidAssumptionException ex) {
return executeCallAndRewrite(nextNode, frame, primaryObj, arguments);
}
}
}
public static final class DispatchBuiltinConstructorNode extends CallDispatchBoxedNode {
@Child protected CallNode callNode;
@Child protected CallDispatchBoxedNode nextNode;
protected final Assumption dispatchStable;
public DispatchBuiltinConstructorNode(PythonBasicObject primary, PythonBuiltinClass callee, UninitializedDispatchBoxedNode next) {
super(callee.getName());
PythonCallable constructor = callee.lookUpMethod("__init__");
callNode = Truffle.getRuntime().createCallNode(split(constructor.getCallTarget()));
nextNode = next;
Assumption globalStable = primary.getStableAssumption();
Assumption builtinStable = next.context.getBuiltins().getStableAssumption();
dispatchStable = new UnionAssumption("global and builtin", globalStable, builtinStable);
}
@Override
protected Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
try {
dispatchStable.check();
PArguments arg = new PArguments(PNone.NONE, null, arguments);
return callNode.call(frame.pack(), arg);
} catch (InvalidAssumptionException ex) {
return executeCallAndRewrite(nextNode, frame, primaryObj, arguments);
}
}
}
/**
* The primary is a {@link PythonObject}
*
*/
public static final class DispatchMethodNode extends CallDispatchBoxedNode {
@Child protected CallNode callNode;
@Child protected CallDispatchBoxedNode nextNode;
private final PythonClass cachedClass;
private final Assumption dispatchStable;
private final MaterializedFrame declarationFrame;
public DispatchMethodNode(PythonBasicObject primary, PMethod callee, CallDispatchBoxedNode next) {
super(callee.getName());
callNode = Truffle.getRuntime().createCallNode(callee.getCallTarget());
nextNode = next;
cachedClass = primary.getPythonClass();
declarationFrame = callee.__func__().getDeclarationFrame();
dispatchStable = primary.getStableAssumption();
}
@Override
protected Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
if (primaryObj.getPythonClass() == cachedClass) {
try {
dispatchStable.check();
PArguments arg = new PArguments(primaryObj, declarationFrame, arguments);
return callNode.call(frame.pack(), arg);
} catch (InvalidAssumptionException ex) {
return executeCallAndRewrite(nextNode, frame, primaryObj, arguments);
}
}
return nextNode.executeCall(frame, primaryObj, arguments);
}
}
public static final class UninitializedDispatchBoxedNode extends CallDispatchBoxedNode {
@Child protected PNode calleeNode;
private final PythonContext context;
public UninitializedDispatchBoxedNode(PythonContext context, String calleeName, PNode calleeNode) {
super(calleeName);
this.context = context;
this.calleeNode = calleeNode;
}
@Override
protected Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
CompilerDirectives.transferToInterpreterAndInvalidate();
CallDispatchNode current = this;
int depth = 0;
while (current.getParent() instanceof CallDispatchNode) {
current = (CallDispatchNode) current.getParent();
depth++;
}
CallDispatchBoxedNode specialized;
if (depth < PythonOptions.CallSiteInlineCacheMaxDepth) {
PythonCallable callee;
try {
callee = calleeNode.executePythonCallable(frame);
} catch (UnexpectedResultException e) {
throw new IllegalStateException("Call to " + e.getMessage() + " not supported.");
}
CallDispatchBoxedNode direct = create(context, primaryObj, callee, calleeNode);
specialized = replace(direct);
} else {
CallDispatchBoxedNode generic = new GenericDispatchBoxedNode(calleeName, calleeNode);
specialized = current.replace(generic);
}
return specialized.executeCall(frame, primaryObj, arguments);
}
}
public static final class GenericDispatchBoxedNode extends CallDispatchBoxedNode {
@Child protected PNode calleeNode;
public GenericDispatchBoxedNode(String calleeName, PNode calleeNode) {
super(calleeName);
this.calleeNode = calleeNode;
}
@Override
protected Object executeCall(VirtualFrame frame, PythonBasicObject primaryObj, Object... arguments) {
PythonCallable callee;
try {
callee = calleeNode.executePythonCallable(frame);
} catch (UnexpectedResultException e) {
throw new IllegalStateException("Call to " + e.getMessage() + " not supported.");
}
return callee.call(frame.pack(), arguments);
}
}
}
|
package org.ccnx.ccn.impl.security.crypto.util;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.SimpleTimeZone;
import java.util.Vector;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.ccnx.ccn.impl.support.Log;
/**
* Wrap BouncyCastle's X.509 certificate generator in a slightly more user-friendly way.
*/
public class MinimalCertificateGenerator {
/**
* A few useful OIDs that aren't in X509Extension, plus those that
* are (because they're protected there).
*/
public static final DERObjectIdentifier id_kp_serverAuth = new DERObjectIdentifier("1.3.6.1.5.5.7.3.1");
public static final DERObjectIdentifier id_kp_clientAuth = new DERObjectIdentifier("1.3.6.1.5.5.7.3.2");
public static final DERObjectIdentifier id_kp_emailProtection = new DERObjectIdentifier("1.3.6.1.5.5.7.3.4");
public static final DERObjectIdentifier id_kp_ipsec = new DERObjectIdentifier("1.3.6.1.5.5.8.2.2");
/**
* Can't just use null to get the default provider
* and have any assurance of what it is, as a user
* can change the default provider.
*/
public static final String SUN_PROVIDER = "SUN";
/**
* SHA is the official JCA name for SHA1
*/
protected static final String DEFAULT_DIGEST_ALGORITHM = "SHA";
/**
* Cache a random number generator (non-secure, used for generating
* certificate serial numbers.)
*/
protected static Random cachedRandom = new Random();
protected static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyMMddHHmmss");
protected static SimpleTimeZone TZ = new SimpleTimeZone(0, "Z");
public static long MSEC_IN_YEAR = 1000 * 60 * 60 * 24 * 365;
static {
DATE_FORMAT.setTimeZone(TZ);
}
protected X509V3CertificateGenerator _generator = new X509V3CertificateGenerator();
/**
* Cons up a list of EKUs and SubjectAltNames, then add them en masse just before signing.
*/
protected Vector<DERObjectIdentifier> _ekus = new Vector<DERObjectIdentifier>();
protected ASN1EncodableVector _subjectAltNames = new ASN1EncodableVector();
public static X509Certificate GenerateUserCertificate(KeyPair userKeyPair, String subjectDN, long duration) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException {
MinimalCertificateGenerator mg = new MinimalCertificateGenerator(subjectDN, userKeyPair.getPublic(), duration, false);
mg.setClientAuthenticationUsage();
return mg.sign(null, userKeyPair.getPrivate());
}
public static X509Certificate GenerateUserCertificate(KeyPair userKeyPair, String subjectDN, String emailAddress, long duration) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException {
MinimalCertificateGenerator mg = new MinimalCertificateGenerator(subjectDN, userKeyPair.getPublic(), duration, false);
mg.setClientAuthenticationUsage();
mg.setSecureEmailUsage(emailAddress);
return mg.sign(null, userKeyPair.getPrivate());
}
/**
* Certificate issued under an existing CA.
* @param subjectDN
* @param subjectPublicKey
* @param issuerCertificate
* @param duration
* @param isCA
* @throws CertificateEncodingException
* @throws IOException
*/
public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey,
X509Certificate issuerCertificate, long duration, boolean isCA) throws CertificateEncodingException, IOException {
this(subjectDN, subjectPublicKey, issuerCertificate.getSubjectX500Principal(), duration, isCA);
AuthorityKeyIdentifier aki =
new AuthorityKeyIdentifier(CryptoUtil.generateKeyID(subjectPublicKey));
_generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
}
/**
* Self-signed certificate (which may or may not be a CA).
* @param subjectDN
* @param keyPair
* @param duration
* @param isCA
* @throws CertificateEncodingException
* @throws IOException
*/
public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey,
long duration, boolean isCA) {
this(subjectDN, subjectPublicKey, new X500Principal(subjectDN), duration, isCA);
AuthorityKeyIdentifier aki =
new AuthorityKeyIdentifier(CryptoUtil.generateKeyID(subjectPublicKey));
_generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, aki);
}
/**
* Basic common path.
* @param subjectDN
* @param subjectPublicKey
* @param issuerDN
* @param duration
* @param isCA
*/
public MinimalCertificateGenerator(String subjectDN, PublicKey subjectPublicKey,
X500Principal issuerDN, long duration, boolean isCA) {
_generator.setSubjectDN(new X509Name(subjectDN));
_generator.setIssuerDN(issuerDN);
_generator.setSerialNumber(new BigInteger(64, cachedRandom));
_generator.setPublicKey(subjectPublicKey);
Date startTime = new Date();
Date stopTime = new Date(startTime.getTime() + duration);
_generator.setNotBefore(startTime);
_generator.setNotAfter(stopTime);
// CA key usage
final KeyUsage caKeyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyCertSign | KeyUsage.cRLSign);
// Non-CA key usage
final KeyUsage nonCAKeyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement);
if (isCA) {
_generator.addExtension(X509Extensions.KeyUsage, false, caKeyUsage);
} else {
_generator.addExtension(X509Extensions.KeyUsage, false, nonCAKeyUsage);
}
BasicConstraints bc = new BasicConstraints(isCA);
_generator.addExtension(X509Extensions.BasicConstraints, true, bc);
SubjectKeyIdentifier ski = new SubjectKeyIdentifier(CryptoUtil.generateKeyID(subjectPublicKey));
_generator.addExtension(X509Extensions.SubjectKeyIdentifier, false, ski);
}
/**
* Both adds the server authentication OID to the EKU
* extension, and adds the DNS name to the subject alt name
* extension (not marked critical). (Combines addServerAuthenticationEKU and
* addDNSNameSubjectAltName).
* @throws java.security.cert.CertificateEncodingException if the DNS name
* is not a DNS name
*/
public void setServerAuthenticationUsage(String serverDNSName) {
GeneralName name = new GeneralName(GeneralName.dNSName, serverDNSName);
_subjectAltNames.add(name);
_ekus.add(id_kp_serverAuth);
}
/**
* Adds client authentication as a usage for this
* certificate.
*/
public void setClientAuthenticationUsage() {
_ekus.add(id_kp_clientAuth);
}
/**
* Both adds the secure email OID to the EKU
* extension, and adds the email address to the subject alt name
* extension (not marked critical). (Combines addSecureEmailEKU and addEmailSubjectAltName).
* @throws java.security.cert.CertificateEncodingException if the email address
* is not an email address
*/
public void setSecureEmailUsage(String subjectEmailAddress) {
GeneralName name = new GeneralName(GeneralName.rfc822Name, subjectEmailAddress);
_subjectAltNames.add(name);
_ekus.add(id_kp_emailProtection);
}
/**
* Adds ip address to subjectAltName and IPSec usage to EKU
* @param ipAddress string form of the IP address. Assumed to be in either
* IPv4 form, "n.n.n.n", with 0<=n<256, orIPv6 form,
* "n.n.n.n.n.n.n.n", where the n's are the HEXADECIMAL form of the
* 16-bit address components.
**/
public void setIPSecUsage(String ipAddress) {
GeneralName name = new GeneralName(GeneralName.iPAddress, ipAddress);
_subjectAltNames.add(name);
_ekus.add(id_kp_ipsec);
}
public X509Certificate sign(String digestAlgorithm, PrivateKey signingKey) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException {
/**
* Finalize extensions.
*/
addExtendedKeyUsageExtension();
addSubjectAltNamesExtension();
if (null == digestAlgorithm)
digestAlgorithm = DEFAULT_DIGEST_ALGORITHM;
String signatureAlgorithm = OIDLookup.getSignatureAlgorithm(digestAlgorithm, signingKey.getAlgorithm());
if (null == signatureAlgorithm) {
Log.warning("Cannot find signature algorithm for digest " + digestAlgorithm + " and key " + signingKey.getAlgorithm() + ".");
}
_generator.setSignatureAlgorithm(signatureAlgorithm);
return _generator.generate(signingKey);
}
protected void addExtendedKeyUsageExtension() {
if (_ekus.isEmpty())
return;
ExtendedKeyUsage eku = new ExtendedKeyUsage(_ekus);
_generator.addExtension(X509Extensions.ExtendedKeyUsage, false, eku);
}
protected void addSubjectAltNamesExtension() {
if (_subjectAltNames.size() == 0)
return;
GeneralNames genNames = new GeneralNames(new DERSequence(_subjectAltNames));
_generator.addExtension(X509Extensions.SubjectAlternativeName, false, genNames);
}
}
|
package org.javers.core.diff.custom;
import org.javers.core.diff.changetype.PropertyChange;
import org.javers.core.diff.changetype.PropertyChangeMetadata;
import org.javers.core.diff.changetype.ValueChange;
import org.javers.core.metamodel.property.Property;
import org.javers.core.metamodel.type.CustomType;
import org.javers.core.metamodel.type.ValueType;
import java.util.Optional;
public interface CustomPropertyComparator<T, C extends PropertyChange> extends CustomValueComparator<T> {
/**
* Called by JaVers to calculate property-to-property diff
* between two Custom Type objects. Can calculate any of concrete {@link PropertyChange}.
*
* <br/><br/>
* Implementation of <code>compare()</code> should be consistent with
* {@link #equals(Object, Object)}.
* When <code>compare()</code> returns <code>Optional.empty()</code>,
* <code>equals()</code> should return false.
*
* @param left left (or old) value
* @param right right (or current) value
* @param metadata call {@link PropertyChangeMetadata#getAffectedCdoId()} to get
* Id of domain object being compared
* @param property property being compared
*
* @return should return Optional.empty() if compared objects are the same
*/
Optional<C> compare(T left, T right, PropertyChangeMetadata metadata, Property property);
@Override
default String toString(T value) {
return null;
}
}
|
package org.javers.model.object.graph;
import org.javers.core.model.DummyAddress;
import org.javers.core.model.DummyUser;
import org.javers.model.mapping.EntityManager;
import org.javers.test.assertion.Assertions;
import org.testng.annotations.Test;
import static com.googlecode.catchexception.CatchException.caughtException;
import static com.googlecode.catchexception.apis.CatchExceptionBdd.when;
import static org.javers.test.assertion.NodeAssert.assertThat;
import static org.javers.test.builder.DummyUserBuilder.dummyUser;
/**
* @author bartosz walacik
*/
@Test
public abstract class ObjectGraphBuilderTest {
protected EntityManager entityManager;
@Test
public void shouldBuildOneNodeGraph(){
//given
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser user = dummyUser().withName("Mad Kaz").build();
//when
ObjectNode node = graphBuilder.build(user);
//then
Assertions.assertThat(node.getEntity().getSourceClass()).isSameAs(DummyUser.class);
Assertions.assertThat(node.getCdoId()).isEqualTo("Mad Kaz") ;
Assertions.assertThat(node.getEdges()).isEmpty();
}
@Test
public void shouldBuildTwoNodesGraphForTheSameEntity(){
//given
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser user = dummyUser().withName("Mad Kaz").withSupervisor("Mad Stach").build();
//when
ObjectNode node = graphBuilder.build(user);
//then
assertThat(node).hasEdges(1)
.hasCdoWithId("Mad Kaz")
.andFirstEdge() //jump to EdgeAssert
.hasProperty("supervisor")
.isSingleEdge()
.refersToCdoWithId("Mad Stach");
}
@Test
public void shouldBuildTwoNodesGraphForDifferentEntities() {
//given
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser user = dummyUser().withName("Mad Kaz").withDetails().build();
//when
ObjectNode node = graphBuilder.build(user);
//then
assertThat(node).hasEdges(1)
.hasCdoWithId("Mad Kaz")
.andFirstEdge() //jump to EdgeAssert
.hasProperty("dummyUserDetails")
.isSingleEdge()
.refersToCdoWithId(1L);
}
@Test
public void shouldBuildThreeNodesLinearGraph() {
//kaz0 - kaz1 - kaz2
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser[] kaziki = new DummyUser[4];
for (int i=0; i<3; i++){
kaziki[i] = dummyUser().withName("Mad Kaz "+i).build();
if (i>0) {
kaziki[i-1].setSupervisor(kaziki[i]);
}
}
//when
ObjectNode node = graphBuilder.build(kaziki[0]);
//then
assertThat(node).hasEdges(1)
.hasCdoWithId("Mad Kaz 0")
.hasEdge("supervisor")
.isSingleEdge()
.refersToNodeWhich()
.hasEdges(1)
.hasCdoWithId("Mad Kaz 1")
.hasEdge("supervisor")
.isSingleEdge()
.refersToNodeWhich()
.hasNoEdges()
.hasCdoWithId("Mad Kaz 2");
}
@Test
public void shouldBuildFourNodesGraphWithThreeLevels() {
// kaz - kas.details
// stach - stach.details
//given
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser stach = dummyUser().withName("Mad Stach").withDetails(2L).build();
DummyUser kaz = dummyUser().withName("Mad Kaz").withDetails(1L).withSupervisor(stach).build();
//when
ObjectNode node = graphBuilder.build(kaz);
//then
assertThat(node).hasEdges(2)
.hasCdoWithId("Mad Kaz");
assertThat(node).hasEdge("supervisor")
.isSingleEdge()
.refersToNodeWhich()
.hasCdoWithId("Mad Stach")
.hasEdge("dummyUserDetails")
.isSingleEdge()
.refersToCdoWithId(2L);
assertThat(node).hasEdge("dummyUserDetails")
.isSingleEdge()
.refersToCdoWithId(1L);
}
@Test
public void shouldBuildGraphWithOneSingleEdgeAndOneMultiEdge(){
//given
int numberOfDetailsInList = 3;
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser stach = dummyUser().withName("Mad Stach").withDetails(2L).withDetailsList(numberOfDetailsInList).build();
//when
ObjectNode node = graphBuilder.build(stach);
//then
assertThat(node).hasEdges(2).haveAtLeastSingleEdge(1).haveAtLeastMultiEdge(1);
}
@Test
public void shouldBuildGraphWithThreeLevelsWithMultiEdge() {
// kaz - kas.details
// stach - stach.details
// detailsList
// id id id
//given
int numberOfDetailsInList = 3;
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser stach = dummyUser().withName("Mad Stach").withDetails(2L).withDetailsList(numberOfDetailsInList).build();
DummyUser kaz = dummyUser().withName("Mad Kaz").withDetails(1L).withSupervisor(stach).build();
//when
ObjectNode node = graphBuilder.build(kaz);
//then
assertThat(node).hasEdges(2)
.hasCdoWithId("Mad Kaz");
assertThat(node).hasEdge("supervisor")
.isSingleEdge()
.refersToNodeWhich()
.hasCdoWithId("Mad Stach")
.haveAtLeastMultiEdge(1)
.hasEdge("dummyUserDetails")
.isSingleEdge()
.refersToCdoWithId(2L);
assertThat(node).hasEdge("dummyUserDetails")
.isSingleEdge()
.refersToCdoWithId(1L);
}
public void shouldBuildGraphWithMultiEdgeContainMultiEdge(){
// kaz
// stach
// Em1 Em2 rob
// Em4 Em5 Em6
//given
int numberOfElements = 3;
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyUser rob = dummyUser().withName("Mad Rob").withEmployees(3).build();
DummyUser stach = dummyUser().withName("Mad Stach")
.withDetails(2L)
.withDetailsList(numberOfElements)
.withEmployees(2)
.build();
stach.getEmployeesList().add(rob);
DummyUser kaz = dummyUser().withName("Mad Kaz").withDetails(1L).withSupervisor(stach).build();
//when
ObjectNode node = graphBuilder.build(kaz);
//then
assertThat(node).hasEdges(2)
.hasCdoWithId("Mad Kaz");
assertThat(node).hasEdge("supervisor")
.isSingleEdge()
.refersToNodeWhich()
.hasCdoWithId("Mad Stach")
.haveAtLeastMultiEdge(1)
.hasEdge("employeesList")
.isMultiEdge();
}
@Test
public void shouldThrowExceptionWhenTryToBuildGraphFromValueObject() throws Throwable {
//given
ObjectGraphBuilder graphBuilder = new ObjectGraphBuilder(entityManager);
DummyAddress valueObject = new DummyAddress();
when(graphBuilder).build(valueObject);
//then
org.fest.assertions.api.Assertions.assertThat(caughtException())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Error can not build graph from an object of " + valueObject.getClass() + ".\n"
+ " Expected object managed as Entity but was Value Object.\n"
+ " Value Object isn't client's domain object.");
}
}
|
package org.uma.jmetal.auto.irace;
import org.uma.jmetal.auto.irace.crossover.CrossoverParameter;
import org.uma.jmetal.auto.irace.mutation.MutationParameter;
import org.uma.jmetal.auto.irace.selection.SelectionParameter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class GenerateIraceParameterFile {
public static void main(String[] args) {
List<Parameter> parameterList = new ArrayList<>();
parameterList.add(new CrossoverParameter());
parameterList.add(new MutationParameter());
parameterList.add(new SelectionParameter());
parameterList.add(
new Parameter(
"offspringPopulationSize",
"--offspringPopulationSize",
ParameterType.i,
"(1, 400)",
"",
Collections.emptyList()));
String formatString = "%40s %40s %7s %30s %20s\n" ;
for (Parameter parameter : parameterList) {
System.out.format(
formatString,
parameter.getName(),
parameter.getSwitch(),
parameter.getType(),
parameter.getValidValues(),
parameter.getConditionalParameters());
for (Parameter relatedParameter : parameter.getAssociatedParameters()) {
System.out.format(
formatString,
relatedParameter.getName(),
relatedParameter.getSwitch(),
relatedParameter.getType(),
relatedParameter.getValidValues(),
relatedParameter.getConditionalParameters());
}
}
}
}
|
package com.lsjwzh.widget.recyclerviewpager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
/**
* RecyclerViewPagerAdapter </br>
* Adapter wrapper.
*
* @author Green
*/
public class RecyclerViewPagerAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private final RecyclerViewPager mViewPager;
RecyclerView.Adapter<VH> mAdapter;
public RecyclerViewPagerAdapter(RecyclerViewPager viewPager, RecyclerView.Adapter<VH> adapter) {
mAdapter = adapter;
mViewPager = viewPager;
if (mAdapter != null)
setHasStableIds(mAdapter.hasStableIds());
}
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
return mAdapter.onCreateViewHolder(parent, viewType);
}
@Override
public void registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
super.registerAdapterDataObserver(observer);
mAdapter.registerAdapterDataObserver(observer);
}
@Override
public void unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
super.unregisterAdapterDataObserver(observer);
mAdapter.unregisterAdapterDataObserver(observer);
}
@Override
public void onViewRecycled(VH holder) {
super.onViewRecycled(holder);
mAdapter.onViewRecycled(holder);
}
@Override
public boolean onFailedToRecycleView(VH holder) {
return mAdapter.onFailedToRecycleView(holder);
}
@Override
public void onViewAttachedToWindow(VH holder) {
super.onViewAttachedToWindow(holder);
mAdapter.onViewAttachedToWindow(holder);
}
@Override
public void onViewDetachedFromWindow(VH holder) {
super.onViewDetachedFromWindow(holder);
mAdapter.onViewDetachedFromWindow(holder);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mAdapter.onAttachedToRecyclerView(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
mAdapter.onDetachedFromRecyclerView(recyclerView);
}
@Override
public void onBindViewHolder(VH holder, int position) {
mAdapter.onBindViewHolder(holder, position);
final View itemView = holder.itemView;
ViewGroup.LayoutParams lp;
if (itemView.getLayoutParams() == null) {
lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
} else {
lp = itemView.getLayoutParams();
if (mViewPager.getLayoutManager().canScrollHorizontally()) {
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
} else {
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
}
}
itemView.setLayoutParams(lp);
}
@Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(hasStableIds);
mAdapter.setHasStableIds(hasStableIds);
}
@Override
public int getItemCount() {
return mAdapter.getItemCount();
}
@Override
public int getItemViewType(int position) {
return mAdapter.getItemViewType(position);
}
@Override
public long getItemId(int position) {
return mAdapter.getItemId(position);
}
}
|
package br.senac.tads4.lojinha.managedbean;
import br.senac.tads4.lojinha.entidade.Categoria;
import br.senac.tads4.lojinha.service.CategoriaService;
import br.senac.tads4.lojinha.service.fakeimpl.CategoriaServiceFakeImpl;
import br.senac.tads4.lojinha.service.jpaimpl.CategoriaServiceJPAImpl;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
/**
*
* @author Fernando
*/
@Named
@ApplicationScoped
public class CategoriaBean implements Serializable {
public CategoriaBean() {
}
public List<Categoria> getLista() {
CategoriaService service = new CategoriaServiceJPAImpl();
return service.listar();
}
}
|
package com.macro.mall.dao;
import com.macro.mall.model.CmsPrefrenceAreaProductRelation;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CmsPrefrenceAreaProductRelationDao {
int insertList(@Param("list") List<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationList);
}
|
package openrtb.bidrequest.model;
import java.io.Serializable;
public final class Device implements Cloneable, Serializable {
private static final long serialVersionUID = 2458174019726387405L;
// normally recommended, but not available?
// private String ua;
private Geo geo;
private int dnt = 1;// default, don't track
private int lmt = 1;// default, don't track
private String ip;
private String ipv6;
private int devicetype = 6; // out-of-home (suggestion)
private String language;
private Object ext;
public Device() {}
public Geo getGeo() {
return geo;
}
public void setGeo(final Geo geo) {
this.geo = geo;
}
public int getDnt() {
return dnt;
}
public void setDnt(final int dnt) {
this.dnt = dnt;
}
public int getLmt() {
return lmt;
}
public void setLmt(final int lmt) {
this.lmt = lmt;
}
public int getDevicetype() {
return devicetype;
}
public void setDevicetype(final int devicetype) {
this.devicetype = devicetype;
}
public String getIp() {
return ip;
}
public void setIp(final String ip) {
this.ip = ip;
}
public void setIpv6(final String ipv6) {
this.ipv6 = ipv6;
}
public String getIpv6() {
return ipv6;
}
public String getLanguage() {
return language;
}
public void setLanguage(final String language) {
this.language = language;
}
public Object getExt() {
return ext;
}
public void setExt(final Object ext) {
this.ext = ext;
}
@Override
public Device clone() {
try {
final Device device = (Device) super.clone();
if (geo != null) {
device.setGeo(geo.clone());
}
return device;
} catch (final CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public static class Builder {
private final Device device;
public Builder() {
device = new Device();
}
public Builder setGeo(final Geo geo) {
device.setGeo(geo);
return this;
}
public Builder setDnt(final int dnt) {
device.setDnt(dnt);
return this;
}
public Builder setIp(final String ip) {
System.out.println("ip: " + ip);
if (ip != null) {
if (ip.contains(":")) {
device.setIpv6(ip);
} else {
device.setIp(ip);
}
}
return this;
}
public Builder setIpv6(final String ipv6) {
device.setIpv6(ipv6);
return this;
}
public Builder setLmt(final int lmt) {
device.setLmt(lmt);
return this;
}
public Builder setLanguage(final String iso_alpha_2) {
device.setLanguage(iso_alpha_2);
return this;
}
public Builder setExtension(final Object ext) {
device.setExt(ext);
return this;
}
public Builder setDeviceType(final int deviceType) {
device.setDevicetype(deviceType);
return this;
}
public Device build() {
return device;
}
}
@Override
public String toString() {
return String.format("Device [geo=%s, ext=%s]", geo, ext);
}
}
|
package org.opennms.web;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Category;
import org.opennms.core.utils.ThreadCategory;
/**
*
* @author <a href="dj@opennms.org">DJ Gregor</a>
*/
public class DependencyCheckingContextListener implements ServletContextListener {
private static final String IGNORE_ERRORS_PROPERTY = "dontBlameOpenNMS";
private static final String IGNORE_ERRORS_MESSAGE = "but don't blame OpenNMS for any errors that occur without switching back to a supported JVM and setting the property back to 'false', first.";
public void contextDestroyed(ServletContextEvent event) {
}
public void contextInitialized(ServletContextEvent event) {
Boolean skipJvm = new Boolean(System.getProperty("opennms.skipjvmcheck"));
if (!skipJvm) {
checkJvmName(event.getServletContext());
}
}
private void checkJvmName(ServletContext context) {
final String systemProperty = "java.vm.name";
final String[] acceptableProperties = { "HotSpot(TM)", "BEA JRockit" };
String vmName = System.getProperty(systemProperty);
if (vmName == null) {
logAndOrDie(context, "System property '" + systemProperty + "' is not set so we can't figure out if this version of Java is supported");
}
boolean ok = false;
for (String systemPropertyMatch : acceptableProperties) {
if (vmName.contains(systemPropertyMatch)) {
ok = true;
}
}
if (ok) {
log().info("System property '" + systemProperty + "' appears to contain a suitable JVM signature ('" + vmName + "') -- congratulations! ;)");
} else {
logAndOrDie(context, "System property '" + systemProperty + "' does not contain a suitable JVM signature ('" + vmName + "'). OpenNMS recommends the official Sun JVM.");
}
}
private void logAndOrDie(ServletContext context, String message) {
String webXmlPath = context.getRealPath("/WEB-INF/web.xml");
if (Boolean.parseBoolean(context.getInitParameter(IGNORE_ERRORS_PROPERTY))) {
log().warn(message);
log().warn("Context parameter '" + IGNORE_ERRORS_PROPERTY + "' is set in " + webXmlPath + ", so the above warning is not fatal, " + IGNORE_ERRORS_MESSAGE);
} else {
String howToFixMessage = "You can edit " + webXmlPath + " and change the value for the '" + IGNORE_ERRORS_PROPERTY + "' context parameter from 'false' to 'true', " + IGNORE_ERRORS_MESSAGE;
log().fatal(message);
log().fatal(howToFixMessage);
throw new RuntimeException(message + " " + howToFixMessage);
}
}
private Category log() {
return ThreadCategory.getInstance(getClass());
}
}
|
package org.caleydo.core.io.gui.dataimport;
import java.util.ArrayList;
import java.util.List;
import org.caleydo.core.gui.util.AStatusDialog;
import org.caleydo.core.gui.util.FontUtil;
import org.caleydo.core.util.collection.Pair;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* @author Christian
*
*/
public class DataImportStatusDialog extends AStatusDialog {
private String fileName;
private List<Pair<String, String>> attributes = new ArrayList<>();
/**
* @param parentShell
*/
public DataImportStatusDialog(Shell parentShell, String title, String fileName) {
super(parentShell, title);
this.fileName = fileName;
}
public void addAttribute(String attribute, String value) {
attributes.add(Pair.make(attribute, value));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite parentComposite = new Composite(parent, SWT.NONE);
parentComposite.setLayout(new GridLayout(2, false));
parentComposite.setLayoutData(new GridData(400, 200));
Label statusLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
gd.widthHint = 400;
statusLabel.setLayoutData(gd);
statusLabel.setText("The file " + fileName + " was imported successfully!");
for (Pair<String, String> attribute : attributes) {
Label attributeLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
gd = new GridData(SWT.FILL, SWT.FILL, false, false);
gd.widthHint = 320;
attributeLabel.setLayoutData(gd);
attributeLabel.setText(attribute.getFirst());
FontUtil.makeBold(attributeLabel);
Label valueLabel = new Label(parentComposite, SWT.RIGHT);
valueLabel.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
valueLabel.setText(attribute.getSecond());
}
return super.createDialogArea(parent);
}
}
|
package org.jerkar.tool.builtins.eclipse;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.jerkar.api.ide.eclipse.JkEclipseClasspathGenerator;
import org.jerkar.api.ide.eclipse.JkEclipseProject;
import org.jerkar.api.project.java.JkJavaProject;
import org.jerkar.api.system.JkLog;
import org.jerkar.api.utils.JkUtilsPath;
import org.jerkar.tool.JkBuild;
import org.jerkar.tool.JkConstants;
import org.jerkar.tool.JkDoc;
import org.jerkar.tool.JkPlugin;
import org.jerkar.tool.Main;
import org.jerkar.tool.builtins.java.JkJavaProjectBuild;
@JkDoc("Generation of Eclipse files (.project and .classpath) from actual project structure and dependencies.")
public final class JkPluginEclipse extends JkPlugin {
@JkDoc("If true, .classpath will include javadoc reference for declared dependencies.")
boolean javadoc = true;
/** If not null, this value will be used as the JRE container path when generating .classpath file.*/
@JkDoc({ "If not null, this value will be used as the JRE container path in .classpath" })
public String jreContainer = null;
/** Flag to set whether 'generateAll' task should use absolute paths instead of classpath variables */
@JkDoc({ "If true, dependency paths will be expressed relatively to Eclipse path variables instead of absolute path." })
public boolean useVarPath = false;
protected JkPluginEclipse(JkBuild build) {
super(build);
}
/** Set the JRE container to the Eclipse Standard VM type with the desired name. */
public void setStandardJREContainer(String jreName) {
jreContainer = "org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/" + jreName;
}
@Override
@JkDoc("Adds .classpath and .project generation when scaffolding.")
protected void decorateBuild() {
build.scaffolder().extraActions.chain(this::generateFiles); // If this plugin is activated while scaffolding, we want Eclipse metada file be generated.
}
@JkDoc("Generates Eclipse files (.classpath and .project) in the current directory. The files reflect project " +
"dependencies and source layout.")
public void generateFiles() {
final Path dotProject = build.baseDir().resolve(".project");
if (build instanceof JkJavaProjectBuild) {
final JkJavaProjectBuild javaProjectBuild = (JkJavaProjectBuild) build;
final JkJavaProject javaProject = javaProjectBuild.java().project();
final List<Path> importedBuildProjects = new LinkedList<>();
for (final JkBuild depBuild : build.importedBuilds().directs()) {
importedBuildProjects.add(depBuild.baseTree().root());
}
final JkEclipseClasspathGenerator classpathGenerator = new JkEclipseClasspathGenerator(javaProject);
classpathGenerator.setBuildDependencyResolver(build.buildDependencyResolver(), build.buildDependencies());
classpathGenerator.setIncludeJavadoc(true);
classpathGenerator.setJreContainer(this.jreContainer);
classpathGenerator.setImportedBuildProjects(importedBuildProjects);
classpathGenerator.setUsePathVariables(this.useVarPath);
// generator.fileDependencyToProjectSubstitution = this.fileDependencyToProjectSubstitution;
// generator.projectDependencyToFileSubstitutions = this.projectDependencyToFileSubstitutions;
final String result = classpathGenerator.generate();
final Path dotClasspath = build.baseDir().resolve(".classpath");
JkUtilsPath.write(dotClasspath, result.getBytes(Charset.forName("UTF-8")));
if (!Files.exists(dotProject)) {
JkEclipseProject.ofJavaNature(build.baseTree().root().getFileName().toString()).writeTo(dotProject);
}
} else {
if (!Files.exists(dotProject)) {
JkEclipseProject.ofSimpleNature(build.baseTree().root().getFileName().toString()).writeTo(dotProject);
}
}
}
@JkDoc("Generates Eclipse files (.project and .classpath) on all sub-folders of the current directory. Only sub-folders having a build/def directory are taken in account. See generateFiles.")
public void generateAll() {
final Iterable<Path> folders = build.baseTree()
.accept("**/" + JkConstants.BUILD_DEF_DIR, JkConstants.BUILD_DEF_DIR)
.refuse("**/build/output/**")
.stream().collect(Collectors.toList());
for (final Path folder : folders) {
final Path projectFolder = folder.getParent().getParent();
JkLog.startln("Generating Eclipse files on " + projectFolder);
Main.exec(projectFolder, "eclipse#generateFiles");
JkLog.done();
}
}
}
|
package org.smeup.sys.rt.core.e4;
import java.util.Collections;
import java.util.Map;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.smeup.sys.rt.core.QApplication;
import org.smeup.sys.rt.core.QApplicationManager;
import org.smeup.sys.rt.core.QRuntimeCorePackage;
public class E4EquinoxApplicationImpl implements IApplication {
private QApplication application = null;
@Override
public Object start(IApplicationContext context) throws Exception {
String applicationConfig = null;
String[] arguments = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS);
for (int i = 0; i < arguments.length; i++)
if (arguments[i].equals("-asupConfig")) {
applicationConfig = arguments[i + 1];
i++;
continue;
}
if (applicationConfig == null) {
System.out.println("Configuration required: see -asupConfig parameter");
return null;
}
context.applicationRunning();
// BundleContext bundleContext =
// InternalPlatform.getDefault().getBundleContext();
// Load application
QRuntimeCorePackage.eINSTANCE.eClass();
Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
Map<String, Object> m = reg.getExtensionToFactoryMap();
m.put("xmi", new XMIResourceFactoryImpl());
ResourceSet resourceSet = new ResourceSetImpl();
URI uri = null;
if(applicationConfig.startsWith("http"))
uri = URI.createURI(applicationConfig);
else
uri = URI.createFileURI(applicationConfig);
Resource resource = resourceSet.getResource(uri, true);
resource.load(Collections.EMPTY_MAP);
application = (QApplication) resource.getContents().get(0);
System.out.println("Starting " + application);
BundleContext bundleContext = FrameworkUtil.getBundle(QApplication.class).getBundleContext();
ServiceReference<QApplicationManager> applicationManagerReference = bundleContext.getServiceReference(QApplicationManager.class);
QApplicationManager applicationManager = bundleContext.getService(applicationManagerReference);
return applicationManager.start(application, System.out);
}
@Override
public void stop() {
System.out.println("Stopping " + application.getText());
}
}
|
package org.skyve.util.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.skyve.CORE;
import org.skyve.domain.Bean;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.types.Decimal;
import org.skyve.domain.types.Decimal2;
import org.skyve.impl.bind.BindUtil;
import org.skyve.impl.metadata.model.document.AssociationImpl;
import org.skyve.impl.metadata.model.document.field.Decimal10;
import org.skyve.impl.metadata.model.document.field.Decimal5;
import org.skyve.impl.metadata.model.document.field.LengthField;
import org.skyve.impl.metadata.model.document.field.LongInteger;
import org.skyve.impl.metadata.model.document.field.Text;
import org.skyve.impl.metadata.model.document.field.TextFormat;
import org.skyve.impl.metadata.model.document.field.validator.DecimalValidator;
import org.skyve.impl.metadata.model.document.field.validator.IntegerValidator;
import org.skyve.impl.metadata.model.document.field.validator.LongValidator;
import org.skyve.impl.metadata.model.document.field.validator.TextValidator.ValidatorType;
import org.skyve.impl.persistence.AbstractDocumentQuery;
import org.skyve.impl.util.TimeUtil;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.Attribute;
import org.skyve.metadata.model.Attribute.AttributeType;
import org.skyve.metadata.model.document.Collection;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.module.Module;
import org.skyve.metadata.user.User;
import org.skyve.persistence.DocumentQuery;
import org.skyve.persistence.DocumentQuery.AggregateFunction;
import org.skyve.util.Binder;
import org.skyve.util.Util;
import com.mifmif.common.regex.Generex;
public class TestUtil {
private static final Random RANDOM = new Random();
private static final String NUMBERS = "0123456789";
private static final String LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static final String ALPHA_NUMERIC = LETTERS + NUMBERS;
/**
* Name of generic text file to fill long text fields and memos.
*/
private static final String LOREM = "lorem.txt";
/**
* Cache of module.document.attributeName to loaded file random values.
*/
private static final Map<String, List<String>> DATA_CACHE = new HashMap<>();
/**
* Cache of module.document.attributeName to @DataMap fileNames.
*/
private static final Map<String, String> DATA_MAP_CACHE = new HashMap<>();
private TestUtil() {
// no implementation
}
/**
* Make an instance of a document bean with random values for its properties.
*
* @param <T> The type of Document bean to produce.
* @param user
* @param module
* @param document The document (corresponds to type T)
* @param depth How far to traverse the object graph - through associations and collections.
* There are relationships that are never ending - ie Contact has Interactions which has User which has COntact
* @return The randomly constructed bean.
* @throws Exception
*/
public static <T extends Bean> T constructRandomInstance(User user,
Module module,
Document document,
int depth)
throws Exception {
return TestUtil.constructRandomInstance(user, module, document, 1, depth);
}
/**
* Update an attribute on the given bean with a random value. Note: this method will
* not make use of any {@link DataMap} annotations present on the bean Factory. Please use
* {@link #updateAttribute(Module, Document, PersistentBean, Attribute)} instead.
*
* @param bean The bean containing the to update
* @param attribute The current value of the attribute of the bean to modify
* @return The bean with a modified attribute with a different random value if possible
* @throws IOException
*/
public static <T extends PersistentBean> T updateAttribute(final T bean, final Attribute attribute) throws IOException {
return updateAttribute(null, null, bean, attribute);
}
/**
* Update an attribute on the given bean with a random value
*
* @param module The module (corresponds to type T)
* @param document The document (corresponds to type T)
* @param bean The bean containing the to update
* @param attribute The current value of the attribute of the bean to modify
* @return The bean with a modified attribute with a different random value if possible
* @throws IOException
*/
@SuppressWarnings({ "unchecked", "boxing" })
public static <T extends PersistentBean> T updateAttribute(final Module module, final Document document, final T bean,
final Attribute attribute) throws IOException {
if (attribute == null) {
return bean;
}
final String name = attribute.getName();
final AttributeType type = attribute.getAttributeType();
switch (type) {
case bool:
// get the current value of the boolean
Boolean currentBool = (Boolean) Binder.get(bean, name);
BindUtil.set(bean, name, currentBool != null ? !currentBool : false);
break;
case colour:
BindUtil.set(bean, name, "#FFFFFF");
break;
case date:
Date futureDate = new Date();
TimeUtil.addDays(futureDate, RANDOM.nextInt(10) + 1);
BindUtil.convertAndSet(bean, name, futureDate);
break;
case dateTime:
case time:
case timestamp:
Date futureTime = new Date();
TimeUtil.addHours(futureTime, RANDOM.nextInt(10) + 1);
BindUtil.convertAndSet(bean, name, futureTime);
break;
case decimal10:
case decimal2:
case decimal5:
BindUtil.convertAndSet(bean, name, randomDecimal(attribute));
break;
case integer:
case longInteger:
BindUtil.convertAndSet(bean, name, randomInteger(attribute));
break;
case enumeration:
// get the current int value of the enum
Class<Enum<?>> clazz = (Class<Enum<?>>) Binder.getPropertyType(bean, name);
Object o = Binder.get(bean, name);
Integer currentEnum = null;
for (int i = 0; i < clazz.getEnumConstants().length; i++) {
if (clazz.getEnumConstants()[i].equals(o)) {
currentEnum = Integer.valueOf(i);
break;
}
}
// pick a new random enum
BindUtil.set(bean, name, randomEnum(clazz, currentEnum));
break;
case geometry:
BindUtil.set(bean, name, new GeometryFactory().createPoint(
new Coordinate(RANDOM.nextInt(10), RANDOM.nextInt(10))));
break;
case id:
BindUtil.set(bean, name, UUID.randomUUID().toString());
break;
case markup:
case memo:
case text:
BindUtil.set(bean, name, randomText(module, document, attribute));
break;
case association:
case collection:
case content:
case inverseMany:
case inverseOne:
break;
default:
break;
}
return bean;
}
/**
* Creates a cache key for an attribute so it is unique per document.
*/
private static String attributeKey(final Module module, final Document document, final String attributeName) {
if (attributeName != null) {
if (module != null && document != null) {
return String.format("%s.%s.%s", module.getName(), document.getName(), attributeName);
}
return attributeName;
}
return null;
}
@SuppressWarnings("incomplete-switch") // content type missing from switch statement
private static <T extends Bean> T constructRandomInstance(User user,
Module module,
Document document,
int currentDepth,
int maxDepth)
throws Exception {
T result = document.newInstance(user);
for (Attribute attribute : document.getAllAttributes()) {
String name = attribute.getName();
AttributeType type = attribute.getAttributeType();
switch (type) {
case association:
if (currentDepth < maxDepth) {
AssociationImpl association = (AssociationImpl) attribute;
Module associationModule = module;
String associationModuleRef = module.getDocumentRefs().get(association.getDocumentName())
.getReferencedModuleName();
if (associationModuleRef != null) {
associationModule = user.getCustomer().getModule(associationModuleRef);
}
Document associationDocument = associationModule.getDocument(user.getCustomer(),
association.getDocumentName());
BindUtil.set(result,
name,
TestUtil.constructRandomInstance(user,
associationModule,
associationDocument,
currentDepth + 1,
maxDepth));
}
break;
case bool:
// Random bools always are set to false as most processing changes around the true value.
// This is considered the standard case, and can be set true after the random instance is constructed if needed.
BindUtil.set(result, name, Boolean.FALSE);
break;
case collection:
if (currentDepth < maxDepth) {
Collection collection = (Collection) attribute;
Module collectionModule = module;
String collectionModuleRef = module.getDocumentRefs().get(collection.getDocumentName())
.getReferencedModuleName();
if (collectionModuleRef != null) {
collectionModule = user.getCustomer().getModule(collectionModuleRef);
}
Document collectionDocument = collectionModule.getDocument(user.getCustomer(),
collection.getDocumentName());
@SuppressWarnings("unchecked")
List<Bean> list = (List<Bean>) BindUtil.get(result, name);
list.add(TestUtil.constructRandomInstance(user,
collectionModule,
collectionDocument,
currentDepth + 1,
maxDepth));
list.add(TestUtil.constructRandomInstance(user,
collectionModule,
collectionDocument,
currentDepth + 1,
maxDepth));
}
break;
case colour:
BindUtil.set(result, name, "#FFFFFF");
break;
case date:
case dateTime:
case time:
case timestamp:
BindUtil.convertAndSet(result, name, new Date());
break;
case decimal10:
case decimal2:
case decimal5:
BindUtil.convertAndSet(result, name, randomDecimal(attribute));
break;
case integer:
case longInteger:
BindUtil.convertAndSet(result, name, randomInteger(attribute));
break;
case enumeration:
// pick a random value from the enum
@SuppressWarnings("unchecked")
Class<Enum<?>> clazz = (Class<Enum<?>>) Binder.getPropertyType(result, name);
BindUtil.set(result, name, randomEnum(clazz, null));
break;
case geometry:
BindUtil.set(result, name, new GeometryFactory().createPoint(new Coordinate(0, 0)));
break;
case id:
BindUtil.set(result, name, UUID.randomUUID().toString());
break;
case markup:
case memo:
case text:
BindUtil.set(result, name, randomText(user.getCustomerName(), module, document, attribute));
break;
}
}
return result;
}
/**
* Checks if the requested filename has a file extension.
* @param filename The name of the file to check
* @return True if the string contains a period followed by at least one character, false otherwise
*/
private static boolean hasExtension(final String filename) {
if(filename != null && filename.length() > 0 && filename.indexOf(".") > 0) {
if ((filename.substring(filename.indexOf(".") + 1)).length() > 0) {
return true;
}
}
return false;
}
/**
* Returns a random decimal which conforms to any min and max validators set,
* otherwise between 0 and 10,000.
*
* @param attribute The attribute to generate the random decimal for
* @return A random decimal
*/
public static Decimal randomDecimal(Attribute attribute) {
Decimal min = new Decimal2(0), max = new Decimal2(10000);
DecimalValidator validator = null;
if (attribute instanceof org.skyve.impl.metadata.model.document.field.Decimal2) {
org.skyve.impl.metadata.model.document.field.Decimal2 field = (org.skyve.impl.metadata.model.document.field.Decimal2) attribute;
validator = field.getValidator();
} else if (attribute instanceof Decimal5) {
Decimal5 field = (Decimal5) attribute;
validator = field.getValidator();
} else if (attribute instanceof Decimal10) {
Decimal10 field = (Decimal10) attribute;
validator = field.getValidator();
}
if (validator != null) {
if (validator.getMin() != null) {
min = validator.getMin();
}
if (validator.getMax() != null) {
max = validator.getMax();
}
}
return new Decimal2(RANDOM.nextInt(
(max.subtract(min))
.add(new Decimal2(1)).intValue())).add(min);
}
public static String randomEmail(int length) {
int addressLength = (int) Math.floor((length - 2) / 2);
int domainLength = (int) Math.floor((length - 2) / 2) - 2;
char[] address = new char[addressLength];
for (int i = 0; i < addressLength; i++) {
address[i] = Character.toChars(65 + (int) (RANDOM.nextDouble() * 26))[0];
}
char[] domain = new char[domainLength];
for (int i = 0; i < domainLength; i++) {
domain[i] = Character.toChars(65 + (int) (RANDOM.nextDouble() * 26))[0];
}
char[] code = new char[2];
for (int i = 0; i < 2; i++) {
code[i] = Character.toChars(65 + (int) (RANDOM.nextDouble() * 26))[0];
}
return String.valueOf(address) + "@" + String.valueOf(domain) + "." + String.valueOf(code);
}
/**
* Returns a random value from the enum class
*
* @param type The enum class
* @param currentValue The current int value of the enum so that it is not chosen again
* @return A random enum constant or null if this is a dynamic enum (with no class)
*/
public static <T extends Enum<?>> T randomEnum(Class<T> type, Integer currentValue) {
int x;
T[] constants = type.getEnumConstants();
if (constants == null) { // no enum values - maybe this is a dynamic enum
return null;
}
if (currentValue != null) {
int currentValueInt = currentValue.intValue();
do {
x = RANDOM.nextInt(constants.length);
}
while (x == currentValueInt);
}
else {
x = RANDOM.nextInt(constants.length);
}
return constants[x];
}
/**
* Returns a random string which complies to the format mask
* of the text attribute
*
* @param textFormat The format to comply to
* @param length The maximum length of the random string
* @return A format compliant random string
*/
private static String randomFormat(TextFormat textFormat, int length) {
String mask = textFormat.getMask();
String out = new String();
if (mask != null) {
for (int i = 0; i < mask.length(); i++) {
char c = mask.charAt(i);
switch (c) {
case '
out += NUMBERS.charAt(RANDOM.nextInt(NUMBERS.length()));
break;
case 'A':
out += ALPHA_NUMERIC.charAt(RANDOM.nextInt(ALPHA_NUMERIC.length()));
break;
case 'L':
out += LETTERS.charAt(RANDOM.nextInt(LETTERS.length()));
break;
default:
out += c;
break;
}
}
} else if (textFormat.getCase() != null) {
out = randomString(RANDOM.nextInt(length) + 1);
switch (textFormat.getCase()) {
case capital:
out = StringUtils.capitalize(out);
break;
case lower:
out = out.toLowerCase();
break;
case upper:
out = out.toUpperCase();
break;
default:
break;
}
}
if (out.length() > length) {
out = StringUtils.left(out, length);
}
return out;
}
/**
* Returns a random number which conforms to any min and max validators set,
* otherwise between 0 and 10,000.
*
* @param attribute The attribute to generate the random integer for
* @return A random integer
*/
public static Integer randomInteger(Attribute attribute) {
int min = 0, max = 10000;
// if there is a min and max make sure it is within the range
if (attribute instanceof org.skyve.impl.metadata.model.document.field.Integer) {
org.skyve.impl.metadata.model.document.field.Integer field = (org.skyve.impl.metadata.model.document.field.Integer) attribute;
IntegerValidator validator = field.getValidator();
if (validator != null) {
if (validator.getMin() != null) {
min = validator.getMin().intValue();
}
if (validator.getMax() != null) {
max = validator.getMax().intValue();
}
}
} else if (attribute instanceof org.skyve.impl.metadata.model.document.field.LongInteger) {
LongInteger field = (LongInteger) attribute;
LongValidator validator = field.getValidator();
if (validator != null) {
if (validator.getMin() != null) {
min = validator.getMin().intValue();
}
if (validator.getMax() != null) {
max = validator.getMax().intValue();
}
}
}
return Integer.valueOf(RANDOM.nextInt((max - min) + 1) + min);
}
/**
* Returns a random string which complies to the regular
* expression of the text attribute. Returns null if this
* cannot be achieved.
*
* @param regularExpression The regular expression to comply to
* @return A regex compliant random string, or null
*/
private static String randomRegex(String regularExpression) {
Generex generex = new Generex(regularExpression);
// Generate random String matching the regex
try {
String result = generex.random();
// strip boundaries
if (result.startsWith("^") && result.endsWith("$")) {
return StringUtils.substringBetween(result, "^", "$");
}
return result;
} catch (@SuppressWarnings("unused") Exception e) {
Util.LOGGER.warning("Couldnt generate compliant string for expression " + regularExpression);
}
return null;
}
private static String randomString(int length) {
char[] guts = new char[length];
for (int i = 0; i < length; i++) {
guts[i] = Character.toChars(65 + (int) (RANDOM.nextDouble() * 26))[0];
}
return String.valueOf(guts);
}
/**
* Constructs a random string for the specified {@link Text} attribute. It will attempt
* to fill the text based on:
* <ul>
* <li>the presence of a file with the attribute name, e.g. firstName.txt
* <li>the presence of a format mask
* <li>a regular expression or other validator
* <li>random text
*
* @param customerName The name of the current logged in user's customer to locate any test data files
* @param module The module this attribute belongs to
* @param document The document this attribute belongs to
* @param text The attribute to create the random data for
* @return A string containing random data for the text attribute
* @throws IOException
*/
public static String randomText(String customerName, Module module, Document document, Attribute attribute)
throws IOException {
if (attribute != null) {
String fileName = null;
Integer length = null;
// check if there is a data map for this field
if (module != null && document != null) {
final String key = attributeKey(module, document, attribute.getName());
if (DATA_MAP_CACHE.containsKey(key)) {
fileName = DATA_MAP_CACHE.get(key);
Util.LOGGER.fine(String.format("Loaded %s filename from cache", key));
} else {
String className = String.format("modules.%1$s.%2$s.%2$sFactory", module.getName(), document.getName());
Util.LOGGER.fine("Looking for factory class " + className);
try {
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(className);
if (c != null) {
Util.LOGGER.fine("Found class " + c.getName());
if (c.isAnnotationPresent(DataMap.class)) {
DataMap annotation = c.getAnnotation(DataMap.class);
Util.LOGGER.fine(
String.format("attributeName: %s fileName: %s", annotation.attributeName(),
annotation.fileName()));
if (attribute.getName().equals(annotation.attributeName())) {
fileName = annotation.fileName();
DATA_MAP_CACHE.put(key, fileName);
}
} else if (c.isAnnotationPresent(SkyveFactory.class)) {
SkyveFactory annotation = c.getAnnotation(SkyveFactory.class);
DataMap[] values = annotation.value();
for (DataMap map : values) {
Util.LOGGER.fine(
String.format("attributeName: %s fileName: %s", map.attributeName(), map.fileName()));
if (attribute.getName().equals(map.attributeName())) {
fileName = map.fileName();
DATA_MAP_CACHE.put(key, fileName);
break;
}
}
}
}
} catch (@SuppressWarnings("unused") Exception e) {
// couldn't find the extension file on the classpath
}
}
// check if there is a data file for this field
Util.LOGGER.fine(String.format(
"Looking for test data file in data/%s.txt", fileName != null ? fileName : attribute.getName()));
String value = randomValueFromFile(customerName, module, document, attribute.getName(), fileName);
if (value != null) {
Util.LOGGER.fine(String.format("Random %s: %s", attribute.getName(), value));
return value;
}
}
// check if this string has a format mask
if(attribute instanceof Text) {
Text text = (Text) attribute;
length = Integer.valueOf(text.getLength());
if (text.getFormat() != null) {
// check if it has a format mask and a regex, if so, prefer the regex
if (text.getValidator() != null && text.getValidator().getRegularExpression() != null
&& text.getValidator().getType() == null) {
// return text matching the regex
String xeger = randomRegex(text.getValidator().getRegularExpression());
if (xeger != null) {
return xeger;
}
}
// return text matching the format mask
return randomFormat(text.getFormat(), length.intValue());
} else if (text.getValidator() != null && text.getValidator().getRegularExpression() != null
&& text.getValidator().getType() == null) {
// check if this string has a regex and no validator type
String xeger = randomRegex(text.getValidator().getRegularExpression());
if (xeger != null) {
return xeger;
}
} else {
// check if this is an email address
if (text.getValidator() != null && ValidatorType.email.equals(text.getValidator().getType())) {
return randomEmail(((LengthField) text).getLength());
} else if (text.getValidator() != null && text.getValidator().getRegularExpression() != null) {
// check if this string has a regex via a validator type
String xeger = randomRegex(text.getValidator().getRegularExpression());
if (xeger != null) {
return xeger;
}
}
}
}
// return random lorem ipsum text
if (length == null) {
// set an arbitrary max length for memo fields
length = Integer.valueOf(2048);
}
String value = randomValueFromFile(null, null, null, LOREM);
if (value != null) {
String[] sentences = value.split("\\.");
shuffleArray(sentences);
int i = 0,
min = length.intValue() / 3,
r = RANDOM.nextInt(length.intValue() + 1 - min) + min;
// keep adding sentences until we hit the length
StringBuilder b = new StringBuilder();
while ((b.length() < r) && (sentences.length > i)) {
b.append(sentences[i]).append(".");
i++;
if (b.length() > r) {
String out = b.toString();
out = out.substring(0, out.length() < r ? out.length() : r).trim();
if (out.indexOf(".") > 0) {
// trim to last sentence boundary
out = out.substring(0, out.lastIndexOf(".") + 1).trim();
}
if (out.length() > 0) {
Util.LOGGER.fine(String.format("Random %s for %s with length %d(%d): %s",
attribute.getAttributeType(),
attribute.getName(),
Integer.valueOf(r),
length,
out));
return out;
}
}
}
}
// return random text
return randomString(length.intValue());
}
return null;
}
private static String randomText(Module module, Document document, Attribute attribute) throws IOException {
String customerName = null;
User user = CORE.getUser();
if (user != null) {
Customer customer = CORE.getCustomer();
if (customer != null) {
customerName = customer.getName();
}
}
return randomText(customerName, module, document, attribute);
}
/**
* <p>
* Returns a random value from the test data file for the specified attribute if
* a data file exists, null otherwise. The file name is expected to be within a
* <code>data</code> directory on the classpath with the same name (case sensitive)
* as the attribute name.
* </p>
*
* <p>
* E.g. <code>src/test/resources/data/postCode.txt</code>
* </p>
*
* <p>
* The file will be cached the first time it is requested, and loaded from memory
* for subsequent random value requests.
* </p>
*
* @param module The module this attribute belongs to
* @param document The document this attribute belongs to
* @param attributeName The attribute name to return the random value for
* @param fileName <em>Optional</em> The filename to load random values for, if it doesn't match the attribute name
* @return A random value from the data file if it exists, null otherwise
* @throws IOException
*/
private static String randomValueFromFile(String customerName, final Module module, final Document document,
final String attributeName,
final String... fileName) throws IOException {
if (attributeName != null) {
final String key = attributeKey(module, document, attributeName);
List<String> values = null;
if (DATA_CACHE.containsKey(key)) {
values = DATA_CACHE.get(key);
Util.LOGGER.fine(String.format("Loaded %s list from cache", key));
} else {
String fileToLoad = attributeName;
if (fileName != null && fileName.length == 1 && fileName[0] != null) {
fileToLoad = fileName[0];
}
// default the extension if none specified
if (fileToLoad != null && !hasExtension(fileToLoad)) {
fileToLoad = fileToLoad + ".txt";
}
Util.LOGGER.fine("Attempting to find on the classpath: " + String.format("data/%s", fileToLoad));
File file = CORE.getRepository().findResourceFile(String.format("data/%s",
fileToLoad),
customerName,
(module == null) ? null : module.getName());
if ((file != null) && file.exists()) {
try (InputStream inputStream = new FileInputStream(file)) {
values = readFromInputStream(inputStream);
DATA_CACHE.put(key, values);
Util.LOGGER.fine(String.format("Caching attribute %s with filename %s", key, fileToLoad));
if (values != null && values.size() > 0) {
Util.LOGGER.fine(String.format("Loaded %s list from %s. Found %d values.", attributeName, fileToLoad,
Integer.valueOf(values.size())));
}
}
}
}
if (values != null) {
// return random value or all of lorem
if (attributeName.equals(LOREM)) {
return values.stream().collect(Collectors.joining("\n"));
}
return values.get(RANDOM.nextInt(values.size()));
}
}
return null;
}
/**
* Attempts to read a test data file from an input stream and stores each line
* as a string in a list.
*
* @param inputStream The input stream to read from
* @return A list of strings for each line in the file, null if the input stream cannot be read
* @throws IOException
*/
private static List<String> readFromInputStream(InputStream inputStream) throws IOException {
if (inputStream == null) {
return null;
}
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
}
return list;
}
private static void shuffleArray(String[] arr) {
for (int i = arr.length - 1; i > 0; i
int index = RANDOM.nextInt(i + 1);
// Simple swap
String a = arr[index];
arr[index] = arr[i];
arr[i] = a;
}
}
/**
* <p>
* Returns a random bean tuple from the specified document query
* </p>
*
* <p>
* E.g. <code>src/test/resources/data/postCode.txt</code>
* </p>
*
* @param q - the query to find a random value from
* @return - the random bean from the query result
*/
public static <T extends Bean> T findRandomDocumentQueryResult(DocumentQuery q) {
AbstractDocumentQuery aq = ((AbstractDocumentQuery) q);
aq.clearProjections();
q.addAggregateProjection(AggregateFunction.Count, Bean.DOCUMENT_ID, "CountOfId");
long count = q.scalarResult(Number.class).longValue();
// we just need a random number
if (count > Integer.MAX_VALUE) {
count = Integer.MAX_VALUE;
} else if (count == 0) {
return null;
}
int randomIndex = new Random().nextInt((int) count - 1);
// get the random record
aq.clearProjections();
q.setFirstResult(randomIndex);
q.setMaxResults(1);
return q.beanResult();
}
}
|
package com.jediterm.terminal.model;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.jediterm.terminal.CharacterUtils;
import com.jediterm.terminal.TextStyle;
import com.jediterm.terminal.util.Pair;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author traff
*/
public class TerminalLine {
private TextEntries myTextEntries = new TextEntries();
private boolean myWrapped = false;
public TerminalLine() {
}
public TerminalLine(@NotNull TextEntry entry) {
myTextEntries.add(entry);
}
public static TerminalLine createEmpty() {
return new TerminalLine();
}
public String getText() {
final StringBuilder sb = new StringBuilder();
for (TerminalLine.TextEntry textEntry : Lists.newArrayList(myTextEntries)) {
sb.append(textEntry.getText());
}
return sb.toString();
}
public char charAt(int x) {
String text = getText();
return x < text.length() ? text.charAt(x) : CharacterUtils.EMPTY_CHAR;
}
public boolean isWrapped() {
return myWrapped;
}
public void setWrapped(boolean wrapped) {
myWrapped = wrapped;
}
public void clear() {
myTextEntries.clear();
setWrapped(false);
}
public void writeString(int x, @NotNull String str, @NotNull TextStyle style) {
writeCharacters(x, style, new CharBuffer(str));
}
private void writeCharacters(int x, @NotNull TextStyle style, @NotNull CharBuffer characters) {
int len = myTextEntries.length();
if (x >= len) {
if (x - len > 0) {
myTextEntries.add(new TextEntry(TextStyle.EMPTY, new CharBuffer(CharacterUtils.EMPTY_CHAR, x - len)));
}
myTextEntries.add(new TextEntry(style, characters));
} else {
len = Math.max(len, x + characters.length());
myTextEntries = merge(x, characters, style, myTextEntries, len);
}
}
private static TextEntries merge(int x, @NotNull CharBuffer str, @NotNull TextStyle style, @NotNull TextEntries entries, int lineLength) {
Pair<char[], TextStyle[]> pair = toBuf(entries, lineLength);
for (int i = 0; i < str.length(); i++) {
pair.first[i + x] = str.charAt(i);
pair.second[i + x] = style;
}
return collectFromBuffer(pair.first, pair.second);
}
private static Pair<char[], TextStyle[]> toBuf(TextEntries entries, int lineLength) {
Pair<char[], TextStyle[]> pair = Pair.create(new char[lineLength], new TextStyle[lineLength]);
int p = 0;
for (TextEntry entry : entries) {
for (int i = 0; i < entry.getLength(); i++) {
pair.first[p + i] = entry.getText().charAt(i);
pair.second[p + i] = entry.getStyle();
}
p += entry.getLength();
}
return pair;
}
private static TextEntries collectFromBuffer(@NotNull char[] buf, @NotNull TextStyle[] styles) {
TextEntries result = new TextEntries();
TextStyle curStyle = styles[0];
int start = 0;
for (int i = 1; i < buf.length; i++) {
if (styles[i] != curStyle) {
result.add(new TextEntry(curStyle, new CharBuffer(buf, start, i - start)));
curStyle = styles[i];
start = i;
}
}
result.add(new TextEntry(curStyle, new CharBuffer(buf, start, buf.length - start)));
return result;
}
public void deleteCharacters(int x) {
deleteCharacters(x, myTextEntries.length() - x);
// delete to the end of line : line is no more wrapped
setWrapped(false);
}
public void deleteCharacters(int x, int count) {
int p = 0;
TextEntries newEntries = new TextEntries();
for (TextEntry entry : myTextEntries) {
if (count == 0) {
newEntries.add(entry);
continue;
}
int len = entry.getLength();
if (p + len <= x) {
p += len;
newEntries.add(entry);
continue;
}
int dx = x - p;
if (dx > 0) {
//part of entry before x
newEntries.add(new TextEntry(entry.getStyle(), entry.getText().subBuffer(0, dx)));
p = x;
}
if (dx + count < len) {
//part that left after deleting count
newEntries.add(new TextEntry(entry.getStyle(), entry.getText().subBuffer(dx + count, len - (dx + count))));
count = 0;
} else {
count -= (len - dx);
p = x;
}
}
myTextEntries = newEntries;
}
public void insertBlankCharacters(int x, int count, int maxLen) {
int len = myTextEntries.length();
len = Math.min(len + count, maxLen);
char[] buf = new char[len];
TextStyle[] styles = new TextStyle[len];
int p = 0;
for (TextEntry entry : myTextEntries) {
for (int i = 0; i < entry.getLength() && p < len; i++) {
if (p == x) {
for (int j = 0; j < count; j++) {
buf[p] = CharacterUtils.EMPTY_CHAR;
styles[p] = TextStyle.EMPTY;
p++;
}
}
if (p < len) {
buf[p] = entry.getText().charAt(i);
styles[p] = entry.getStyle();
p++;
}
}
if (p >= len) {
break;
}
}
myTextEntries = collectFromBuffer(buf, styles);
}
public void clearArea(int leftX, int rightX, @NotNull TextStyle style) {
if (leftX < myTextEntries.length()) {
writeCharacters(leftX, style, new CharBuffer(CharacterUtils.EMPTY_CHAR, Math.min(myTextEntries.length(), rightX) - leftX));
}
}
@Nullable
public TextStyle getStyleAt(int x) {
int i = 0;
for (TextEntry te: myTextEntries) {
if (x>=i && x< i + te.getLength()) {
return te.getStyle();
}
i+=te.getLength();
}
return null;
}
public void process(int y, LinesBuffer.TextEntryProcessor processor) {
int x = 0;
for (TextEntry te: myTextEntries) {
processor.process(x, y, te);
x+=te.getLength();
}
}
static class TextEntry {
private final TextStyle myStyle;
private final CharBuffer myText;
public TextEntry(@NotNull TextStyle style, @NotNull CharBuffer text) {
myStyle = style;
myText = text.clone();
}
public TextStyle getStyle() {
return myStyle;
}
public CharBuffer getText() {
return myText;
}
public int getLength() {
return myText.getLength();
}
}
private static class TextEntries implements Iterable<TextEntry> {
private ArrayList<TextEntry> myTextEntries = new ArrayList<TextEntry>();
private int myLength = 0;
public void add(TextEntry entry) {
myTextEntries.add(entry);
myLength += entry.getLength();
}
private Collection<TextEntry> entries() {
return Collections.unmodifiableCollection(myTextEntries);
}
public Iterator<TextEntry> iterator() {
return entries().iterator();
}
public int length() {
return myLength;
}
public void clear() {
myTextEntries.clear();
myLength = 0;
}
}
}
|
/**
* There are two sorted arrays A and B of size m and n respectively. Find the
* median of the two sorted arrays. The overall run time complexity should be
* O(log (m+n)).
*
* Tags: Divide and Conquer, Array, Binary Search
*/
class MedianOfTwoSortedArrs {
public static void main(String[] args) {
MedianOfTwoSortedArrs m = new MedianOfTwoSortedArrs();
int[] A = {1, 2, 3, 4, 5};
int[] B = {2, 4, 5, 6, 7};
System.out.println(m.findMedianSortedArrays(A, B));
}
// Mine
public double findMedianSortedArrays(int[] A, int[] B) {
int n = A.length, m = B.length;
int[] kkp1 = findElementsWithIdxOfKKp1(A, B, (m + n - 1) / 2);
if((n+m)%2 == 1){
return kkp1[0];
}
else{
return (kkp1[0] + kkp1[1])/2.0;
}
}
private int[] findElementsWithIdxOfKKp1(int[] A, int[] B, int k){
int n = A.length;
int m = B.length;
if (n > m) return findElementsWithIdxOfKKp1(B, A, k); // shorter array first
// j = k - i, 0 <= j <= m - 1
int iMin = Math.max(0, k - m + 1);
int iMax = Math.min(n - 1, k);
int l = iMin, r = iMax;
while(l <= r){
int i = l + (r - l)/2;
int j = k - i;
if(A[i] < B[j]){
if(A[i] >= getPrevElement(B, j)){
return new int[]{A[i], Math.min(B[j], getNextElement(A, i))};
}
else{//A[i] < Bj - 1, at most k - 1 elements are in front of A[i]
l = i + 1;
}
}
else{//B[j] <= A[i]
if(B[j] >= getPrevElement(A, i)){
return new int[]{B[j], Math.min(A[i], getNextElement(B, j))};
}
else{// B[j] < Aj_1, at least k + 1 elements are in front of A[i].
r = i;
}
}
}
return new int[]{B[k - l],getNextElement(B, k - l)};
}
private int getPrevElement(int[] arr, int idx){
int n = arr.length;
if(idx <= 0) return Integer.MIN_VALUE;
if(idx < n) return arr[idx - 1];
return arr[n-1];
}
private int getNextElement(int[] arr, int idx){
int n = arr.length;
if(idx < 0) return arr[0];
if(idx < n - 1) return arr[idx + 1];
return Integer.MAX_VALUE;
}
/**
* Search in shorter array
* Find 4 possible candidates A[l-1], A[l], B[k-1], B[k-l+1]
* If total # of items is odd, return the max of A[l-1] and B[k-l], a
* If total # of items is even, get the min of A[l] and B[k-l+1], b
* Return the average of a and b
*/
public double findMedianSortedArrays(int[] A, int[] B) {
int n = A.length;
int m = B.length;
if (n > m) return findMedianSortedArrays(B, A); // shorter array first
int k = (n + m - 1) / 2; // mid position INDEX
int l = 0, r = Math.min(k, n); // r is n, NOT n-1, this is important!!
// find A[l] > B[k - l]
while (l < r) {
int midA = l + (r - l) / 2; // A[i], avoid overflow
int midB = k - midA; // B[j - 1]
if (A[midA] < B[midB])//before midB: # of A >= midA + 1, # of B = midB, total # >= K + 1
l = midA + 1; // i + 1, r
else
r = midA; // l, i
}
// A[l-1], A[l], B[k-l], and B[k-l+1]
int a = Math.max(l > 0 ? A[l - 1] : Integer.MIN_VALUE, k - l >= 0 ? B[k - l] : Integer.MIN_VALUE);
if ((n + m) % 2 == 1) return (double) a; // odd
int b = Math.min(l < n ? A[l] : Integer.MAX_VALUE, k - l + 1 < m ? B[k - l + 1] : Integer.MAX_VALUE);
return (a + b) / 2.0; // even
}
}
|
package com.scg.domain;
import static org.junit.Assert.*;
import java.util.Formatter;
import org.junit.Test;
/**
* Test the InvoiceFooter.java
* @author Brian Stamm
*/
public class InvoiceFooterTest {
//private variables
private String testDashes = "=========================================================================\n";
private String testBusiness = "Expeditors";
/**
* Tests the constructor and toString method
*/
@Test
public void testConstructorToString() {
StringBuilder sb = new StringBuilder();
Formatter ft = new Formatter(sb);
ft.format("%s\nPage Number: %d\n%s\n", testBusiness,1,testDashes);
ft.close();
String testString = sb.toString();
InvoiceFooter footer = new InvoiceFooter(testBusiness);
assertEquals(footer.toString(),testString);
}
/**
* Tests making sure the increment of page works
*/
@Test
public void testIncrementPageNumber(){
StringBuilder sb = new StringBuilder();
Formatter ft = new Formatter(sb);
ft.format("%s\nPage Number: %d\n%s\n", testBusiness,5,testDashes);
ft.close();
String testString = sb.toString();
InvoiceFooter footer = new InvoiceFooter(testBusiness);
for(int i =0; i<4;i++){
footer.incrementPageNumber();
}
assertEquals(footer.toString(),testString);
}
}
|
package org.pac4j.play;
import java.util.*;
import org.pac4j.core.context.Cookie;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.play.store.PlaySessionStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.api.mvc.AnyContentAsFormUrlEncoded;
import play.api.mvc.AnyContentAsText;
import play.api.mvc.Request;
import play.api.mvc.RequestHeader;
import play.libs.typedmap.TypedKey;
import play.mvc.Http;
import play.mvc.Result;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
/**
* <p>This class is the web context for Play (used both for Java and Scala).</p>
* <p>"Session objects" are managed by the defined {@link SessionStore}.</p>
*
* @author Jerome Leleu
* @since 1.1.0
*/
public class PlayWebContext implements WebContext {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected static final TypedKey<Map<String, Object>> PAC4J_REQUEST_ATTRIBUTES = TypedKey.create("pac4jRequestAttributes");
protected Http.RequestHeader javaRequest;
protected RequestHeader scalaRequest;
protected String requestContent;
protected PlaySessionStore sessionStore;
protected Map<String, String> responseHeaders = new HashMap<>();
protected List<Http.Cookie> responseCookies = new ArrayList<>();
protected String responseContentType;
protected boolean sessionHasChanged;
protected Http.Session session;
public PlayWebContext(final Http.RequestHeader javaRequest, final PlaySessionStore sessionStore) {
CommonHelper.assertNotNull("request", javaRequest);
CommonHelper.assertNotNull("sessionStore", sessionStore);
this.javaRequest = javaRequest;
this.sessionStore = sessionStore;
this.session = javaRequest.session();
sessionHasChanged = false;
}
public PlayWebContext(final RequestHeader scalaRequest, final PlaySessionStore sessionStore) {
this(scalaRequest.asJava(), sessionStore);
this.scalaRequest = scalaRequest;
}
public Http.RequestHeader getNativeJavaRequest() {
return javaRequest;
}
public RequestHeader getNativeScalaRequest() {
return scalaRequest;
}
@Override
public SessionStore getSessionStore() {
return this.sessionStore;
}
@Override
public Optional<String> getRequestHeader(final String name) {
return javaRequest.header(name);
}
@Override
public String getRequestMethod() {
return javaRequest.method();
}
@Override
public Optional<String> getRequestParameter(final String name) {
final Map<String, String[]> parameters = getRequestParameters();
final String[] values = parameters.get(name);
if (values != null && values.length > 0) {
return Optional.of(values[0]);
}
return Optional.empty();
}
@Override
public Map<String, String[]> getRequestParameters() {
final Map<String, String[]> parameters = new HashMap<>();
final Object body = getBody();
Map<String, String[]> p = null;
if (body instanceof Http.RequestBody) {
p = ((Http.RequestBody) body).asFormUrlEncoded();
} else if (body instanceof AnyContentAsFormUrlEncoded) {
p = ScalaCompatibility.parseBody((AnyContentAsFormUrlEncoded) body);
}
if (p != null) {
parameters.putAll(p);
}
final Map<String, String[]> urlParameters = javaRequest.queryString();
if (urlParameters != null) {
parameters.putAll(urlParameters);
}
return parameters;
}
protected Object getBody() {
if (scalaRequest != null && scalaRequest.hasBody() && scalaRequest instanceof Request) {
return ((Request) scalaRequest).body();
} else if (javaRequest.hasBody() && javaRequest instanceof Http.Request) {
return ((Http.Request) javaRequest).body();
}
return null;
}
@Override
public void setResponseHeader(final String name, final String value) {
responseHeaders.put(name, value);
}
@Override
public String getServerName() {
String[] split = javaRequest.host().split(":");
return split[0];
}
@Override
public int getServerPort() {
String defaultPort = javaRequest.secure() ? "443" : "80";
String[] split = javaRequest.host().split(":");
String portStr = split.length > 1 ? split[1] : defaultPort;
return Integer.parseInt(portStr);
}
@Override
public String getScheme() {
if (javaRequest.secure()) {
return "https";
} else {
return "http";
}
}
@Override
public boolean isSecure() { return javaRequest.secure(); }
@Override
public String getFullRequestURL() {
return getScheme() + "://" + javaRequest.host() + javaRequest.uri();
}
@Override
public String getRemoteAddr() {
return javaRequest.remoteAddress();
}
@Override
public Optional<Object> getRequestAttribute(final String name) {
Map<String, Object> attributes = javaRequest.attrs().getOptional(PAC4J_REQUEST_ATTRIBUTES).orElse(new HashMap<>());
return Optional.ofNullable(attributes.get(name));
}
@Override
public void setRequestAttribute(final String name, final Object value) {
Map<String, Object> attributes = javaRequest.attrs().getOptional(PAC4J_REQUEST_ATTRIBUTES).orElse(new HashMap<>());
attributes.put(name, value);
javaRequest = javaRequest.addAttr(PAC4J_REQUEST_ATTRIBUTES, attributes);
}
@Override
public Collection<Cookie> getRequestCookies() {
final List<Cookie> cookies = new ArrayList<>();
final Http.Cookies httpCookies = javaRequest.cookies();
httpCookies.forEach(httpCookie -> {
final Cookie cookie = new Cookie(httpCookie.name(), httpCookie.value());
if(httpCookie.domain() != null) {
cookie.setDomain(httpCookie.domain());
}
cookie.setHttpOnly(httpCookie.httpOnly());
if(httpCookie.maxAge() != null) {
cookie.setMaxAge(httpCookie.maxAge());
}
cookie.setPath(httpCookie.path());
cookie.setSecure(httpCookie.secure());
cookies.add(cookie);
});
return cookies;
}
@Override
public String getPath() {
return javaRequest.path();
}
@Override
public void addResponseCookie(final Cookie cookie) {
final Http.CookieBuilder cookieBuilder =
Http.Cookie.builder(cookie.getName(), cookie.getValue())
.withPath(cookie.getPath())
.withDomain(cookie.getDomain())
.withSecure(cookie.isSecure())
.withHttpOnly(cookie.isHttpOnly());
// in Play, maxAge: Cookie duration in seconds (null for a transient cookie [value by default], 0 or less for one that expires now)
// in pac4j, maxAge == -1 -> session cookie, 0 -> expires now, > 0, expires in x seconds
final int maxAge = cookie.getMaxAge();
if (maxAge != -1) {
cookieBuilder.withMaxAge(Duration.of(maxAge, ChronoUnit.SECONDS));
}
final Http.Cookie responseCookie = cookieBuilder.build();
responseCookies.add(responseCookie);
}
@Override
public void setResponseContentType(final String contentType) {
responseContentType = contentType;
}
@Override
public String getRequestContent() {
if (requestContent == null) {
final Object body = getBody();
if (body instanceof Http.RequestBody) {
requestContent = ((Http.RequestBody) body).asText();
} else if (body instanceof AnyContentAsText) {
requestContent = ((AnyContentAsText) body).asText().getOrElse(null);
}
}
return requestContent;
}
public Http.Session getNativeSession() {
return session;
}
public void setNativeSession(final Http.Session session) {
this.session = session;
sessionHasChanged = true;
}
public Http.Request supplementRequest(final Http.Request request) {
logger.trace("supplement request with: {}", this.javaRequest.attrs());
return request.withAttrs(this.javaRequest.attrs());
}
public Http.RequestHeader supplementRequest(final Http.RequestHeader request) {
logger.trace("supplement request with: {}", this.javaRequest.attrs());
return request.withAttrs(this.javaRequest.attrs());
}
public Result supplementResponse(final Result result) {
Result r = result;
if (responseCookies.size() > 0) {
logger.trace("supplement response with cookies: {}", responseCookies);
r = r.withCookies(responseCookies.toArray(new Http.Cookie[responseCookies.size()]));
responseCookies.clear();
}
if (responseHeaders.size() > 0) {
for (final Map.Entry<String, String> header : responseHeaders.entrySet()) {
logger.trace("supplement response with header: {}", header);
r = r.withHeader(header.getKey(), header.getValue());
}
responseHeaders.clear();
}
if (responseContentType != null) {
logger.trace("supplement response with type: {}", responseContentType);
r = r.as(responseContentType);
responseContentType = null;
}
if (sessionHasChanged) {
logger.trace("supplement response with session: {}", session);
r = r.withSession(session);
session = javaRequest.session();
sessionHasChanged = false;
}
return r;
}
}
|
package io.flutter.view;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import io.flutter.util.PathUtils;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* A class to intialize the Flutter engine.
*/
public class FlutterMain {
private static final String TAG = "FlutterMain";
// Must match values in sky::switches
private static final String AOT_SHARED_LIBRARY_PATH = "aot-shared-library-path";
private static final String AOT_SNAPSHOT_PATH_KEY = "aot-snapshot-path";
private static final String AOT_VM_SNAPSHOT_DATA_KEY = "vm-snapshot-data";
private static final String AOT_VM_SNAPSHOT_INSTR_KEY = "vm-snapshot-instr";
private static final String AOT_ISOLATE_SNAPSHOT_DATA_KEY = "isolate-snapshot-data";
private static final String AOT_ISOLATE_SNAPSHOT_INSTR_KEY = "isolate-snapshot-instr";
private static final String FLUTTER_ASSETS_DIR_KEY = "flutter-assets-dir";
// XML Attribute keys supported in AndroidManifest.xml
public static final String PUBLIC_AOT_AOT_SHARED_LIBRARY_PATH =
FlutterMain.class.getName() + '.' + AOT_SHARED_LIBRARY_PATH;
public static final String PUBLIC_AOT_VM_SNAPSHOT_DATA_KEY =
FlutterMain.class.getName() + '.' + AOT_VM_SNAPSHOT_DATA_KEY;
public static final String PUBLIC_AOT_VM_SNAPSHOT_INSTR_KEY =
FlutterMain.class.getName() + '.' + AOT_VM_SNAPSHOT_INSTR_KEY;
public static final String PUBLIC_AOT_ISOLATE_SNAPSHOT_DATA_KEY =
FlutterMain.class.getName() + '.' + AOT_ISOLATE_SNAPSHOT_DATA_KEY;
public static final String PUBLIC_AOT_ISOLATE_SNAPSHOT_INSTR_KEY =
FlutterMain.class.getName() + '.' + AOT_ISOLATE_SNAPSHOT_INSTR_KEY;
public static final String PUBLIC_FLUTTER_ASSETS_DIR_KEY =
FlutterMain.class.getName() + '.' + FLUTTER_ASSETS_DIR_KEY;
// Resource names used for components of the precompiled snapshot.
private static final String DEFAULT_AOT_SHARED_LIBRARY_PATH= "app.so";
private static final String DEFAULT_AOT_VM_SNAPSHOT_DATA = "vm_snapshot_data";
private static final String DEFAULT_AOT_VM_SNAPSHOT_INSTR = "vm_snapshot_instr";
private static final String DEFAULT_AOT_ISOLATE_SNAPSHOT_DATA = "isolate_snapshot_data";
private static final String DEFAULT_AOT_ISOLATE_SNAPSHOT_INSTR = "isolate_snapshot_instr";
private static final String DEFAULT_LIBRARY = "libflutter.so";
private static final String DEFAULT_KERNEL_BLOB = "kernel_blob.bin";
private static final String DEFAULT_FLUTTER_ASSETS_DIR = "flutter_assets";
@NonNull
private static String fromFlutterAssets(@NonNull String filePath) {
return sFlutterAssetsDir + File.separator + filePath;
}
// Mutable because default values can be overridden via config properties
private static String sAotSharedLibraryPath = DEFAULT_AOT_SHARED_LIBRARY_PATH;
private static String sAotVmSnapshotData = DEFAULT_AOT_VM_SNAPSHOT_DATA;
private static String sAotVmSnapshotInstr = DEFAULT_AOT_VM_SNAPSHOT_INSTR;
private static String sAotIsolateSnapshotData = DEFAULT_AOT_ISOLATE_SNAPSHOT_DATA;
private static String sAotIsolateSnapshotInstr = DEFAULT_AOT_ISOLATE_SNAPSHOT_INSTR;
private static String sFlutterAssetsDir = DEFAULT_FLUTTER_ASSETS_DIR;
private static boolean sInitialized = false;
private static boolean sIsPrecompiledAsBlobs = false;
private static boolean sIsPrecompiledAsSharedLibrary = false;
@Nullable
private static ResourceExtractor sResourceExtractor;
@Nullable
private static Settings sSettings;
@NonNull
private static String sSnapshotPath;
private static final class ImmutableSetBuilder<T> {
static <T> ImmutableSetBuilder<T> newInstance() {
return new ImmutableSetBuilder<>();
}
HashSet<T> set = new HashSet<>();
private ImmutableSetBuilder() {}
@NonNull
ImmutableSetBuilder<T> add(@NonNull T element) {
set.add(element);
return this;
}
@SafeVarargs
@NonNull
final ImmutableSetBuilder<T> add(@NonNull T... elements) {
for (T element : elements) {
set.add(element);
}
return this;
}
@NonNull
Set<T> build() {
return Collections.unmodifiableSet(set);
}
}
public static class Settings {
private String logTag;
@Nullable
public String getLogTag() {
return logTag;
}
/**
* Set the tag associated with Flutter app log messages.
* @param tag Log tag.
*/
public void setLogTag(String tag) {
logTag = tag;
}
}
/**
* Starts initialization of the native system.
* @param applicationContext The Android application context.
*/
public static void startInitialization(@NonNull Context applicationContext) {
startInitialization(applicationContext, new Settings());
}
/**
* Starts initialization of the native system.
* @param applicationContext The Android application context.
* @param settings Configuration settings.
*/
public static void startInitialization(@NonNull Context applicationContext, @NonNull Settings settings) {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("startInitialization must be called on the main thread");
}
// Do not run startInitialization more than once.
if (sSettings != null) {
return;
}
sSettings = settings;
long initStartTimestampMillis = SystemClock.uptimeMillis();
initConfig(applicationContext);
initAot(applicationContext);
initResources(applicationContext);
System.loadLibrary("flutter");
// We record the initialization time using SystemClock because at the start of the
// initialization we have not yet loaded the native library to call into dart_tools_api.h.
// To get Timeline timestamp of the start of initialization we simply subtract the delta
// from the Timeline timestamp at the current moment (the assumption is that the overhead
// of the JNI call is negligible).
long initTimeMillis = SystemClock.uptimeMillis() - initStartTimestampMillis;
nativeRecordStartTimestamp(initTimeMillis);
}
/**
* Blocks until initialization of the native system has completed.
* @param applicationContext The Android application context.
* @param args Flags sent to the Flutter runtime.
*/
public static void ensureInitializationComplete(@NonNull Context applicationContext, @Nullable String[] args) {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("ensureInitializationComplete must be called on the main thread");
}
if (sSettings == null) {
throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization");
}
if (sInitialized) {
return;
}
try {
// There are resources to extract. For example, the AOT blobs from the `assets` directory.
// `sResourceExtractor` is `null` if there isn't any AOT blob to extract.
if (sResourceExtractor != null) {
sResourceExtractor.waitForCompletion();
}
List<String> shellArgs = new ArrayList<>();
shellArgs.add("--icu-symbol-prefix=_binary_icudtl_dat");
ApplicationInfo applicationInfo = getApplicationInfo(applicationContext);
shellArgs.add("--icu-native-lib-path=" + applicationInfo.nativeLibraryDir + File.separator + DEFAULT_LIBRARY);
if (args != null) {
Collections.addAll(shellArgs, args);
}
if (sIsPrecompiledAsSharedLibrary) {
shellArgs.add("--" + AOT_SHARED_LIBRARY_PATH + "=" +
new File(sSnapshotPath, sAotSharedLibraryPath));
} else {
if (sIsPrecompiledAsBlobs) {
shellArgs.add("--" + AOT_SNAPSHOT_PATH_KEY + "=" + sSnapshotPath);
} else {
shellArgs.add("--cache-dir-path=" + PathUtils.getCacheDirectory(applicationContext));
shellArgs.add("--" + AOT_SNAPSHOT_PATH_KEY + "=" + PathUtils.getDataDirectory(applicationContext) + "/" + sFlutterAssetsDir);
}
shellArgs.add("--" + AOT_VM_SNAPSHOT_DATA_KEY + "=" + sAotVmSnapshotData);
shellArgs.add("--" + AOT_VM_SNAPSHOT_INSTR_KEY + "=" + sAotVmSnapshotInstr);
shellArgs.add("--" + AOT_ISOLATE_SNAPSHOT_DATA_KEY + "=" + sAotIsolateSnapshotData);
shellArgs.add("--" + AOT_ISOLATE_SNAPSHOT_INSTR_KEY + "=" + sAotIsolateSnapshotInstr);
}
if (sSettings.getLogTag() != null) {
shellArgs.add("--log-tag=" + sSettings.getLogTag());
}
String appBundlePath = findAppBundlePath(applicationContext);
String appStoragePath = PathUtils.getFilesDir(applicationContext);
String engineCachesPath = PathUtils.getCacheDirectory(applicationContext);
nativeInit(applicationContext, shellArgs.toArray(new String[0]),
appBundlePath, appStoragePath, engineCachesPath);
sInitialized = true;
} catch (Exception e) {
Log.e(TAG, "Flutter initialization failed.", e);
throw new RuntimeException(e);
}
}
/**
* Same as {@link #ensureInitializationComplete(Context, String[])} but waiting on a background
* thread, then invoking {@code callback} on the {@code callbackHandler}.
*/
public static void ensureInitializationCompleteAsync(
@NonNull Context applicationContext,
@Nullable String[] args,
@NonNull Handler callbackHandler,
@NonNull Runnable callback
) {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalStateException("ensureInitializationComplete must be called on the main thread");
}
if (sSettings == null) {
throw new IllegalStateException("ensureInitializationComplete must be called after startInitialization");
}
if (sInitialized) {
return;
}
new Thread(new Runnable() {
@Override
public void run() {
if (sResourceExtractor != null) {
sResourceExtractor.waitForCompletion();
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
ensureInitializationComplete(applicationContext.getApplicationContext(), args);
callbackHandler.post(callback);
}
});
}
}).start();
}
private static native void nativeInit(Context context, String[] args, String bundlePath, String appStoragePath, String engineCachesPath);
private static native void nativeRecordStartTimestamp(long initTimeMillis);
@NonNull
private static ApplicationInfo getApplicationInfo(@NonNull Context applicationContext) {
try {
return applicationContext
.getPackageManager()
.getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Initialize our Flutter config values by obtaining them from the
* manifest XML file, falling back to default values.
*/
private static void initConfig(@NonNull Context applicationContext) {
Bundle metadata = getApplicationInfo(applicationContext).metaData;
// There isn't a `<meta-data>` tag as a direct child of `<application>` in
// `AndroidManifest.xml`.
if (metadata == null) {
return;
}
sAotSharedLibraryPath = metadata.getString(PUBLIC_AOT_AOT_SHARED_LIBRARY_PATH, DEFAULT_AOT_SHARED_LIBRARY_PATH);
sFlutterAssetsDir = metadata.getString(PUBLIC_FLUTTER_ASSETS_DIR_KEY, DEFAULT_FLUTTER_ASSETS_DIR);
sAotVmSnapshotData = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_DATA_KEY, DEFAULT_AOT_VM_SNAPSHOT_DATA);
sAotVmSnapshotInstr = metadata.getString(PUBLIC_AOT_VM_SNAPSHOT_INSTR_KEY, DEFAULT_AOT_VM_SNAPSHOT_INSTR);
sAotIsolateSnapshotData = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_DATA_KEY, DEFAULT_AOT_ISOLATE_SNAPSHOT_DATA);
sAotIsolateSnapshotInstr = metadata.getString(PUBLIC_AOT_ISOLATE_SNAPSHOT_INSTR_KEY, DEFAULT_AOT_ISOLATE_SNAPSHOT_INSTR);
}
/**
* Extract the AOT blobs from the app's asset directory.
* This is required by the Dart runtime, so it can read the blobs.
*/
private static void initResources(@NonNull Context applicationContext) {
// When the AOT blobs are contained in the native library directory,
// we don't need to extract them manually because they are
// extracted by the Android Package Manager automatically.
if (!sSnapshotPath.equals(PathUtils.getDataDirectory(applicationContext))) {
return;
}
new ResourceCleaner(applicationContext).start();
final String dataDirPath = PathUtils.getDataDirectory(applicationContext);
final String packageName = applicationContext.getPackageName();
final PackageManager packageManager = applicationContext.getPackageManager();
final AssetManager assetManager = applicationContext.getResources().getAssets();
sResourceExtractor = new ResourceExtractor(dataDirPath, packageName, packageManager, assetManager);
sResourceExtractor
.addResource(fromFlutterAssets(sAotVmSnapshotData))
.addResource(fromFlutterAssets(sAotVmSnapshotInstr))
.addResource(fromFlutterAssets(sAotIsolateSnapshotData))
.addResource(fromFlutterAssets(sAotIsolateSnapshotInstr))
.addResource(fromFlutterAssets(DEFAULT_KERNEL_BLOB));
if (sIsPrecompiledAsSharedLibrary) {
sResourceExtractor
.addResource(sAotSharedLibraryPath);
} else {
sResourceExtractor
.addResource(sAotVmSnapshotData)
.addResource(sAotVmSnapshotInstr)
.addResource(sAotIsolateSnapshotData)
.addResource(sAotIsolateSnapshotInstr);
}
sResourceExtractor.start();
}
/**
* Returns a list of the file names at the root of the application's asset
* path.
*/
@NonNull
private static Set<String> listAssets(@NonNull Context applicationContext, @NonNull String path) {
AssetManager manager = applicationContext.getResources().getAssets();
try {
return ImmutableSetBuilder.<String>newInstance()
.add(manager.list(path))
.build();
} catch (IOException e) {
Log.e(TAG, "Unable to list assets", e);
throw new RuntimeException(e);
}
}
/**
* Returns a list of the file names at the root of the application's
* native library directory.
*/
@NonNull
private static Set<String> listLibs(@NonNull Context applicationContext) {
ApplicationInfo applicationInfo = getApplicationInfo(applicationContext);
File[] files = new File(applicationInfo.nativeLibraryDir).listFiles();
ImmutableSetBuilder builder = ImmutableSetBuilder.<String>newInstance();
for (File file : files) {
builder.add(file.getName());
}
return builder.build();
}
/**
* Determines if the APK contains a shared library or AOT snapshots,
* the file name of the snapshots and the directory where they are contained.
*
* <p>The snapshots can be contained in the app's assets or in the native library
* directory. The default names are:
*
* <ul>
* <li>`vm_snapshot_data`</li>
* <li>`vm_snapshot_instr`</li>
* <li>`isolate_snapshot_data`</li>
* <li>`isolate_snapshot_instr`</li>
* <li> Shared library: `app.so`</li>
* </ul>
*
* <p>When the blobs are contained in the native library directory,
* the format <b>`lib_%s.so`</b> is applied to the file name.
*
* <p>Note: The name of the files can be customized in the app's metadata, but the
* format is preserved.
*
* <p>The AOT snapshots and the shared library cannot exist at the same time in the APK.
*/
private static void initAot(@NonNull Context applicationContext) {
Set<String> assets = listAssets(applicationContext, "");
Set<String> libs = listLibs(applicationContext);
String aotVmSnapshotDataLib = "lib_" + sAotVmSnapshotData + ".so";
String aotVmSnapshotInstrLib = "lib_" + sAotVmSnapshotInstr + ".so";
String aotIsolateSnapshotDataLib = "lib_" + sAotIsolateSnapshotData + ".so";
String aotIsolateSnapshotInstrLib = "lib_" + sAotIsolateSnapshotInstr + ".so";
String aotSharedLibraryLib = "lib_" + sAotSharedLibraryPath + ".so";
boolean isPrecompiledBlobInLib = libs
.containsAll(Arrays.asList(
aotVmSnapshotDataLib,
aotVmSnapshotInstrLib,
aotIsolateSnapshotDataLib,
aotIsolateSnapshotInstrLib
));
if (isPrecompiledBlobInLib) {
sIsPrecompiledAsBlobs = true;
sAotVmSnapshotData = aotVmSnapshotDataLib;
sAotVmSnapshotInstr = aotVmSnapshotInstrLib;
sAotIsolateSnapshotData = aotIsolateSnapshotDataLib;
sAotIsolateSnapshotInstr = aotIsolateSnapshotInstrLib;
} else {
sIsPrecompiledAsBlobs = assets.containsAll(Arrays.asList(
sAotVmSnapshotData,
sAotVmSnapshotInstr,
sAotIsolateSnapshotData,
sAotIsolateSnapshotInstr
));
}
boolean isSharedLibraryInLib = libs.contains(aotSharedLibraryLib);
boolean isSharedLibraryInAssets = assets.contains(sAotSharedLibraryPath);
if (isSharedLibraryInLib) {
sAotSharedLibraryPath = aotSharedLibraryLib;
sIsPrecompiledAsSharedLibrary = true;
} else if (isSharedLibraryInAssets) {
sIsPrecompiledAsSharedLibrary = true;
}
if (isSharedLibraryInLib || isPrecompiledBlobInLib) {
sSnapshotPath = getApplicationInfo(applicationContext).nativeLibraryDir;
} else {
sSnapshotPath = PathUtils.getDataDirectory(applicationContext);
}
if (sIsPrecompiledAsBlobs && sIsPrecompiledAsSharedLibrary) {
throw new RuntimeException(
"Found precompiled app as shared library and as Dart VM snapshots.");
}
}
public static boolean isRunningPrecompiledCode() {
return sIsPrecompiledAsBlobs || sIsPrecompiledAsSharedLibrary;
}
@Nullable
public static String findAppBundlePath(@NonNull Context applicationContext) {
String dataDirectory = PathUtils.getDataDirectory(applicationContext);
File appBundle = new File(dataDirectory, sFlutterAssetsDir);
return appBundle.exists() ? appBundle.getPath() : null;
}
/**
* Returns the file name for the given asset.
* The returned file name can be used to access the asset in the APK
* through the {@link android.content.res.AssetManager} API.
*
* @param asset the name of the asset. The name can be hierarchical
* @return the filename to be used with {@link android.content.res.AssetManager}
*/
@NonNull
public static String getLookupKeyForAsset(@NonNull String asset) {
return fromFlutterAssets(asset);
}
/**
* Returns the file name for the given asset which originates from the
* specified packageName. The returned file name can be used to access
* the asset in the APK through the {@link android.content.res.AssetManager} API.
*
* @param asset the name of the asset. The name can be hierarchical
* @param packageName the name of the package from which the asset originates
* @return the file name to be used with {@link android.content.res.AssetManager}
*/
@NonNull
public static String getLookupKeyForAsset(@NonNull String asset, @NonNull String packageName) {
return getLookupKeyForAsset(
"packages" + File.separator + packageName + File.separator + asset);
}
}
|
package ee.ria.DigiDoc.sign;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.system.ErrnoException;
import android.system.Os;
import android.text.TextUtils;
import com.google.common.io.ByteStreams;
import org.bouncycastle.util.encoders.Base64;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import ee.ria.DigiDoc.configuration.ConfigurationProvider;
import ee.ria.libdigidocpp.Conf;
import ee.ria.libdigidocpp.DigiDocConf;
import ee.ria.libdigidocpp.digidoc;
import timber.log.Timber;
import static android.content.Context.USB_SERVICE;
public final class SignLib {
/**
* Sub-directory name in {@link Context#getCacheDir() cache dir} for schema.
*/
private static final String SCHEMA_DIR = "schema";
private static SharedPreferences.OnSharedPreferenceChangeListener tsaUrlChangeListener;
/**
* Initialize sign-lib.
* <p>
* Unzips the schema, access certificate and initializes libdigidocpp.
*/
public static void init(Context context, String tsaUrlPreferenceKey, ConfigurationProvider configurationProvider) {
initNativeLibs();
try {
initSchema(context);
} catch (IOException e) {
Timber.e(e, "Init schema failed");
}
initLibDigiDocpp(context, tsaUrlPreferenceKey, configurationProvider);
}
public static String accessTokenPass() {
return Objects.requireNonNull(Conf.instance()).PKCS12Pass();
}
public static String accessTokenPath() {
return Objects.requireNonNull(Conf.instance()).PKCS12Cert();
}
public static String libdigidocppVersion() {
return digidoc.version();
}
private static void initNativeLibs() {
System.loadLibrary("c++_shared");
System.loadLibrary("digidoc_java");
}
private static void initSchema(Context context) throws IOException {
File schemaDir = getSchemaDir(context);
try (ZipInputStream inputStream = new ZipInputStream(context.getResources()
.openRawResource(R.raw.schema))) {
ZipEntry entry;
while ((entry = inputStream.getNextEntry()) != null) {
File entryFile = new File(schemaDir, entry.getName());
FileOutputStream outputStream = new FileOutputStream(entryFile);
ByteStreams.copy(inputStream, outputStream);
outputStream.close();
}
}
}
private static void initLibDigiDocpp(Context context, String tsaUrlPreferenceKey, ConfigurationProvider configurationProvider) {
String path = getSchemaDir(context).getAbsolutePath();
try {
Os.setenv("HOME", path, true);
} catch (ErrnoException e) {
Timber.e(e, "Setting HOME environment variable failed");
}
ArrayList<String> devices = new ArrayList<>();
for (UsbDevice device : getConnectedUsbs(context)) {
devices.add(device.getProductName());
}
StringBuilder initializingMessage = new StringBuilder();
initializingMessage.append("libdigidoc/").append(getAppVersion(context));
initializingMessage.append(" (Android ").append(Build.VERSION.RELEASE).append(")");
initializingMessage.append(" Lang: ").append(Locale.getDefault().getLanguage());
initializingMessage.append(" Devices: ").append(TextUtils.join(", ", devices));
initLibDigiDocConfiguration(context, tsaUrlPreferenceKey, configurationProvider);
digidoc.initializeLib(initializingMessage.toString(), path);
}
private static void initLibDigiDocConfiguration(Context context, String tsaUrlPreferenceKey, ConfigurationProvider configurationProvider) {
DigiDocConf conf = new DigiDocConf(getSchemaDir(context).getAbsolutePath());
Conf.init(conf.transfer());
forcePKCS12Certificate();
overrideTSLUrl(configurationProvider.getTslUrl());
overrideTSLCert(configurationProvider.getTslCerts());
overrideSignatureValidationServiceUrl(configurationProvider.getSivaUrl());
overrideOCSPUrls(configurationProvider.getOCSPUrls());
initTsaUrl(context, tsaUrlPreferenceKey, configurationProvider.getTsaUrl());
}
private static void forcePKCS12Certificate() {
DigiDocConf.instance().setPKCS12Cert("798.p12");
}
private static void overrideTSLUrl(String TSLUrl) {
DigiDocConf.instance().setTSLUrl(TSLUrl);
}
private static void overrideTSLCert(List<String> tslCerts) {
DigiDocConf.instance().setTSLCert(new byte[0]); // Clear existing TSL certificates list
for (String tslCert : tslCerts) {
DigiDocConf.instance().addTSLCert(Base64.decode(tslCert));
}
}
private static void overrideSignatureValidationServiceUrl(String sivaUrl) {
DigiDocConf.instance().setVerifyServiceUri(sivaUrl);
// DigiDocConf.instance().setVerifyServiceCert(new byte[0]);
}
private static void overrideOCSPUrls(Map<String, String> ocspUrls) {
ee.ria.libdigidocpp.StringMap stringMap = new ee.ria.libdigidocpp.StringMap();
for (Map.Entry<String, String> entry : ocspUrls.entrySet()) {
stringMap.put(entry.getKey(), entry.getValue());
}
DigiDocConf.instance().setOCSPUrls(stringMap);
}
private static void initTsaUrl(Context context, String preferenceKey, String defaultValue) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (tsaUrlChangeListener != null) {
preferences.unregisterOnSharedPreferenceChangeListener(tsaUrlChangeListener);
}
tsaUrlChangeListener = new TsaUrlChangeListener(preferenceKey, defaultValue);
preferences.registerOnSharedPreferenceChangeListener(tsaUrlChangeListener);
tsaUrlChangeListener.onSharedPreferenceChanged(preferences, preferenceKey);
}
private static File getSchemaDir(Context context) {
File schemaDir = new File(context.getCacheDir(), SCHEMA_DIR);
//noinspection ResultOfMethodCallIgnored
schemaDir.mkdirs();
return schemaDir;
}
private static List<UsbDevice> getConnectedUsbs(Context context) {
UsbManager usbManager = (UsbManager)context.getSystemService(USB_SERVICE);
HashMap<String, UsbDevice> devices = usbManager.getDeviceList();
Object[] devicesArray = devices.values().toArray();
List<UsbDevice> usbDevices = new ArrayList<>();
for (Object device : devicesArray) {
usbDevices.add((UsbDevice) device);
}
return usbDevices;
}
private static StringBuilder getAppVersion(Context context) {
StringBuilder versionName = new StringBuilder();
try {
versionName.append(context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0).versionName)
.append(".")
.append(context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0).versionCode);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
private SignLib() {
}
private static final class TsaUrlChangeListener implements
SharedPreferences.OnSharedPreferenceChangeListener {
private final String preferenceKey;
private final String defaultValue;
TsaUrlChangeListener(String preferenceKey, String defaultValue) {
this.preferenceKey = preferenceKey;
this.defaultValue = defaultValue;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (TextUtils.equals(key, preferenceKey)) {
DigiDocConf.instance().setTSUrl(sharedPreferences.getString(key, defaultValue));
}
}
}
}
|
package ru.ifmo.neerc.chat.xmpp;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smackx.muc.DefaultParticipantStatusListener;
import org.jivesoftware.smackx.muc.DefaultUserStatusListener;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.Occupant;
import org.jivesoftware.smackx.packet.DelayInformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.neerc.chat.MessageListener;
import ru.ifmo.neerc.chat.UserEntry;
import ru.ifmo.neerc.chat.UserRegistry;
import ru.ifmo.neerc.chat.message.*;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
/**
* Adapts XMPP protocol to neerc-chat protocol, which based on {@link ru.ifmo.neerc.chat.message.Message}.
*
* @author Evgeny Mandrikov
*/
public abstract class XmppAdapter implements PacketListener, MessageListener {
private static final Logger LOG = LoggerFactory.getLogger(XmppAdapter.class);
private MultiUserChat chat;
private Date lastActivity = null;
public UserEntry getUser(String user, String role) {
final UserRegistry userRegistry = UserRegistry.getInstance();
final String nick = user.substring(user.indexOf('/') + 1);
UserEntry userEntry = userRegistry.findByName(nick);
final boolean power = "moderator".equalsIgnoreCase(role) || "owner".equalsIgnoreCase(role);
if (userEntry == null) {
final int id = userRegistry.getUserNumber() + 1;
LOG.debug("Added {} {} with id {}", new Object[]{role, user, id});
userEntry = new UserEntry(
id,
nick,
power
);
} else {
userEntry.setPower(power);
}
userRegistry.register(userEntry);
return userEntry;
}
private UserEntry getUser(String user) {
final Occupant occupant = chat.getOccupant(user);
final String role = occupant == null ? "member" : occupant.getRole();
return getUser(user, role);
}
@Override
public void processPacket(Packet packet) {
if (!(packet instanceof org.jivesoftware.smack.packet.Message)) {
// TODO Godin: maybe throw exception?
return;
}
org.jivesoftware.smack.packet.Message xmppMessage = (org.jivesoftware.smack.packet.Message) packet;
UserEntry user = getUser(xmppMessage.getFrom());
Date timestamp = null;
for (PacketExtension extension : xmppMessage.getExtensions()) {
if ("jabber:x:delay".equals(extension.getNamespace())) {
DelayInformation delayInformation = (DelayInformation) extension;
timestamp = delayInformation.getStamp();
} else {
LOG.debug("Found unknown packet extenstion {} with namespace {}",
extension.getClass().getSimpleName(),
extension.getNamespace()
);
}
}
Message message;
Object taskMessageProperty = xmppMessage.getProperty("taskMessage");
if (taskMessageProperty != null) {
byte[] bytes = (byte[]) taskMessageProperty;
bytes = Arrays.copyOf(bytes, bytes.length - 1); // TODO Godin: WTF?
message = MessageFactory.getInstance().deserialize(bytes);
LOG.debug("Found taskMessage: " + message.asString());
} else {
message = new UserMessage(
user.getId(),
new UserText(xmppMessage.getBody())
);
}
if (timestamp == null) {
timestamp = new Date();
}
message.setTimestamp(timestamp);
lastActivity = timestamp;
processMessage(message);
}
public void registerListeners(MultiUserChat chat) {
this.chat = chat;
chat.addMessageListener(this);
chat.addParticipantStatusListener(new MyParticipantStatusListener());
chat.addUserStatusListener(new MyUserStatusListener());
LOG.debug("Occupants count = " + chat.getOccupantsCount());
Iterator<String> occupants = chat.getOccupants();
while (occupants.hasNext()) {
String user = occupants.next();
Occupant occupant = chat.getOccupant(user);
LOG.debug("JID={} Nick={} Role={} Affiliation={}", new Object[]{
occupant.getJid(),
occupant.getNick(),
occupant.getRole(),
occupant.getAffiliation()
});
UserRegistry.getInstance().putOnline(getUser(user, occupant.getRole()), true);
}
}
private class MyUserStatusListener extends DefaultUserStatusListener {
@Override
public void moderatorGranted() {
LOG.debug("Moderator granted");
}
@Override
public void moderatorRevoked() {
LOG.debug("Moderator revoked");
}
}
private class MyParticipantStatusListener extends DefaultParticipantStatusListener {
@Override
public void joined(String participant) {
LOG.debug("JOINED: {}", participant);
processMessage(new ServerMessage(ServerMessage.USER_JOINED, getUser(participant)));
}
@Override
public void left(String participant) {
LOG.debug("LEFT: {}", participant);
processMessage(new ServerMessage(ServerMessage.USER_LEFT, getUser(participant)));
}
}
public Date getLastActivity() {
return lastActivity;
}
}
|
package fr.cph.chicago.activity;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.commons.collections4.MultiMap;
import org.apache.commons.collections4.map.MultiValueMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import fr.cph.chicago.R;
import fr.cph.chicago.connection.CtaConnect;
import fr.cph.chicago.connection.CtaRequestType;
import fr.cph.chicago.entity.Bus;
import fr.cph.chicago.entity.Pattern;
import fr.cph.chicago.entity.PatternPoint;
import fr.cph.chicago.entity.Position;
import fr.cph.chicago.exception.ConnectException;
import fr.cph.chicago.exception.ParserException;
import fr.cph.chicago.fragment.NearbyFragment;
import fr.cph.chicago.xml.Xml;
public class MapActivity extends Activity {
/** Tag **/
private static final String TAG = "MapActivity";
/** The map fragment from google api **/
private MapFragment mapFragment;
/** The map **/
private GoogleMap map;
/** Bus id **/
private Integer busId;
/** Bus route id **/
private String busRouteId;
/** Bound **/
private String bound;
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!this.isFinishing()) {
setContentView(R.layout.activity_map);
busId = getIntent().getExtras().getInt("busId");
busRouteId = getIntent().getExtras().getString("busRouteId");
bound = getIntent().getExtras().getString("bound");
new LoadCurrentPosition().execute();
new LoadBusPosition().execute();
new LoadPattern().execute();
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public final void onStart() {
super.onStart();
FragmentManager fm = getFragmentManager();
mapFragment = (MapFragment) fm.findFragmentById(R.id.map);
GoogleMapOptions options = new GoogleMapOptions();
CameraPosition camera = new CameraPosition(NearbyFragment.CHICAGO, 7, 0, 0);
options.camera(camera);
mapFragment = MapFragment.newInstance(options);
mapFragment.setRetainInstance(true);
fm.beginTransaction().replace(R.id.map, mapFragment).commit();
}
@Override
public final void onStop() {
super.onStop();
//map = null;
Log.i(TAG, "onStop");
}
@Override
public final void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
public final void onResume() {
super.onResume();
if (map == null) {
map = mapFragment.getMap();
}
new LoadCurrentPosition().execute();
new LoadBusPosition().execute();
new LoadPattern().execute();
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
busId = savedInstanceState.getInt("busId");
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("busId", busId);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public final boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main_no_search, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_refresh:
new LoadCurrentPosition().execute();
new LoadBusPosition().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
private final class LoadBusPosition extends AsyncTask<Void, Void, List<Bus>> {
@Override
protected List<Bus> doInBackground(Void... params) {
List<Bus> buses = null;
CtaConnect connect = CtaConnect.getInstance();
MultiMap<String, String> connectParam = new MultiValueMap<String, String>();
connectParam.put("vid", String.valueOf(busId));
try {
String content = connect.connect(CtaRequestType.BUS_VEHICLES, connectParam);
Xml xml = new Xml();
buses = xml.parseVehicles(content);
} catch (ConnectException e) {
Log.e(TAG, e.getMessage(), e);
} catch (ParserException e) {
Log.e(TAG, e.getMessage(), e);
}
return buses;
}
@Override
protected final void onPostExecute(final List<Bus> result) {
if (result != null) {
drawBuses(result);
centerMapOnBus(result);
}
}
}
private final class LoadCurrentPosition extends AsyncTask<Void, Void, Void> implements LocationListener {
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// flag for GPS status
private boolean isGPSEnabled = false;
// flag for network status
private boolean isNetworkEnabled = false;
/** The location **/
private Location location;
/** The position **/
private Position position;
/** The latitude **/
private double latitude;
/** THe longitude **/
private double longitude;
/** The location manager **/
private LocationManager locationManager;
@Override
protected final Void doInBackground(final Void... params) {
locationManager = (LocationManager) MapActivity.this.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
showSettingsAlert();
} else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
this, Looper.getMainLooper());
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
this, Looper.getMainLooper());
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
position = new Position();
position.setLatitude(latitude);
position.setLongitude(longitude);
}
return null;
}
@Override
protected final void onPostExecute(final Void result) {
centerMap(position);
locationManager.removeUpdates(LoadCurrentPosition.this);
}
@Override
public final void onLocationChanged(final Location location) {
}
@Override
public final void onProviderDisabled(final String provider) {
}
@Override
public final void onProviderEnabled(final String provider) {
}
@Override
public final void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
/**
* Function to show settings alert dialog
*/
private void showSettingsAlert() {
new Thread() {
public void run() {
MapActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MapActivity.this);
alertDialogBuilder.setTitle("GPS settings");
alertDialogBuilder.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialogBuilder.setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MapActivity.this.startActivity(intent);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}.start();
}
}
/**
* Load nearby data
*
* @author Carl-Philipp Harmant
*
*/
private final class LoadPattern extends AsyncTask<Void, Void, Pattern> implements LocationListener {
private Pattern pattern;
@Override
protected final Pattern doInBackground(final Void... params) {
CtaConnect connect = CtaConnect.getInstance();
MultiMap<String, String> connectParam = new MultiValueMap<String, String>();
connectParam.put("rt", busRouteId);
String boundIgnoreCase = bound.toLowerCase(Locale.US);
try {
String content = connect.connect(CtaRequestType.BUS_PATTERN, connectParam);
Xml xml = new Xml();
List<Pattern> patterns = xml.parsePatterns(content);
for (Pattern pattern : patterns) {
String directionIgnoreCase = pattern.getDirection().toLowerCase(Locale.US);
if (pattern.getDirection().equals(bound) || boundIgnoreCase.indexOf(directionIgnoreCase) != -1) {
this.pattern = pattern;
break;
}
}
} catch (ConnectException e) {
Log.e(TAG, e.getMessage(), e);
} catch (ParserException e) {
Log.e(TAG, e.getMessage(), e);
}
return this.pattern;
}
@Override
protected final void onPostExecute(final Pattern result) {
if (result != null) {
//int center = result.getPoints().size() / 2;
//centerMap(result.getPoints().get(center).getPosition());
drawPattern(result);
} else {
Toast.makeText(MapActivity.this, "Sorry, could not load the path!", Toast.LENGTH_SHORT).show();
}
}
@Override
public final void onLocationChanged(final Location location) {
}
@Override
public final void onProviderDisabled(final String provider) {
}
@Override
public final void onProviderEnabled(final String provider) {
}
@Override
public final void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
}
/**
* Center map
*
* @param positon
* the position we want to center on
*/
private void centerMap(final Position positon) {
// Because the fragment can possibly not be ready
while (mapFragment.getMap() == null) {
}
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
}
private void centerMapOnBus(List<Bus> result) {
Bus bus = result.get(0);
while (mapFragment.getMap() == null) {
}
map = mapFragment.getMap();
LatLng latLng = new LatLng(bus.getPosition().getLatitude(), bus.getPosition().getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14));
}
private void drawBuses(final List<Bus> buses) {
if (map != null) {
final List<Marker> markers = new ArrayList<Marker>();
for (Bus bus : buses) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.bus_gta_north);
Bitmap bhalfsize = Bitmap.createScaledBitmap(icon, icon.getWidth() / 4, icon.getHeight() / 4, false);
LatLng point = new LatLng(bus.getPosition().getLatitude(), bus.getPosition().getLongitude());
Marker marker = map.addMarker(new MarkerOptions().position(point).title(bus.getId() + "").snippet(bus.getId() + "")
.icon(BitmapDescriptorFactory.fromBitmap(bhalfsize))
.anchor(0.5f, 0.5f).rotation(bus.getHeading())
.flat(true));
markers.add(marker);
}
}
}
private void drawPattern(final Pattern pattern) {
if (map != null) {
final List<Marker> markers = new ArrayList<Marker>();
PolylineOptions poly = new PolylineOptions();
poly.geodesic(true).color(Color.BLUE);
for (PatternPoint patternPoint : pattern.getPoints()) {
LatLng point = new LatLng(patternPoint.getPosition().getLatitude(), patternPoint.getPosition().getLongitude());
poly.add(point);
if (patternPoint.getStopId() != null) {
Marker marker = map.addMarker(new MarkerOptions().position(point).title(patternPoint.getStopName())
.snippet(patternPoint.getSequence() + "").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
markers.add(marker);
marker.setVisible(false);
}
}
map.addPolyline(poly);
map.setOnCameraChangeListener(new OnCameraChangeListener() {
private float currentZoom = -1;
@Override
public void onCameraChange(CameraPosition pos) {
if (pos.zoom != currentZoom) {
currentZoom = pos.zoom;
if (currentZoom >= 16) {
for (Marker marker : markers) {
marker.setVisible(true);
}
} else {
for (Marker marker : markers) {
marker.setVisible(false);
}
}
}
}
});
}
}
}
|
package org.voovan.tools.log;
import org.voovan.tools.TEnv;
import org.voovan.tools.TString;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicBoolean;
public class LoggerThread implements Runnable {
private ConcurrentLinkedDeque<String> logQueue;
private OutputStream[] outputStreams;
private volatile AtomicBoolean finished = new AtomicBoolean(false);
/**
*
* @param outputStreams
*/
public LoggerThread(OutputStream[] outputStreams) {
this.logQueue = new ConcurrentLinkedDeque<String>();
this.outputStreams = outputStreams;
}
public boolean isFinished() {
return finished.get();
}
/**
*
* @return
*/
public OutputStream[] getOutputStreams() {
return outputStreams;
}
/**
*
* @param outputStreams
*/
public void setOutputStreams(OutputStream[] outputStreams) {
this.outputStreams = outputStreams;
}
/**
* OutputStream
*/
public void closeAllOutputStreams() {
try {
for (OutputStream outputStream : outputStreams) {
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*
*
* @param msg
*/
public void addLogMessage(String msg) {
logQueue.offer(msg);
}
@Override
public void run() {
String formatedMessage = null;
Thread mainThread = TEnv.getMainThread();
boolean needFlush = false;
try {
while (true) {
if(logQueue.size() == 0) {
if(needFlush) {
for (OutputStream outputStream : outputStreams) {
if (outputStream != null) {
outputStream.flush();
}
}
needFlush = false;
}
Thread.sleep(1);
if(mainThread !=null && mainThread.getState() == Thread.State.TERMINATED){
break;
}
continue;
}
formatedMessage = logQueue.poll();
if (formatedMessage != null && outputStreams!=null) {
for (OutputStream outputStream : outputStreams) {
if (outputStream != null) {
if(!(outputStream instanceof PrintStream)){
formatedMessage = TString.fastReplaceAll(formatedMessage, "\033\\[\\d{2}m", "");
}
outputStream.write(formatedMessage.getBytes());
outputStream.flush();
needFlush = true;
}
}
}
if(mainThread == null){
break;
}
}
finished.set(true);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
for (OutputStream outputStream : outputStreams) {
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Web
* @param outputStreams
* @return
*/
public synchronized static LoggerThread start(OutputStream[] outputStreams) {
LoggerThread loggerThread = new LoggerThread(outputStreams);
Thread loggerMainThread = new Thread(loggerThread,"VOOVAN@LOGGER_THREAD");
loggerMainThread.start();
return loggerThread;
}
}
|
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
package com.sharefile.api.models;
import java.io.InputStream;
import java.util.ArrayList;
import java.net.URI;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import com.google.gson.annotations.SerializedName;
import com.sharefile.api.enumerations.SFSafeEnum;
import com.sharefile.api.models.*;
public class SFAccountUser extends SFUser {
@SerializedName("IsAdministrator")
private Boolean IsAdministrator;
@SerializedName("CanCreateFolders")
private Boolean CanCreateFolders;
@SerializedName("CanUseFileBox")
private Boolean CanUseFileBox;
@SerializedName("CanManageUsers")
private Boolean CanManageUsers;
@SerializedName("IsVirtualClient")
private Boolean IsVirtualClient;
@SerializedName("DiskSpace")
private Integer DiskSpace;
@SerializedName("Bandwidth")
private Integer Bandwidth;
@SerializedName("StorageQuotaLimitGB")
private Integer StorageQuotaLimitGB;
@SerializedName("StorageQuotaPercent")
private Integer StorageQuotaPercent;
@SerializedName("EnableHardLimit")
private Boolean EnableHardLimit;
public Boolean getIsAdministrator() {
return this.IsAdministrator;
}
public void setIsAdministrator(Boolean isadministrator) {
this.IsAdministrator = isadministrator;
}
public Boolean getCanCreateFolders() {
return this.CanCreateFolders;
}
public void setCanCreateFolders(Boolean cancreatefolders) {
this.CanCreateFolders = cancreatefolders;
}
public Boolean getCanUseFileBox() {
return this.CanUseFileBox;
}
public void setCanUseFileBox(Boolean canusefilebox) {
this.CanUseFileBox = canusefilebox;
}
public Boolean getCanManageUsers() {
return this.CanManageUsers;
}
public void setCanManageUsers(Boolean canmanageusers) {
this.CanManageUsers = canmanageusers;
}
public Boolean getIsVirtualClient() {
return this.IsVirtualClient;
}
public void setIsVirtualClient(Boolean isvirtualclient) {
this.IsVirtualClient = isvirtualclient;
}
public Integer getDiskSpace() {
return this.DiskSpace;
}
public void setDiskSpace(Integer diskspace) {
this.DiskSpace = diskspace;
}
public Integer getBandwidth() {
return this.Bandwidth;
}
public void setBandwidth(Integer bandwidth) {
this.Bandwidth = bandwidth;
}
public Integer getStorageQuotaLimitGB() {
return this.StorageQuotaLimitGB;
}
public void setStorageQuotaLimitGB(Integer storagequotalimitgb) {
this.StorageQuotaLimitGB = storagequotalimitgb;
}
public Integer getStorageQuotaPercent() {
return this.StorageQuotaPercent;
}
public void setStorageQuotaPercent(Integer storagequotapercent) {
this.StorageQuotaPercent = storagequotapercent;
}
public Boolean getEnableHardLimit() {
return this.EnableHardLimit;
}
public void setEnableHardLimit(Boolean enablehardlimit) {
this.EnableHardLimit = enablehardlimit;
}
}
|
package io.xchris6041x.devin.commands;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;;
/**
* Command Options annotations to give more control and ease of use with less code.
* @author Christopher Bishop
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CommandOptions {
/**
* @return The description of what the command does.
*/
public String description() default "";
/**
* @return The command paramters in <required> [optional] format.
*/
public String parameters() default "";
/**
* @return Whether this command can only be executed by players.
*/
public boolean onlyPlayers() default false;
public String permission() default "[NULL]";
/**
* @return Whether this command can only be executed by ops.
*/
public boolean onlyOps() default false;
}
|
package com.special.ResideMenuDemo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.special.ResideMenu.ResideMenu;
import com.special.ResideMenu.ResideMenuItem;
public class MenuActivity extends FragmentActivity implements View.OnClickListener{
private ResideMenu resideMenu;
private MenuActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemProfile;
private ResideMenuItem itemCalendar;
private ResideMenuItem itemSettings;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
setUpMenu();
changeFragment(new HomeFragment());
}
private void setUpMenu() {
// attach to current activity;
resideMenu = new ResideMenu(this);
resideMenu.setBackground(R.drawable.menu_background);
resideMenu.attachToActivity(this);
resideMenu.setMenuListener(menuListener);
// create menu items;
itemHome = new ResideMenuItem(this, R.drawable.icon_home, "Home");
itemProfile = new ResideMenuItem(this, R.drawable.icon_profile, "Profile");
itemCalendar = new ResideMenuItem(this, R.drawable.icon_calendar, "Calendar");
itemSettings = new ResideMenuItem(this, R.drawable.icon_settings, "Settings");
itemHome.setOnClickListener(this);
itemProfile.setOnClickListener(this);
itemCalendar.setOnClickListener(this);
itemSettings.setOnClickListener(this);
resideMenu.addMenuItem(itemHome);
resideMenu.addMenuItem(itemProfile);
resideMenu.addMenuItem(itemCalendar);
resideMenu.addMenuItem(itemSettings);
findViewById(R.id.title_bar_menu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
resideMenu.openMenu();
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return resideMenu.onInterceptTouchEvent(ev) || super.dispatchTouchEvent(ev);
}
@Override
public void onClick(View view) {
if (view == itemHome){
changeFragment(new HomeFragment());
}else if (view == itemProfile){
changeFragment(new ProfileFragment());
}else if (view == itemCalendar){
changeFragment(new CalendarFragment());
}else if (view == itemSettings){
changeFragment(new SettingsFragment());
}
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
@Override
public void openMenu() {
Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
@Override
public void closeMenu() {
Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
private void changeFragment(Fragment targetFragment){
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
// What good method is to access resideMenu
public ResideMenu getResideMenu(){
return resideMenu;
}
}
|
/*
* Matricola: 427263
*/
package goldrush;
import java.util.Random;
/**
*
* @author cl427263
*/
public class Euge extends GoldDigger {
int chosenSite;
int tmpchs;
Euge()
{
}
public void basicChoice(int[] distances)
{
Random rr = new Random();
tmpchs = rr.nextInt(distances.length);
for(int i = 0; i < distances.length; i++)
{
if(tmpchs == distances[i])
{
chosenSite = i;
}
}
}
@Override
public int chooseDiggingSite(int[] distances)
{
basicChoice(distances);
return chosenSite;
}
@Override
public void dailyOutcome(int revenue, int[] distances, int[] diggers)
{
/*
while(false)
{
chooseDiggingSite(distances);
}
*/
}
}
|
package org.jfree.chart.annotations;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.HashUtilities;
import org.jfree.chart.util.ObjectUtilities;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.chart.util.RectangleEdge;
import org.jfree.chart.util.SerialUtilities;
/**
* An arrow and label that can be placed on an {@link XYPlot}. The arrow is
* drawn at a user-definable angle so that it points towards the (x, y)
* location for the annotation.
* <p>
* The arrow length (and its offset from the (x, y) location) is controlled by
* the tip radius and the base radius attributes. Imagine two circles around
* the (x, y) coordinate: the inner circle defined by the tip radius, and the
* outer circle defined by the base radius. Now, draw the arrow starting at
* some point on the outer circle (the point is determined by the angle), with
* the arrow tip being drawn at a corresponding point on the inner circle.
*
*/
public class XYPointerAnnotation extends XYTextAnnotation
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -4031161445009858551L;
/** The default tip radius (in Java2D units). */
public static final double DEFAULT_TIP_RADIUS = 10.0;
/** The default base radius (in Java2D units). */
public static final double DEFAULT_BASE_RADIUS = 30.0;
/** The default label offset (in Java2D units). */
public static final double DEFAULT_LABEL_OFFSET = 3.0;
/** The default arrow length (in Java2D units). */
public static final double DEFAULT_ARROW_LENGTH = 5.0;
/** The default arrow width (in Java2D units). */
public static final double DEFAULT_ARROW_WIDTH = 3.0;
/** The angle of the arrow's line (in radians). */
private double angle;
/**
* The radius from the (x, y) point to the tip of the arrow (in Java2D
* units).
*/
private double tipRadius;
/**
* The radius from the (x, y) point to the start of the arrow line (in
* Java2D units).
*/
private double baseRadius;
/** The length of the arrow head (in Java2D units). */
private double arrowLength;
/** The arrow width (in Java2D units, per side). */
private double arrowWidth;
/** The arrow stroke. */
private transient Stroke arrowStroke;
/** The arrow paint. */
private transient Paint arrowPaint;
/** The radius from the base point to the anchor point for the label. */
private double labelOffset;
/**
* Creates a new label and arrow annotation.
*
* @param label the label (<code>null</code> permitted).
* @param x the x-coordinate (measured against the chart's domain axis).
* @param y the y-coordinate (measured against the chart's range axis).
* @param angle the angle of the arrow's line (in radians).
*/
public XYPointerAnnotation(String label, double x, double y, double angle) {
super(label, x, y);
this.angle = angle;
this.tipRadius = DEFAULT_TIP_RADIUS;
this.baseRadius = DEFAULT_BASE_RADIUS;
this.arrowLength = DEFAULT_ARROW_LENGTH;
this.arrowWidth = DEFAULT_ARROW_WIDTH;
this.labelOffset = DEFAULT_LABEL_OFFSET;
this.arrowStroke = new BasicStroke(1.0f);
this.arrowPaint = Color.black;
}
/**
* Returns the angle of the arrow.
*
* @return The angle (in radians).
*
* @see #setAngle(double)
*/
public double getAngle() {
return this.angle;
}
/**
* Sets the angle of the arrow.
*
* @param angle the angle (in radians).
*
* @see #getAngle()
*/
public void setAngle(double angle) {
this.angle = angle;
}
/**
* Returns the tip radius.
*
* @return The tip radius (in Java2D units).
*
* @see #setTipRadius(double)
*/
public double getTipRadius() {
return this.tipRadius;
}
/**
* Sets the tip radius.
*
* @param radius the radius (in Java2D units).
*
* @see #getTipRadius()
*/
public void setTipRadius(double radius) {
this.tipRadius = radius;
}
/**
* Returns the base radius.
*
* @return The base radius (in Java2D units).
*
* @see #setBaseRadius(double)
*/
public double getBaseRadius() {
return this.baseRadius;
}
/**
* Sets the base radius.
*
* @param radius the radius (in Java2D units).
*
* @see #getBaseRadius()
*/
public void setBaseRadius(double radius) {
this.baseRadius = radius;
}
/**
* Returns the label offset.
*
* @return The label offset (in Java2D units).
*
* @see #setLabelOffset(double)
*/
public double getLabelOffset() {
return this.labelOffset;
}
/**
* Sets the label offset (from the arrow base, continuing in a straight
* line, in Java2D units).
*
* @param offset the offset (in Java2D units).
*
* @see #getLabelOffset()
*/
public void setLabelOffset(double offset) {
this.labelOffset = offset;
}
/**
* Returns the arrow length.
*
* @return The arrow length.
*
* @see #setArrowLength(double)
*/
public double getArrowLength() {
return this.arrowLength;
}
/**
* Sets the arrow length.
*
* @param length the length.
*
* @see #getArrowLength()
*/
public void setArrowLength(double length) {
this.arrowLength = length;
}
/**
* Returns the arrow width.
*
* @return The arrow width (in Java2D units).
*
* @see #setArrowWidth(double)
*/
public double getArrowWidth() {
return this.arrowWidth;
}
/**
* Sets the arrow width.
*
* @param width the width (in Java2D units).
*
* @see #getArrowWidth()
*/
public void setArrowWidth(double width) {
this.arrowWidth = width;
}
/**
* Returns the stroke used to draw the arrow line.
*
* @return The arrow stroke (never <code>null</code>).
*
* @see #setArrowStroke(Stroke)
*/
public Stroke getArrowStroke() {
return this.arrowStroke;
}
/**
* Sets the stroke used to draw the arrow line.
*
* @param stroke the stroke (<code>null</code> not permitted).
*
* @see #getArrowStroke()
*/
public void setArrowStroke(Stroke stroke) {
if (stroke == null) {
throw new IllegalArgumentException("Null 'stroke' not permitted.");
}
this.arrowStroke = stroke;
}
/**
* Returns the paint used for the arrow.
*
* @return The arrow paint (never <code>null</code>).
*
* @see #setArrowPaint(Paint)
*/
public Paint getArrowPaint() {
return this.arrowPaint;
}
/**
* Sets the paint used for the arrow.
*
* @param paint the arrow paint (<code>null</code> not permitted).
*
* @see #getArrowPaint()
*/
public void setArrowPaint(Paint paint) {
if (paint == null) {
throw new IllegalArgumentException("Null 'paint' argument.");
}
this.arrowPaint = paint;
}
/**
* Draws the annotation.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param dataArea the data area.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param rendererIndex the renderer index.
* @param info the plot rendering info.
*/
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea,
ValueAxis domainAxis, ValueAxis rangeAxis,
int rendererIndex,
PlotRenderingInfo info) {
PlotOrientation orientation = plot.getOrientation();
RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(
plot.getDomainAxisLocation(), orientation);
RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(
plot.getRangeAxisLocation(), orientation);
double j2DX = domainAxis.valueToJava2D(getX(), dataArea, domainEdge);
double j2DY = rangeAxis.valueToJava2D(getY(), dataArea, rangeEdge);
if (orientation == PlotOrientation.HORIZONTAL) {
double temp = j2DX;
j2DX = j2DY;
j2DY = temp;
}
double startX = j2DX + Math.cos(this.angle) * this.baseRadius;
double startY = j2DY + Math.sin(this.angle) * this.baseRadius;
double endX = j2DX + Math.cos(this.angle) * this.tipRadius;
double endY = j2DY + Math.sin(this.angle) * this.tipRadius;
double arrowBaseX = endX + Math.cos(this.angle) * this.arrowLength;
double arrowBaseY = endY + Math.sin(this.angle) * this.arrowLength;
double arrowLeftX = arrowBaseX
+ Math.cos(this.angle + Math.PI / 2.0) * this.arrowWidth;
double arrowLeftY = arrowBaseY
+ Math.sin(this.angle + Math.PI / 2.0) * this.arrowWidth;
double arrowRightX = arrowBaseX
- Math.cos(this.angle + Math.PI / 2.0) * this.arrowWidth;
double arrowRightY = arrowBaseY
- Math.sin(this.angle + Math.PI / 2.0) * this.arrowWidth;
GeneralPath arrow = new GeneralPath();
arrow.moveTo((float) endX, (float) endY);
arrow.lineTo((float) arrowLeftX, (float) arrowLeftY);
arrow.lineTo((float) arrowRightX, (float) arrowRightY);
arrow.closePath();
g2.setStroke(this.arrowStroke);
g2.setPaint(this.arrowPaint);
Line2D line = new Line2D.Double(startX, startY, arrowBaseX, arrowBaseY);
g2.draw(line);
g2.fill(arrow);
// draw the label
double labelX = j2DX + Math.cos(this.angle) * (this.baseRadius
+ this.labelOffset);
double labelY = j2DY + Math.sin(this.angle) * (this.baseRadius
+ this.labelOffset);
g2.setFont(getFont());
Shape hotspot = TextUtilities.calculateRotatedStringBounds(
getText(), g2, (float) labelX, (float) labelY, getTextAnchor(),
getRotationAngle(), getRotationAnchor());
if (getBackgroundPaint() != null) {
g2.setPaint(getBackgroundPaint());
g2.fill(hotspot);
}
g2.setPaint(getPaint());
TextUtilities.drawRotatedString(getText(), g2, (float) labelX,
(float) labelY, getTextAnchor(), getRotationAngle(),
getRotationAnchor());
if (isOutlineVisible()) {
g2.setStroke(getOutlineStroke());
g2.setPaint(getOutlinePaint());
g2.draw(hotspot);
}
String toolTip = getToolTipText();
String url = getURL();
if (toolTip != null || url != null) {
addEntity(info, hotspot, rendererIndex, toolTip, url);
}
}
/**
* Tests this annotation for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof XYPointerAnnotation)) {
return false;
}
XYPointerAnnotation that = (XYPointerAnnotation) obj;
if (this.angle != that.angle) {
return false;
}
if (this.tipRadius != that.tipRadius) {
return false;
}
if (this.baseRadius != that.baseRadius) {
return false;
}
if (this.arrowLength != that.arrowLength) {
return false;
}
if (this.arrowWidth != that.arrowWidth) {
return false;
}
if (!this.arrowPaint.equals(that.arrowPaint)) {
return false;
}
if (!ObjectUtilities.equal(this.arrowStroke, that.arrowStroke)) {
return false;
}
if (this.labelOffset != that.labelOffset) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = super.hashCode();
long temp = Double.doubleToLongBits(this.angle);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.tipRadius);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.baseRadius);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.arrowLength);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.arrowWidth);
result = 37 * result + (int) (temp ^ (temp >>> 32));
result = result * 37 + HashUtilities.hashCodeForPaint(this.arrowPaint);
result = result * 37 + this.arrowStroke.hashCode();
temp = Double.doubleToLongBits(this.labelOffset);
result = 37 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/**
* Returns a clone of the annotation.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the annotation can't be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.arrowPaint, stream);
SerialUtilities.writeStroke(this.arrowStroke, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.arrowPaint = SerialUtilities.readPaint(stream);
this.arrowStroke = SerialUtilities.readStroke(stream);
}
}
|
// G u i A c t i o n s //
// Contact author at herve.bitteur@laposte.net to report bugs & suggestions. //
package omr.ui;
import omr.Main;
import omr.constant.Constant;
import omr.constant.ConstantSet;
import omr.constant.UnitManager;
import omr.constant.UnitModel;
import omr.constant.UnitTreeTable;
import omr.glyph.ui.ShapeColorChooser;
import omr.plugin.Dependency;
import omr.plugin.Plugin;
import omr.plugin.PluginType;
import omr.ui.treetable.JTreeTable;
import omr.util.Implement;
import omr.util.Logger;
import omr.util.Memory;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import javax.swing.*;
/**
* Class <code>GuiActions</code> gathers individual actions trigerred from the
* main Gui interface.
*
* @author Hervé Bitteur and Brenton Partridge
* @version $Id$
*/
public class GuiActions
{
/** Specific application parameters */
private static final Constants constants = new Constants();
/** Usual logger utility */
private static final Logger logger = Logger.getLogger(GuiActions.class);
/** Color chooser for shapes */
private static JFrame shapeColorFrame;
/** Options UI */
private static JFrame optionsFrame;
/** Class for reflected access of java.awt.Desktop */
private static Class desktopClass;
static
{
try {
desktopClass = Class.forName("java.awt.Desktop");
}
catch (Exception e) {
logger.warning("Desktop loading failed", e);
}
}
// isDesktopSupported //
/**
* Returns if <code>java.awt.Desktop</code> is present and
* its static method <code>isDesktopSupported()</code> returns true.
*/
private static boolean isDesktopSupported ()
{
if (desktopClass == null) return false;
try {
return (Boolean)desktopClass.getMethod("isDesktopSupported").invoke(null);
}
catch (Exception e) {
logger.fine(e.toString());
return false;
}
}
// launchBrowser //
private static void launchBrowser (String urlString)
{
try {
// Safer
if (!isDesktopSupported()) {
logger.warning("Desktop features are not supported on this platform");
return;
}
else {
try {
URI uri = URI.create(urlString);
Object desktop = desktopClass.getMethod("getDesktop").invoke(null);
desktopClass.getMethod("browse", URI.class).invoke(desktop, uri);
} catch (InvocationTargetException ex) {
logger.warning("Could not launch the browser on " + urlString, ex.getCause());
}
}
}
catch (Exception e) {
logger.warning("Desktop access failed", e);
}
}
// AboutAction //
/**
* Class <code>AboutAction</code> opens an 'About' dialog with some
* information about the application.
*
*/
@Plugin(type = PluginType.HELP, dependency = Dependency.NONE)
public static class AboutAction
extends AbstractAction
{
private StringBuilder sb = null;
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
if (sb == null) {
sb = new StringBuilder();
sb.append("<HTML><TABLE BORDER='0'>");
// Application information
addTableRow("Application", Main.getToolName());
// Version information
addTableRow("Version", Main.getToolVersion());
// Build information, if available
addTableRow(
"Build",
(Main.getToolBuild() != null) ? Main.getToolBuild() : "");
// Launch information
addTableRow("Classes", Main.getClassesContainer());
sb.append("</TABLE></HTML>");
}
Main.getGui()
.displayMessage(sb.toString());
}
private void addTableRow (String name,
Object value)
{
sb.append("<TR><TH>")
.append(name)
.append("<TH><TD>")
.append(value)
.append("</TD></TR>");
}
}
// ClearLogAction //
/**
* Class <code>ClearLogAction</code> erases the content of the log display
* (but not the content of the log itself)
*/
@Plugin(type = PluginType.LOG_VIEW, onToolbar = true)
public static class ClearLogAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
Main.getGui().logPane.clearLog();
}
}
// ExitAction //
/**
* Class <code>ExitAction</code> allows to exit the application
*
*/
@Plugin(type = PluginType.GENERAL_END, dependency = Dependency.NONE, onToolbar = false)
public static class ExitAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
Main.getGui()
.exit();
}
}
// FineAction //
/**
* Class <code>FineAction</code> allows to set looger level to FINE in the
* Selection mechanism
*
*/
@Plugin(type = PluginType.TEST, onToolbar = true)
public static class FineAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
Logger.getLogger(omr.selection.Selection.class)
.setLevel("FINE");
}
}
// MemoryAction //
/**
* Class <code>MemoryAction</code> desplays the current value of occupied
* memory
*
*/
@Plugin(type = PluginType.TOOL)
public static class MemoryAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
logger.info("Occupied memory is " + Memory.getValue() + " bytes");
}
}
// OperationAction //
/**
* Class <code>OperationAction</code> launches a browser on Audiveris Operation manual
*/
@Plugin(type = PluginType.HELP, dependency = Dependency.NONE)
public static class OperationAction
extends AbstractAction
{
public OperationAction ()
{
setEnabled(isDesktopSupported());
}
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
launchBrowser(constants.operationUrl.getValue());
}
}
// OptionsAction //
/**
* Class <code>OptionsAction</code> opens a window where units options
* (logger level, constants) can be managed
*
*/
@Plugin(type = PluginType.TOOL)
public static class OptionsAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
if (optionsFrame == null) {
// Preload constant units
UnitManager.getInstance(Main.class.getName());
optionsFrame = new JFrame("Units Options");
optionsFrame.getContentPane()
.setLayout(new BorderLayout());
JToolBar toolBar = new JToolBar(JToolBar.HORIZONTAL);
optionsFrame.getContentPane()
.add(toolBar, BorderLayout.NORTH);
JButton button = new JButton(
new AbstractAction() {
public void actionPerformed (ActionEvent e)
{
UnitManager.getInstance()
.dumpAllUnits();
}
});
button.setText("Dump all Units");
toolBar.add(button);
UnitModel cm = new UnitModel();
JTreeTable jtt = new UnitTreeTable(cm);
optionsFrame.getContentPane()
.add(new JScrollPane(jtt));
optionsFrame.pack();
optionsFrame.setSize(
constants.paramWidth.getValue(),
constants.paramHeight.getValue());
}
optionsFrame.setVisible(true);
}
}
// ShapeColorAction //
/**
* Class <code>ShapeColorAction</code> allows to define the colors of
* predefined shapes
*
*/
@Plugin(type = PluginType.TOOL)
public static class ShapeColorAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
if (shapeColorFrame == null) {
shapeColorFrame = new JFrame("ShapeColorChooser");
// Create and set up the content pane.
JComponent newContentPane = new ShapeColorChooser().getComponent();
newContentPane.setOpaque(true); //content panes must be opaque
shapeColorFrame.setContentPane(newContentPane);
// Realize the window.
shapeColorFrame.pack();
}
shapeColorFrame.setVisible(true);
}
}
// TestAction //
/**
* Class <code>TestAction</code> triggers a generic test methody
*
*/
@Plugin(type = PluginType.TEST, onToolbar = true)
public static class TestAction
extends AbstractAction
{
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
UITest.test();
}
}
// WebSiteAction //
/**
* Class <code>WebSiteAction</code> launches a browser on Audiveris website
*/
@Plugin(type = PluginType.HELP, dependency = Dependency.NONE)
public static class WebSiteAction
extends AbstractAction
{
public WebSiteAction ()
{
setEnabled(isDesktopSupported());
}
@Implement(ActionListener.class)
public void actionPerformed (ActionEvent e)
{
launchBrowser(constants.webSiteUrl.getValue());
}
}
// Constants //
private static final class Constants
extends ConstantSet
{
PixelCount paramHeight = new PixelCount(
500,
"Height of the Options frame");
PixelCount paramWidth = new PixelCount(
900,
"Width of the Options frame");
Constant.String webSiteUrl = new Constant.String(
"https://audiveris.dev.java.net",
"URL of Audiveris home page");
Constant.String operationUrl = new Constant.String(
"https://audiveris.dev.java.net/nonav/docs/manual/index.html?manual=operation",
"URL of Audiveris operation manual");
}
}
|
package org.hive2hive.core;
import java.io.File;
import java.net.InetAddress;
import net.tomp2p.peers.Number160;
import org.apache.commons.io.FileUtils;
import org.hive2hive.core.security.EncryptionUtil.AES_KEYLENGTH;
import org.hive2hive.core.security.EncryptionUtil.RSA_KEYLENGTH;
public interface H2HConstants {
// TODO this interface should be more structured and documented in a consistent way
// H2HNode default values
public static final int DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024; // 25 MB
public static final int DEFAULT_MAX_NUM_OF_VERSIONS = 100;
public static final int DEFAULT_MAX_SIZE_OF_ALL_VERSIONS = DEFAULT_MAX_FILE_SIZE
* DEFAULT_MAX_NUM_OF_VERSIONS;
public static final int DEFAULT_CHUNK_SIZE = 1024 * 1024; // 1 MB
public static final boolean DEFAULT_AUTOSTART_PROCESSES = true;
public static final boolean DEFAULT_IS_MASTER_PEER = false;
public static final InetAddress DEFAULT_BOOTSTRAP_ADDRESS = null;
public static final String DEFAULT_ROOT_PATH = new File(System.getProperty("user.home"), "Hive2Hive")
.getAbsolutePath();
// standard port for the Hive2Hive network
public static final int H2H_PORT = 4622;
// the configuration file name (lying in the root directory of the node)
public static final String META_FILE_NAME = "h2h.conf";
// the trash directory, where deleted files are moved
public static final File TRASH_DIRECTORY = new File(FileUtils.getTempDirectory(), "H2HTrash");
// configurations for network messages
public static final int MAX_MESSAGE_SENDING = 5;
public static final int MAX_MESSAGE_SENDING_DIRECT = 3;
// enable/disable the put verification on the remote peer
public static final boolean REMOTE_VERIFICATION_ENABLED = true;
// maximal numbers of versions kept in the DHT (see versionKey)
public static final int MAX_VERSIONS_HISTORY = 5;
public static final long MIN_VERSION_AGE_BEFORE_REMOVAL_MS = 5 * 60 * 1000; // 5 mins
// DHT content keys - these are used to distinguish the different data types
// stored for a given key
public static final String USER_PROFILE = "USER_PROFILE";
public static final String USER_LOCATIONS = "USER_LOCATIONS";
public static final String USER_PUBLIC_KEY = "USER_PUBLIC_KEY";
public static final String USER_MESSAGE_QUEUE_KEY = "USER_MESSAGE_QUEUE_KEY";
public static final String FILE_CHUNK = "FILE_CHUNK";
public static final String META_DOCUMENT = "META_DOCUMENT";
// waiting time (in ms) after a put operation to verify if put succeeded
public static final long PUT_VERIFICATION_WAITING_TIME_MS = 2000;
public static final int PUT_RETRIES = 3; // number of allowed tries to retry a put
public static final int REMOVE_RETRIES = 3; // number of allowed tries to retry a remove
public static final int GET_RETRIES = 3; // number of allowed tries to retry a get
// maximum delay to wait until peers have time to answer until they get removed from the locations
public static final long CONTACT_PEERS_AWAIT_MS = 10000;
public static final String USER_PROFILE_TASK_DOMAIN = "USER-PROFILE-TASK";
// default key used in the TomP2P framework
public static final Number160 TOMP2P_DEFAULT_KEY = Number160.ZERO;
// number of threads that netty / tomp2p are allowed to have. Too few threads can lead to slow response
// times, too many threads can exceed the available memory
public static final int NUM_OF_NETWORK_THREADS = 32;
/**
* Encryption Key Management
*/
// key length for asymmetric user key pair
public static final RSA_KEYLENGTH KEYLENGTH_USER_KEYS = RSA_KEYLENGTH.BIT_2048;
// key length for asymmetric meta document encryption
public static final RSA_KEYLENGTH KEYLENGTH_META_DOCUMENT = RSA_KEYLENGTH.BIT_2048;
// key length for asymmetric chunk encryption
public static final RSA_KEYLENGTH KEYLENGTH_CHUNK = RSA_KEYLENGTH.BIT_2048;
// key length for symmetric user profile encryption
public static final AES_KEYLENGTH KEYLENGTH_USER_PROFILE = AES_KEYLENGTH.BIT_256;
// key length for symmetric part of hybrid encryption
public static final AES_KEYLENGTH KEYLENGTH_HYBRID_AES = AES_KEYLENGTH.BIT_256;
}
|
package org.jenetics.util;
import static org.jenetics.util.arrays.isSorted;
import static org.jenetics.util.factories.Int;
import static org.jenetics.util.functions.Null;
import static org.jenetics.util.functions.ObjectToString;
import static org.jenetics.util.functions.not;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ArrayTest extends ObjectTester<Array<Double>> {
static Factory<Double> RANDOM = new Factory<Double>() {
private final Random random = new Random();
@Override
public Double newInstance() {
return random.nextDouble();
}
};
final Factory<Array<Double>> _factory = new Factory<Array<Double>>() {
@Override
public Array<Double> newInstance() {
final Random random = RandomRegistry.getRandom();
final Array<Double> array = new Array<>(random.nextInt(1000) + 100);
for (int i = 0; i < array.length(); ++i) {
array.set(i, random.nextDouble());
}
return array;
}
};
@Override
protected Factory<Array<Double>> getFactory() {
return _factory;
}
@Test
public void newFromCollection() {
final Array<Integer> a1 = Array.valueOf(1, 2, 3, 4, 5);
final Array<Integer> a2 = Array.valueOf(6, 7, 8, 9, 10, 11, 12, 13);
final Array<Integer> a3 = a1.add(a2);
Assert.assertEquals(a3.length(), a1.length() + a2.length());
for (int i = 0; i < a1.length() + a2.length(); ++i) {
Assert.assertEquals(a3.get(i), new Integer(i + 1));
}
}
@Test
public void newFromSubArray() {
final Array<Integer> a1 = Array.valueOf(0, 1, 2, 3, 4, 5, 6, 7);
final Array<Integer> a2 = Array.valueOf(6, 7, 8, 9, 10, 11, 12, 13);
final Array<Integer> a3 = a1.subSeq(0, 6).add(a2);
Assert.assertEquals(a3.length(), a1.length() + a2.length() - 2);
for (int i = 0; i < a1.length() + a2.length() - 2; ++i) {
Assert.assertEquals(a3.get(i), new Integer(i));
}
}
@Test
public void newFromOtherSubArray() {
final Array<Integer> a1 = Array.valueOf(0, 1, 2, 3, 4, 5, 6, 7);
final Array<Integer> a2 = Array.valueOf(6, 7, 8, 9, 10, 11, 12, 13);
final Array<Integer> a3 = a1.subSeq(1, 6).add(a2);
Assert.assertEquals(a3.length(), a1.length() + a2.length() - 3);
for (int i = 1; i < a1.length() + a2.length() - 2; ++i) {
Assert.assertEquals(a3.get(i - 1), new Integer(i));
}
}
@Test
public void create4() {
final Array<Integer> a1 = Array.valueOf(0, 1, 2, 3, 4, 5, 6, 7);
final Array<Integer> a2 = Array.valueOf(6, 7, 8, 9, 10, 11, 12, 13);
final Array<Integer> a3 = a1.add(a2.subSeq(2, 7));
Assert.assertEquals(a3.length(), a1.length() + a2.length() - 3);
for (int i = 0; i < a1.length() + a2.length() - 3; ++i) {
Assert.assertEquals(a3.get(i), new Integer(i));
}
}
@Test
public void filter() {
final Array<Integer> array = new Array<>(20);
array.setAll(100);
array.set(18, null);
array.set(19, null);
final Array<Integer> filtered = array.filter(not(Null));
Assert.assertEquals(filtered.length(), array.length() - 2);
}
@Test
public void boxBoolean() {
final Random random = RandomRegistry.getRandom();
final boolean[] array = new boolean[1000];
for (int i = 0; i < array.length; ++i) {
array[i] = random.nextBoolean();
}
final Array<Boolean> boxed = Array.box(array);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(boxed.get(i).booleanValue(), array[i]);
}
}
@Test
public void boxChar() {
final Random random = RandomRegistry.getRandom();
final char[] array = new char[1000];
for (int i = 0; i < array.length; ++i) {
array[i] = (char)random.nextInt();
}
final Array<Character> boxed = Array.box(array);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(boxed.get(i).charValue(), array[i]);
}
}
@Test
public void boxInt() {
final Random random = RandomRegistry.getRandom();
final int[] array = new int[1000];
for (int i = 0; i < array.length; ++i) {
array[i] = random.nextInt();
}
final Array<Integer> boxed = Array.box(array);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(boxed.get(i).intValue(), array[i]);
}
}
@Test
public void boxLong() {
final Random random = RandomRegistry.getRandom();
final long[] array = new long[1000];
for (int i = 0; i < array.length; ++i) {
array[i] = random.nextLong();
}
final Array<Long> boxed = Array.box(array);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(boxed.get(i).longValue(), array[i]);
}
}
@Test
public void boxFloat() {
final Random random = RandomRegistry.getRandom();
final float[] array = new float[1000];
for (int i = 0; i < array.length; ++i) {
array[i] = random.nextFloat();
}
final Array<Float> boxed = Array.box(array);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(boxed.get(i).floatValue(), array[i]);
}
}
@Test
public void boxDouble() {
final Random random = RandomRegistry.getRandom();
final double[] array = new double[1000];
for (int i = 0; i < array.length; ++i) {
array[i] = random.nextDouble();
}
final Array<Double> boxed = Array.box(array);
for (int i = 0; i < array.length; ++i) {
Assert.assertEquals(boxed.get(i).doubleValue(), array[i]);
}
}
@Test
public void unboxBoolean() {
final Random random = RandomRegistry.getRandom();
final Array<Boolean> array = new Array<>(1000);
for (int i = 0; i < array.length(); ++i) {
array.set(i, random.nextBoolean());
}
final boolean[] unboxed = Array.unboxBoolean(array);
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(unboxed[i], array.get(i).booleanValue());
}
}
@Test
public void unboxCharacter() {
final Random random = RandomRegistry.getRandom();
final Array<Character> array = new Array<>(1000);
for (int i = 0; i < array.length(); ++i) {
array.set(i, (char)random.nextInt());
}
final char[] unboxed = Array.unboxChar(array);
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(unboxed[i], array.get(i).charValue());
}
}
@Test
public void unboxInteger() {
final Random random = RandomRegistry.getRandom();
final Array<Integer> array = new Array<>(1000);
for (int i = 0; i < array.length(); ++i) {
array.set(i, random.nextInt());
}
final int[] unboxed = Array.unboxInt(array);
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(unboxed[i], array.get(i).intValue());
}
}
@Test
public void unboxLong() {
final Random random = RandomRegistry.getRandom();
final Array<Long> array = new Array<>(1000);
for (int i = 0; i < array.length(); ++i) {
array.set(i, random.nextLong());
}
final long[] unboxed = Array.unboxLong(array);
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(unboxed[i], array.get(i).longValue());
}
}
@Test
public void unboxFloat() {
final Random random = RandomRegistry.getRandom();
final Array<Float> array = new Array<>(1000);
for (int i = 0; i < array.length(); ++i) {
array.set(i, random.nextFloat());
}
final float[] unboxed = Array.unboxFloat(array);
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(unboxed[i], array.get(i).floatValue());
}
}
@Test
public void unboxDouble() {
final Random random = RandomRegistry.getRandom();
final Array<Double> array = new Array<>(1000);
for (int i = 0; i < array.length(); ++i) {
array.set(i, random.nextDouble());
}
final double[] unboxed = Array.unboxDouble(array);
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(unboxed[i], array.get(i).doubleValue());
}
}
@Test
public void sort() {
final Array<Integer> integers = new Array<Integer>(10000).fill(Int());
Assert.assertTrue(arrays.isSorted(integers));
integers.sort();
Assert.assertTrue(arrays.isSorted(integers));
arrays.shuffle(integers, new Random());
integers.sort();
Assert.assertTrue(arrays.isSorted(integers));
}
@Test
public void sort2() {
final Random random = new Random();
final Factory<Integer> factory = new Factory<Integer>() {
@Override public Integer newInstance() {
return random.nextInt(10000);
}
};
final Array<Integer> array = new Array<>(100);
array.fill(factory);
Assert.assertFalse(isSorted(array));
final Array<Integer> clonedArray = array.copy();
Assert.assertEquals(array, clonedArray);
clonedArray.sort(30, 40);
array.subSeq(30, 40).sort();
Assert.assertEquals(array, clonedArray);
}
@Test
public void map() {
final Array<Integer> integers = new Array<Integer>(20).fill(Int());
final Array<String> strings = integers.map(ObjectToString);
Assert.assertEquals(strings.length(), integers.length());
for (int i = 0; i < strings.length(); ++i) {
Assert.assertEquals(strings.get(i), Integer.toString(i));
}
}
@Test
public void reverse() {
final Array<Integer> integers = new Array<Integer>(1000).fill(Int(999, -1));
Assert.assertFalse(arrays.isSorted(integers));
integers.reverse();
Assert.assertTrue(arrays.isSorted(integers));
}
@Test
public void swap() {
final Array<Integer> array = new Array<Integer>(10).fill(Int());
for (int i = 0; i < array.length(); ++i) {
for (int j = i; j < array.length(); ++j) {
final Array<Integer> copy = array.copy();
copy.swap(i, j);
Assert.assertEquals(copy.get(j), array.get(i));
}
}
array.swap(4, 4);
}
@Test(expectedExceptions = ArrayIndexOutOfBoundsException.class)
public void swap3() {
final Array<Integer> array = new Array<Integer>(10).fill(Int());
array.swap(5, 10);
}
@Test(expectedExceptions = ArrayIndexOutOfBoundsException.class)
public void swap4() {
final Array<Integer> array = new Array<Integer>(10).fill(Int());
array.swap(-1, 8);
}
@Test
public void swap5() {
final Array<Integer> a1 = new Array<Integer>(50).fill(Int());
final Array<Integer> a2 = new Array<Integer>(33).fill(Int());
for (int i = 0; i < a1.length(); ++i) {
for (int j = i; j < a1.length(); ++j) {
for (int k = 0; k < a2.length() - (j - i); ++k) {
final Array<Integer> ca1 = a1.copy();
final Array<Integer> ca2 = a2.copy();
ca1.swap(i, j, ca2, k);
Assert.assertEquals(ca1.subSeq(i, j), a2.subSeq(k, k + (j - i)));
Assert.assertEquals(ca2.subSeq(k, k + (j - i)), a1.subSeq(i, j));
}
}
}
}
@Test
public void asList() {
final Array<Integer> integers = new Array<Integer>(1000).fill(Int());
Assert.assertTrue(arrays.isSorted(integers));
arrays.shuffle(integers, new Random());
Assert.assertFalse(arrays.isSorted(integers));
Collections.sort(integers.asList());
Assert.assertTrue(arrays.isSorted(integers));
}
@Test
public void fillConstant() {
final ISeq<Integer> array = new Array<Integer>(10).setAll(10).toISeq();
Assert.assertEquals(array.length(), 10);
for (Integer i : array) {
Assert.assertEquals(i, new Integer(10));
}
}
@Test
public void fillFactory() {
final Array<Integer> array = new Array<Integer>(10).setAll(0);
Assert.assertEquals(array.length(), 10);
array.fill(Int());
for (int i = 0; i < array.length(); ++i) {
Assert.assertEquals(array.get(i), new Integer(i));
}
}
static interface ArrayAlterer {
void alter(final MSeq<Double> seq);
}
@Test
void immutableFill() {
immutable(new ArrayAlterer() {
@Override public void alter(final MSeq<Double> seq) {
seq.fill(RANDOM);
}
});
}
@Test
void immutableSet() {
immutable(new ArrayAlterer() {
@Override public void alter(final MSeq<Double> seq) {
for (int i = 0; i < seq.length(); ++i) {
seq.set(i, Math.random());
}
}
});
}
private void immutable(final ArrayAlterer alterer) {
Array<Double> array = getFactory().newInstance();
Array<Double> copy = array.copy();
Assert.assertEquals(copy, array);
int i = 0;
int j = array.length();
while (i < j) {
final Array<Double> sub = array.subSeq(i, j);
assertEquals(sub, 0, array, i, j - i);
final ISeq<Double> iseq = sub.toISeq();
final MSeq<Double> cseq = iseq.copy();
assertEquals(iseq, 0, cseq, 0, iseq.length());
alterer.alter(sub);
Assert.assertEquals(sub, array.subSeq(i, j));
Assert.assertEquals(iseq, cseq);
++i; --j;
array = copy.copy();
}
}
static <T> void assertEquals(
final Seq<T> actual, final int srcPos,
final Seq<T> expected, final int desPos, final int length
) {
for (int i = 0; i < length; ++i) {
Assert.assertEquals(actual.get(srcPos + i), expected.get(desPos + i));
}
}
@Test
public void foreach() {
final Array<Integer> array = new Array<Integer>(10).setAll(123);
array.toISeq();
final AtomicInteger count = new AtomicInteger(0);
boolean value = array.forall(new Function<Integer, Boolean>() {
@Override public Boolean apply(Integer object) {
Assert.assertEquals(object, new Integer(123));
count.addAndGet(1);
return Boolean.TRUE;
}
});
Assert.assertEquals(value, true);
Assert.assertEquals(count.get(), 10);
count.set(0);
int result = array.indexWhere(new Function<Integer, Boolean>() {
@Override public Boolean apply(Integer object) {
Assert.assertEquals(object, new Integer(123));
return count.addAndGet(1) == 5;
}
});
Assert.assertEquals(count.get(), 5);
Assert.assertEquals(result, 4);
}
@Test
public void append1() {
final Array<Integer> a1 = Array.valueOf(0, 1, 2, 3, 4, 5);
final Array<Integer> a2 = Array.valueOf(6, 7, 8, 9, 10);
final Array<Integer> a3 = a1.add(a2);
Assert.assertEquals(a3.length(), 11);
Assert.assertEquals(a3,
Array.valueOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
);
}
@Test
public void append2() {
final Array<Integer> a1 = Array.valueOf(0, 1, 2, 3, 4, 5);
final Array<Integer> a3 = a1.add(Arrays.asList(6, 7, 8, 9, 10));
Assert.assertEquals(a3.length(), 11);
Assert.assertEquals(a3,
Array.valueOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
);
}
@Test
public void append3() {
final Array<Integer> a1 = Array.valueOf(0, 1, 2, 3, 4, 5);
final Array<Integer> a2 = a1.add(6);
final Array<Integer> a3 = a1.add(6);
Assert.assertEquals(a2.length(), a1.length() + 1);
Assert.assertEquals(a3.length(), a1.length() + 1);
Assert.assertNotSame(a2, a3);
Assert.assertEquals(a2, a3);
}
@Test
public void indexOf() {
final Array<Integer> array = new Array<>(20);
for (int i = 0; i < 10; ++i) {
array.set(i, i);
}
for (int i = 10; i < 20; ++i) {
array.set(i, i - 10);
}
int index = array.indexOf(5);
Assert.assertEquals(index, 5);
index = array.lastIndexOf(5);
Assert.assertEquals(index, 15);
index = array.lastIndexOf(25);
Assert.assertEquals(index, -1);
index = array.indexOf(-1);
Assert.assertEquals(index, -1);
index = array.indexOf(Integer.MIN_VALUE);
Assert.assertEquals(index, -1);
index = array.indexOf(Integer.MAX_VALUE);
Assert.assertEquals(index, -1);
}
@Test
public void copy() {
final Array<Integer> array = new Array<>(10);
for (int i = 0; i < array.length(); ++i) {
array.set(i, i);
}
final Array<Integer> copy = array.subSeq(3, 8).copy();
Assert.assertEquals(copy.length(), 5);
for (int i = 0; i < 5; ++i) {
Assert.assertEquals(copy.get(i), new Integer(i + 3));
}
}
@Test
public void subArray() {
final Array<Integer> array = new Array<>(10);
for (int i = 0; i < array.length(); ++i) {
array.set(i, i);
}
final Array<Integer> sub = array.subSeq(3, 8);
Assert.assertEquals(sub.length(), 5);
for (int i = 0; i < 5; ++i) {
Assert.assertEquals(sub.get(i), new Integer(i + 3));
sub.set(i, i + 100);
}
for (int i = 3; i < 8; ++i) {
Assert.assertEquals(array.get(i), new Integer(i + 97));
}
final Array<Integer> copy = sub.copy();
Assert.assertEquals(copy.length(), 5);
for (int i = 0; i < 5; ++i) {
Assert.assertEquals(sub.get(i), new Integer(i + 100));
}
int count = 0;
for (Integer i : sub) {
Assert.assertEquals(i, new Integer(count + 100));
++count;
}
Assert.assertEquals(count, 5);
}
@Test
public void iterator() {
final List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
final Array<Integer> array = Array.valueOf(list);
final Iterator<Integer> ai = array.iterator();
for (Integer i : list) {
Assert.assertEquals(i, ai.next());
}
Assert.assertFalse(ai.hasNext());
}
@Test
public void toObjectArray() {
final Array<Integer> array = new Array<>(10);
for (int i = 0; i < array.length(); ++i) {
array.set(i, i);
}
Object[] oa = array.toArray();
Assert.assertEquals(oa.length, array.length());
Assert.assertEquals(oa.getClass(), Object[].class);
for (int i = 0; i < oa.length; ++i) {
Assert.assertEquals(oa[i], array.get(i));
}
}
@Test
public void toTypedArray() {
final Array<Integer> array = new Array<>(10);
for (int i = 0; i < array.length(); ++i) {
array.set(i, i);
}
Integer[] oa = array.toArray(new Integer[0]);
Assert.assertEquals(oa.length, array.length());
Assert.assertEquals(oa.getClass(), Integer[].class);
for (int i = 0; i < oa.length; ++i) {
Assert.assertEquals(oa[i], array.get(i));
}
Assert.assertEquals(Array.valueOf(oa), array);
}
}
|
package org.pentaho.di.core.parameters;
/**
* Interface to implement named parameters.
*
* @author Sven Boden
*/
public interface NamedParams
{
/**
* Add a parameter definition to this set.
*
* TODO: default, throw exception
*
* @param key Name of the parameter.
* @param defValue default value.
* @param description Description of the parameter.
*/
void addParameterDefinition(String key, String defValue, String description);
/**
* Set the value of a parameter.
*
* @param key key to set value of
* @param value value to set it to.
*/
void setParameterValue(String key, String value);
/**
* Get the value of a parameter.
*
* @param key Key to get value for.
*
* @return null when not defined.
*/
String getParameterValue(String key);
/**
* Get the description of a parameter.
*
* @param key Key to get value for.
*
* @return null when not defined.
*/
String getParameterDescription(String key);
/**
* Get the default value of a parameter.
*
* @param key Key to get value for.
*
* @return null when not defined.
*/
String getParameterDefault(String key);
/**
* List the parameters.
*
* @return Array of parameters.
*/
String[] listParameters();
/**
* Clear the values.
*/
void eraseParameters();
/**
* Copy params to these named parameters (clearing out first).
*
* @param params the parameters to copy from.
*/
void copyParametersFrom(NamedParams params);
/**
* Activate the currently set parameters
*/
void activateParameters();
/**
* Clear all parameters
*/
public void clearParameters();
}
|
// $RCSfile: FixWrapper.java,v $
// @version $Revision: 1.14 $
// $Log: FixWrapper.java,v $
// Revision 1.14 2007/03/12 11:40:24 ian.mayo
// Change default font size to 9px
// Revision 1.13 2007/01/22 09:52:51 ian.mayo
// Better maths
// Revision 1.12 2006/11/28 10:55:12 Ian.Mayo
// Add offset to label to allow for fix symbol
// Revision 1.11 2006/01/18 15:02:54 Ian.Mayo
// Improve how we do interpolated points
// Revision 1.10 2005/12/12 12:40:14 Ian.Mayo
// Don't do the hard-work ourselves
// Revision 1.9 2005/12/02 10:56:31 Ian.Mayo
// Correct use of N/A in date formats
// Revision 1.8 2005/09/23 14:56:05 Ian.Mayo
// Support generation of interpolated fixes
// Revision 1.7 2005/01/28 09:32:11 Ian.Mayo
// Categorise editable properties
// Revision 1.5 2005/01/19 14:31:13 Ian.Mayo
// Make the top-level Visible property available to property editor
// Revision 1.4 2004/12/02 11:37:49 Ian.Mayo
// Optimise fix comparison
// Revision 1.3 2004/11/29 15:44:46 Ian.Mayo
// Only reset name when we have valid time
// Revision 1.2 2004/11/25 10:24:45 Ian.Mayo
// Switch to Hi Res dates
// Revision 1.1.1.2 2003/07/21 14:49:21 Ian.Mayo
// Re-import Java files to keep correct line spacing
// Revision 1.16 2003-07-04 10:59:19+01 ian_mayo
// reflect name change in parent testing class
// Revision 1.15 2003-07-01 14:56:16+01 ian_mayo
// Refactor out painting the labels
// Revision 1.14 2003-06-25 15:39:56+01 ian_mayo
// Improve formatting of multi-line tooltip
// Revision 1.13 2003-06-25 08:42:21+01 ian_mayo
// Switch to multi-line labels
// Revision 1.12 2003-06-10 15:39:21+01 ian_mayo
// Re-instate getFixLocation, since we use it for property editor
// Revision 1.11 2003-06-10 14:34:17+01 ian_mayo
// Remove confusing method (we should access the fix location via the fix)
// Revision 1.10 2003-05-09 12:27:14+01 ian_mayo
// Handle instance where parent track isn't set (we only want the name anyway)
// Revision 1.9 2003-04-01 15:50:20+01 ian_mayo
// Correctly manage the label format - so it doesn't look like a change has been made each time the user saves his properties
// Revision 1.8 2003-03-24 11:05:27+00 ian_mayo
// Make correct parameter public again
// Revision 1.7 2003-03-19 15:36:50+00 ian_mayo
// improvements according to IntelliJ inspector
// Revision 1.6 2003-03-14 16:02:36+00 ian_mayo
// Use static instance of Font, to save object creation
// Revision 1.5 2002-11-01 14:44:44+00 ian_mayo
// Minor tidying, shorten displayed name of fix
// Revision 1.4 2002-10-30 16:27:57+00 ian_mayo
// correct visibility of getDisplayName implementation
// Revision 1.3 2002-10-01 15:41:45+01 ian_mayo
// make final methods & classes final (following IDEA analysis)
// Revision 1.2 2002-05-28 09:25:13+01 ian_mayo
// after switch to new system
// Revision 1.1 2002-05-28 09:11:40+01 ian_mayo
// Initial revision
// Revision 1.1 2002-04-23 12:28:22+01 ian_mayo
// Initial revision
// Revision 1.8 2001-09-14 09:43:09+01 administrator
// Remember to set the time zone
// Revision 1.7 2001-08-29 19:19:17+01 administrator
// Reflect package change of PlainWrapper, and remove Contacts
// Revision 1.6 2001-08-21 12:14:39+01 administrator
// Improve editing of label format
// Revision 1.5 2001-08-20 10:29:00+01 administrator
// For editting format of date text, return "N/A", not null
// Revision 1.4 2001-08-14 14:08:01+01 administrator
// Correct the "Compare" method to put us AFTER any others, not before
// Revision 1.3 2001-08-13 12:53:55+01 administrator
// use the PlainWrapper colour support, and implement Comparable support
// Revision 1.2 2001-08-01 20:08:37+01 administrator
// Added methods & editor class necessary to all user to specify date formatting to be used for text label
// Revision 1.1 2001-07-23 11:53:54+01 administrator
// tidy up
// Revision 1.0 2001-07-17 08:41:08+01 administrator
// Initial revision
// Revision 1.3 2001-01-22 12:30:02+00 novatech
// added JUnit testing code
// Revision 1.2 2001-01-09 10:25:57+00 novatech
// allow setting of symbol size
// Revision 1.1 2001-01-03 13:40:22+00 novatech
// Initial revision
// Revision 1.1.1.1 2000/12/12 20:49:14 ianmayo
// initial import of files
// Revision 1.27 2000-11-22 10:51:56+00 ian_mayo
// provide better colour accessors, so that a null value is return if this fix doesn't have a colour set - not the track colour
// Revision 1.26 2000-11-17 09:11:42+00 ian_mayo
// tidily handle missing location for Tactical fix
// Revision 1.25 2000-10-03 14:15:50+01 ian_mayo
// white space
// Revision 1.24 2000-09-21 09:05:24+01 ian_mayo
// make Editable.EditorType a transient parameter, to save it being written to file
// Revision 1.23 2000-08-18 10:09:00+01 ian_mayo
// Before we make all editables listenable - that is the property editor is listening out for changes to it's editable and updates it accordingly
// Revision 1.22 2000-08-16 14:12:05+01 ian_mayo
// take track name from TrackWrapper outside BeanInfo
// Revision 1.21 2000-08-15 15:28:46+01 ian_mayo
// Bean parameter change
// Revision 1.20 2000-08-14 11:00:28+01 ian_mayo
// switch getSpeed to correct units
// Revision 1.19 2000-08-11 08:40:51+01 ian_mayo
// tidy beaninfo
// Revision 1.18 2000-08-09 16:04:02+01 ian_mayo
// remove stray semi-colons
// Revision 1.17 2000-05-23 13:42:01+01 ian_mayo
// fill in the square symbol when the label is visible
// Revision 1.16 2000-04-03 10:41:02+01 ian_mayo
// handle Label visibility at this level, not in the parent
// Revision 1.15 2000-03-27 14:41:12+01 ian_mayo
// remove showLabel dependency on parent
// Revision 1.14 2000-03-08 16:24:45+00 ian_mayo
// add myArea initialisation to getBounds method (used following deserialisation)
// Revision 1.13 2000-03-07 14:48:18+00 ian_mayo
// optimised algorithms
// Revision 1.12 2000-03-07 10:07:59+00 ian_mayo
// Optimisation, keep local copy of area covered by fix
// Revision 1.11 2000-02-22 13:48:32+00 ian_mayo
// exportShape name changed to exportThis
// Revision 1.10 2000-02-18 11:06:21+00 ian_mayo
// added Label/Symbol visiblility getter/setter methods
// Revision 1.9 2000-02-14 16:48:16+00 ian_mayo
// Corrected label displayed in editor
// Revision 1.8 2000-02-04 15:51:42+00 ian_mayo
// Allowed user to modify position of fix
// Revision 1.7 2000-01-18 15:04:32+00 ian_mayo
// changed UI name from Fix to Location
// Revision 1.6 2000-01-13 15:32:05+00 ian_mayo
// moved paint control to Track
// Revision 1.5 2000-01-12 15:40:18+00 ian_mayo
// added concept of contacts
// Revision 1.4 1999-11-26 15:50:16+00 ian_mayo
// adding toString methods
// Revision 1.3 1999-11-12 14:35:40+00 ian_mayo
// part way through getting them to export themselves
// Revision 1.2 1999-11-11 18:24:03+00 ian_mayo
// changed name of Line object
// Revision 1.1 1999-10-12 15:33:40+01 ian_mayo
// Initial revision
// Revision 1.7 1999-08-04 14:04:36+01 administrator
// make show-label flag inherit from track
// Revision 1.6 1999-08-04 09:45:30+01 administrator
// minor mods, tidying up
// Revision 1.5 1999-07-27 09:24:19+01 administrator
// added BeanInfo editing
// Revision 1.4 1999-07-19 12:40:32+01 administrator
// added storage of sub-second time data (Switched to storing as Long rather than java.utils.Date)
// Revision 1.3 1999-07-16 10:01:47+01 administrator
// Nearing end of phase 2
// Revision 1.2 1999-07-12 08:09:20+01 administrator
// Property editing added
// Revision 1.1 1999-07-07 11:10:13+01 administrator
// Initial revision
package Debrief.Wrappers;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.util.Vector;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Test;
import MWC.GUI.CanvasType;
import MWC.GUI.CreateEditorForParent;
import MWC.GUI.Defaults;
import MWC.GUI.Editable;
import MWC.GUI.FireReformatted;
import MWC.GUI.Griddable;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.TimeStampedDataItem;
import MWC.GUI.Properties.LocationPropertyEditor;
import MWC.GUI.Properties.MyDateFormatPropertyEditor;
import MWC.GUI.Properties.NullableLocationPropertyEditor;
import MWC.GUI.Shapes.Symbols.SymbolScalePropertyEditor;
import MWC.GUI.Tools.SubjectAction;
import MWC.GenericData.HiResDate;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldLocation;
import MWC.TacticalData.Fix;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
import MWC.Utilities.TextFormatting.GMTDateFormat;
import MWC.Utilities.TextFormatting.GeneralFormat;
/**
* The fix wrapper has the responsibility for the GUI and data aspects of the fix, tying the two
* together.
*/
public class FixWrapper extends PlainWrapper implements Watchable,
CanvasType.MultiLineTooltipProvider, TimeStampedDataItem,
CreateEditorForParent
{
// member variables
// bean info for this class
public final class fixInfo extends Griddable
{
public fixInfo(final FixWrapper data, final String theName,
final String trackName)
{
super(data, theName, trackName + ":" + theName);
}
@Override
public final BeanInfo[] getAdditionalBeanInfo()
{
// final BeanInfo[] res =
// {getTrackWrapper().getInfo()};
// return res;
// Hey: let's not return the parent track. The parent track is accessible via
// it's own menu entry
return null;
}
@Override
public final String getDisplayName()
{
return getTrackWrapper().getName() + ":" + super.getName();
}
@Override
public PropertyDescriptor[] getGriddablePropertyDescriptors()
{
try
{
if (_griddableDescriptors == null)
{
_griddableDescriptors =
new PropertyDescriptor[]
{
prop("Label", "the label for this data item"),
prop("Depth", "depth of this position"),
prop("Visible", "whether this position is visible"),
displayProp("FixLocation", "Fix location",
"the location for this position", OPTIONAL),
displayProp("CourseDegs", "Course(degs)",
"current course of this platform (degs)", SPATIAL),
prop("Speed", "current speed of this vehicle", SPATIAL)};
}
return _griddableDescriptors;
}
catch (final IntrospectionException e)
{
return super.getPropertyDescriptors();
}
}
@Override
public final MethodDescriptor[] getMethodDescriptors()
{
if (_methodDescriptors == null)
{
final Class<FixWrapper> c = FixWrapper.class;
_methodDescriptors =
new MethodDescriptor[]
{method(c, "resetColor", null, "Reset Color"),
method(c, "resetName", null, "Reset Label"),
method(c, "resetLabelLocation", null, "Reset label location"),
method(c, "exportThis", null, "Export Shape")};
}
return _methodDescriptors;
}
@Override
public NonBeanPropertyDescriptor[] getNonBeanGriddableDescriptors()
{
// don't worry - we provide the bean-based model
return null;
}
@Override
public final PropertyDescriptor[] getPropertyDescriptors()
{
PropertyDescriptor[] res;
try
{
if (_coreDescriptors == null)
{
_coreDescriptors =
new PropertyDescriptor[]
{
displayExpertLongProp("SymbolScale", "Symbol scale",
"the scale of the symbol", FORMAT,
SymbolScalePropertyEditor.class),
displayProp("SymbolShowing", "Symbol showing",
"whether the symbol is showing", VISIBILITY),
displayProp("ArrowShowing", "Arrow showing",
"whether the arrow is showing", VISIBILITY),
displayProp("LineShowing", "Line showing",
"whether the to join this position it's predecessor",
VISIBILITY),
displayProp("DateTimeGroup", "DateTime group",
"the DTG for the fix"),
prop("Color", "the position color", FORMAT),
prop("Label", "the position label", FORMAT),
prop("Font", "the label font", FORMAT),
displayProp("FixLocation", "Fix location",
"the location of the fix", SPATIAL),
prop("Visible", "whether the whole fix is visible",
VISIBILITY),
displayProp("Comment", "Comment", "Comment for this entry",
OPTIONAL),
displayProp("LabelShowing", "Label showing",
"whether the label is showing", VISIBILITY),
displayLongProp("LabelFormat", "Label format",
"the time format of the label, or N/A to leave as-is",
MyDateFormatPropertyEditor.class, FORMAT),
displayLongProp("LabelLocation", "Label location",
"the label location", LocationPropertyEditor.class,
FORMAT)};
}
// do we have a comment?
final FixWrapper fix = (FixWrapper) this.getData();
if (fix.getComment() != null)
{
// yes = better create height/width editors
final PropertyDescriptor[] coreDescriptorsWithComment =
new PropertyDescriptor[_coreDescriptors.length + 1];
System.arraycopy(_coreDescriptors, 0, coreDescriptorsWithComment, 1,
_coreDescriptors.length);
coreDescriptorsWithComment[0] =
displayProp("CommentShowing", "Comment showing",
"whether the comment is showing", VISIBILITY);
res = coreDescriptorsWithComment;
}
else
{
res = _coreDescriptors;
}
}
catch (final IntrospectionException e)
{
_coreDescriptors = super.getPropertyDescriptors();
res = _coreDescriptors;
}
return res;
}
@Override
public final SubjectAction[] getUndoableActions()
{
// NOTE: we aren't cacheing these, since they're unique
// to each instance.
final FixWrapper fw = (FixWrapper) getData();
final String lbl = fw.getLabel();
final SubjectAction[] res =
new SubjectAction[]
{new SplitTrack(true, "Split track before " + lbl),
new SplitTrack(false, "Split track after " + lbl)};
return res;
}
}
// and a class representing interpolated fixes
public static class InterpolatedFixWrapper extends FixWrapper implements
PlainWrapper.InterpolatedData
{
private static final long serialVersionUID = 1L;
/**
* constructor - just pass the child fix back to the parent
*
* @param fixData
*/
public InterpolatedFixWrapper(final Fix fixData)
{
super(fixData);
}
}
private static class SplitTrack implements SubjectAction
{
private final boolean _splitBefore;
private final String _title;
private Vector<TrackSegment> _splitSections;
/**
* create an instance of this operation
*
* @param keepPort
* whether to keep the port removal
* @param title
* what to call ourselves
*/
public SplitTrack(final boolean splitBefore, final String title)
{
_splitBefore = splitBefore;
_title = title;
}
@Override
public void execute(final Editable subject)
{
final FixWrapper fix = (FixWrapper) subject;
final WatchableList parent = fix.getTrackWrapper();
if(parent instanceof TrackWrapper)
{
TrackWrapper track = (TrackWrapper) parent;
_splitSections = track.splitTrack(fix, _splitBefore);
}
}
@Override
public boolean isRedoable()
{
return true;
}
@Override
public boolean isUndoable()
{
return true;
}
@Override
public String toString()
{
return _title;
}
@Override
public void undo(final Editable subject)
{
final FixWrapper fix = (FixWrapper) subject;
final WatchableList parent = fix.getTrackWrapper();
if(parent instanceof TrackWrapper)
{
TrackWrapper track = (TrackWrapper) parent;
track.combineSections(_splitSections);
}
}
}
// testing for this class
static public final class testMe extends junit.framework.TestCase
{
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public testMe(final String val)
{
super(val);
}
/**
* Test method for {@link Debrief.Wrappers.TrackWrapper#add(MWC.GUI.Editable)} .
*/
public void testInterpolate()
{
FixWrapper fw1 = TrackWrapper_Test.createFix(100, 1, 1, 2, 3);
FixWrapper fw2 = TrackWrapper_Test.createFix(200, 2, 1, 2, 3);
FixWrapper fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(150));
assertEquals("right time", 150, fw3.getTime().getDate().getTime());
assertEquals("right lat", 1.5, fw3.getLocation().getLat(), 0.001);
assertEquals("right lat", 1, fw3.getLocation().getLong(), 0.0001);
fw1 = TrackWrapper_Test.createFix(100, 1, 1, 2, 1);
fw2 = TrackWrapper_Test.createFix(200, 2, 2, 10, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(150));
assertEquals("right time", 150, fw3.getTime().getDate().getTime());
assertEquals("right course", MWC.Algorithms.Conversions.Degs2Rads(6), fw3
.getCourse(), 0.001);
assertEquals("right speed", 2, fw3.getSpeed(), 0.0001);
fw1 = TrackWrapper_Test.createFix(100, 1, 1, 20, 30);
fw2 = TrackWrapper_Test.createFix(200, 2, 2, 10, 10);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(125));
assertEquals("right time", 125, fw3.getTime().getDate().getTime());
assertEquals("right course", MWC.Algorithms.Conversions.Degs2Rads(17.5),
fw3.getCourse(), 0.001);
assertEquals("right speed", 25, fw3.getSpeed(), 0.0001);
fw1 = TrackWrapper_Test.createFix(100, 1, 1, 2, 3);
fw2 = TrackWrapper_Test.createFix(200, 2, 1, 2, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(140));
assertEquals("right time", 140, fw3.getTime().getDate().getTime());
assertEquals("right lat", 1.4, fw3.getLocation().getLat(), 0.001);
assertEquals("right lat", 1, fw3.getLocation().getLong(), 0.0001);
fw1 = TrackWrapper_Test.createFix(100, 1, 21, 2, 3);
fw2 = TrackWrapper_Test.createFix(200, 2, 21, 2, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(140));
assertEquals("right time", 140, fw3.getTime().getDate().getTime());
assertEquals("right lat", 1.4, fw3.getLocation().getLat(), 0.001);
assertEquals("right lat", 21, fw3.getLocation().getLong(), 0.0001);
fw1 = TrackWrapper_Test.createFix(100, 41, 21, 2, 3);
fw2 = TrackWrapper_Test.createFix(200, 42, 21, 2, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(140));
assertEquals("right time", 140, fw3.getTime().getDate().getTime());
assertEquals("right lat", 41.4, fw3.getLocation().getLat(), 0.001);
assertEquals("right lat", 21, fw3.getLocation().getLong(), 0.0001);
fw1 = TrackWrapper_Test.createFix(100, 60, 30, 0, 31, 0, 0, 2, 3);
fw2 = TrackWrapper_Test.createFix(200, 60, 15, 0, 31, 30, 0, 2, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(150));
// System.out.println(fw1.getLocation() + ": " + fw1.getLocation().getLat()
// + ", " + fw1.getLocation().getLong());
// System.out.println(fw2.getLocation() + ": " + fw2.getLocation().getLat()
// + ", " + fw2.getLocation().getLong());
// System.out.println(fw3.getLocation() + ": " + fw3.getLocation().getLat()
// + ", " + fw3.getLocation().getLong());
assertEquals("right time", 150, fw3.getTime().getDate().getTime());
assertEquals("right long", 31.25, fw3.getLocation().getLong(), 0.0001);
assertEquals("right lat", 60.375, fw3.getLocation().getLat(), 0.001);
// handle the course passing through zero
fw1 = TrackWrapper_Test.createFix(100, 1, 1, 0, 1);
fw2 = TrackWrapper_Test.createFix(200, 2, 2, 10, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(150));
assertEquals("right time", 150, fw3.getTime().getDate().getTime());
assertEquals("right course", MWC.Algorithms.Conversions.Degs2Rads(5), fw3
.getCourse(), 0.001);
// handle the course passing through zero
fw1 = TrackWrapper_Test.createFix(100, 1, 1, 355, 1);
fw2 = TrackWrapper_Test.createFix(200, 2, 2, 15, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(150));
assertEquals("right time", 150, fw3.getTime().getDate().getTime());
assertEquals("right course", 5, Math.toDegrees(fw3.getCourse()), 0.001);
fw1 = TrackWrapper_Test.createFix(100, 1, 1, 315, 1);
fw2 = TrackWrapper_Test.createFix(200, 2, 2, 15, 3);
fw3 = FixWrapper.interpolateFix(fw1, fw2, new HiResDate(150));
assertEquals("right time", 150, fw3.getTime().getDate().getTime());
assertEquals("right course", 345, Math.toDegrees(fw3.getCourse()), 0.001);
}
public final void testMyParams()
{
final Fix fx =
new Fix(new HiResDate(12, 0), new WorldLocation(2d, 2d, 2d), 2d, 2d);
final TrackWrapper tw = new TrackWrapper();
tw.setName("here ew arw");
FixWrapper ed = new FixWrapper(fx);
ed.setTrackWrapper(tw);
editableTesterSupport.testParams(ed, this);
ed = null;
}
public final void testOrientation()
{
assertEquals("correct orient", LocationPropertyEditor.LEFT,
orientationFor(Math.toRadians(0)));
assertEquals("correct orient", LocationPropertyEditor.LEFT,
orientationFor(Math.toRadians(20)));
assertEquals("correct orient", LocationPropertyEditor.LEFT,
orientationFor(Math.toRadians(60)));
assertEquals("correct orient", LocationPropertyEditor.TOP,
orientationFor(Math.toRadians(80)));
assertEquals("correct orient", LocationPropertyEditor.TOP,
orientationFor(Math.toRadians(115)));
assertEquals("correct orient", LocationPropertyEditor.RIGHT,
orientationFor(Math.toRadians(135)));
assertEquals("correct orient", LocationPropertyEditor.RIGHT,
orientationFor(Math.toRadians(160)));
assertEquals("correct orient", LocationPropertyEditor.RIGHT,
orientationFor(Math.toRadians(190)));
assertEquals("correct orient", LocationPropertyEditor.RIGHT,
orientationFor(Math.toRadians(220)));
assertEquals("correct orient", LocationPropertyEditor.BOTTOM,
orientationFor(Math.toRadians(260)));
assertEquals("correct orient", LocationPropertyEditor.BOTTOM,
orientationFor(Math.toRadians(290)));
assertEquals("correct orient", LocationPropertyEditor.LEFT,
orientationFor(Math.toRadians(320)));
assertEquals("correct orient", LocationPropertyEditor.LEFT,
orientationFor(Math.toRadians(360)));
assertEquals("correct orient", LocationPropertyEditor.LEFT,
orientationFor(Math.toRadians(380)));
assertEquals("correct orient", LocationPropertyEditor.RIGHT,
orientationFor(Math.toRadians(540)));
assertEquals("correct orient", LocationPropertyEditor.BOTTOM,
orientationFor(Math.toRadians(-90)));
}
public final void testResetColor()
{
final TrackWrapper track = new TrackWrapper();
track.setName("name");
track.setColor(Color.YELLOW);
final FixWrapper fw =
new FixWrapper(new Fix(new HiResDate(1000),
new WorldLocation(1, 1, 0), 12d, 13d));
fw.setColor(Color.GREEN);
assertEquals("Correct color", Color.GREEN, fw.getColor());
fw.resetColor();
assertEquals("Correct color (no track)", Color.GREEN, fw.getColor());
// ok, add the fix to the track
track.addFix(fw);
fw.resetColor();
assertEquals("Correct color (from track)", Color.YELLOW, fw.getColor());
assertEquals("Correct color", null, fw.getActualColor());
// change track color
track.setColor(Color.red);
assertEquals("Correct color (After track color change)", Color.RED, fw
.getColor());
}
}
public static final String INTERPOLATED_FIX = "INTERPOLATED";
/**
* sort out the version id (recommended to serialisable bits)
*/
private static final long serialVersionUID = 1L;
/**
* the tactical data item we are storing
*/
private Fix _theFix;
/**
* the label describing this fix
*/
private MWC.GUI.Shapes.TextLabel _theLabel;
/**
* the comment describing this fix
*/
private MWC.GUI.Shapes.TextLabel _theCommentBox;
/**
* the symbol representing the center of the fix
*/
private LocationWrapper _theLocationWrapper;
/**
* flag for whether to show the label
*/
private boolean _showLabel;
/** flag for whether to show the comment
*
*/
private boolean _showComment;
/**
* the font to draw this track in.
*/
private Font _theFont;
/**
* whether the location symbol is drawn
*/
private boolean _showSymbol = false;
/**
* whether the arrow symbol is drawn
*/
private boolean _showArrow = false;
/**
* the area covered by this fix
*/
private transient WorldArea _myArea;
/**
* a single instance of our editor type - which can be listened to by multiple listeners
*/
transient private Editable.EditorType _myEditor = null;
/**
* the current format we're using
*
*/
private String _theFormat = MyDateFormatPropertyEditor.getTagList()[0];
/**
* whether to connect this fix to the previous one.
*
*/
private boolean _lineShowing = true;
/**
* whether a user label was supplied. if it wasn't, we allow the reset labels to run
*
*/
private boolean _userLabelSupplied = false;
/**
* the segment we're inside
*
*/
private TrackSegment _parentSegment;
/**
* the track we are a part of (note, we're making it static so that when we serialise it we don't
* store a full copy of the parent track and all it's other fixes. We don't need to store it since
* it gets set when we add it to a new parent layer
*/
private transient WatchableList _trackWrapper;
/**
* take a static reference for the list of property descriptors for this object, since we
* repeatedly retrieve them (each time we do a property edit), yet they are identical across all
* objects of this type
*/
private static PropertyDescriptor[] _coreDescriptors;
// member functions
private static PropertyDescriptor[] _griddableDescriptors;
private static MethodDescriptor[] _methodDescriptors;
/**
* produce an interpolated fix between the two supplied ones
*
*/
static public FixWrapper interpolateFix(final Watchable previous,
final Watchable next, final HiResDate dtg)
{
FixWrapper res = null;
// and the time different?
final long timeDiffMicros =
next.getTime().getMicros() - previous.getTime().getMicros();
// through what proportion are we travelling?
final long thisDelta = dtg.getMicros() - previous.getTime().getMicros();
// sort out the proportion
final double proportion = (double) thisDelta / (double) timeDiffMicros;
// LOCATION
// do the calcs
double dLat = next.getLocation().getLat() - previous.getLocation().getLat();
double dLong =
next.getLocation().getLong() - previous.getLocation().getLong();
double dDepth =
next.getLocation().getDepth() - previous.getLocation().getDepth();
double dCourse = next.getCourse() - previous.getCourse();
// SPECIAL HANDLING FOR COURSE - IN CASE IT'S WRAPPING THROUGH ZERO
if (Math.abs(dCourse) > Math.PI)
{
// ok, put them in the same domain
double pCourse = previous.getCourse();
double nCourse = next.getCourse();
if (pCourse < Math.PI)
{
pCourse += 2 * Math.PI;
}
if (nCourse < Math.PI)
{
nCourse += 2 * Math.PI;
}
dCourse = nCourse - pCourse;
}
double dSpeed = next.getSpeed() - previous.getSpeed();
// sort out the proportions
dLat *= proportion;
dLong *= proportion;
dDepth *= proportion;
dCourse *= proportion;
dSpeed *= proportion;
// and apply it (for both range and depth)
// WorldVector newSep = new WorldVector(sep.getBearing(), sep.getRange()
// proportion, sep.getDepth() * proportion);
// cool, sort out the new location
final WorldLocation newLoc =
new WorldLocation(previous.getLocation().getLat() + dLat, previous
.getLocation().getLong()
+ dLong, previous.getDepth() + dDepth);
// COURSE + SPEED
// calculate the course and speed as being the MLA of the unit
double newCourse = previous.getCourse() + dCourse;
final double newSpeed = previous.getSpeed() + dSpeed;
// ok, trim the course
if (newCourse < 0)
{
newCourse += Math.PI * 2;
}
if (newCourse > Math.PI * 2)
{
newCourse -= Math.PI * 2;
}
final Fix tmpFix =
new Fix(dtg, newLoc, newCourse, MWC.Algorithms.Conversions
.Kts2Yps(newSpeed));
res = new InterpolatedFixWrapper(tmpFix);
if (previous instanceof FixWrapper)
{
final FixWrapper prev = (FixWrapper) previous;
res.setTrackWrapper(prev.getTrackWrapper());
}
// don't forget to indicate it's interpolated
res.setLabel(INTERPOLATED_FIX);
return res;
}
public static void main(final String[] args)
{
final testMe tm = new testMe("scrap");
tm.testMyParams();
}
/**
* intelligently locate the text label. Note, this isn't exactly according to the quadrants, since
* we know the label is wider than it is tall, so it's suitable for courses that are more
* horizontal than vertical
*
* @param courseRads
* the current course (Rads)
* @return the label orientation to use
*/
private static int orientationFor(final double courseRads)
{
final int res;
double degs = Math.toDegrees(courseRads);
// put it in the correct domain
while (degs < 0)
{
degs += 360;
}
while (degs > 360)
{
degs -= 360;
}
// ok, now decide the quadrant
if (degs >= 295 || degs <= 65)
{
res = LocationPropertyEditor.LEFT;
}
else if (degs <= 115)
{
res = LocationPropertyEditor.TOP;
}
else if (degs <= 245)
{
res = LocationPropertyEditor.RIGHT;
}
else
{
res = LocationPropertyEditor.BOTTOM;
}
return res;
}
public FixWrapper(final Fix theFix)
{
// store the fix
_theFix = theFix;
// create the symbol
_theLocationWrapper = new LocationWrapper(_theFix.getLocation());
// create the label
_theLabel = new MWC.GUI.Shapes.TextLabel(_theFix.getLocation(), "");
// move the label around a bit
_theLabel.setFixedOffset(new java.awt.Dimension(4, 4));
_theCommentBox = new MWC.GUI.Shapes.TextLabel(_theFix.getLocation(), "");
// move the label around a bit
_theCommentBox.setFixedOffset(new java.awt.Dimension(4, 4));
_theCommentBox.setRelativeLocation(NullableLocationPropertyEditor.AUTO);
// orient the label according to the current heading
resetLabelLocation();
// hide the name, by default
_showLabel = Boolean.FALSE;
_showComment = Boolean.FALSE;
// declare a duff track
setTrackWrapper(null);
// start us off with a nice font
setFont(Defaults.getFont());
// whether to show symbol
_showSymbol = false;
// reset the colour
setColorQuiet(null);
// check that/if we have an area for this fix
final WorldLocation wl = theFix.getLocation();
if (wl != null)
{
// store the area
_myArea = new WorldArea(wl, wl);
}
}
/**
* instruct this object to clear itself out, ready for ditching
*
*/
@Override
public final void closeMe()
{
// do the parent
super.closeMe();
// forget the track
setTrackWrapper(null);
_theLocationWrapper = null;
_theFix = null;
_myEditor = null;
_myArea = null;
_theLabel = null;
_theCommentBox = null;
setFont(null);
_showLabel = false;
}
/**
* meet the requirements of the comparable interface
*
*/
@Override
public final int compareTo(final Plottable o)
{
int res = 0;
if (o instanceof FixWrapper)
{
final FixWrapper f = (FixWrapper) o;
// cool, use our HiResDate comparator
res = getTime().compareTo(f.getTime());
}
else
{
// just put it first
res = 1;
}
return res;
}
/**
* method to provide the actual colour value stored in this fix
*
* @return fix colour, including null if applicable
*/
public final Color getActualColor()
{
// take the colour from the parent class, not from this one
// - this is mostly because when we do a save, we want to
// correctly reflect that this instance may take it's
// colour from the track - meaning it's storing a null value
return super.getColor();
}
public final boolean getArrowShowing()
{
return _showArrow;
}
@Override
public final WorldArea getBounds()
{
// check that our bounds have been defined
if (_myArea == null)
{
_myArea = new WorldArea(this.getLocation(), this.getLocation());
}
// get the bounds from the data object (or its location object)
return _myArea;
}
/**
* method to return the "sanitised" colour value stored in this fix, that-is if it is null, the
* colour of the track is returned
*
* @return the colour of this fix, or the track if null
*/
@Override
public final Color getColor()
{
Color res = Color.RED;
if (super.getColor() == null)
{
if (_trackWrapper != null)
{
res = _trackWrapper.getColor();
}
}
else
{
res = super.getColor();
}
return res;
}
/**
* return the course (in radians)
*/
@Override
public final double getCourse()
{
return _theFix.getCourse();
}
/**
* return the course (in radians)
*/
public final double getCourseDegs()
{
return MWC.Algorithms.Conversions.Rads2Degs(_theFix.getCourse());
}
public final HiResDate getDateTimeGroup()
{
return _theFix.getTime();
}
/**
* return the depth (in metres)
*/
@Override
public final double getDepth()
{
return _theFix.getLocation().getDepth();
}
@Override
public HiResDate getDTG()
{
return _theFix.getTime();
}
public final Fix getFix()
{
return _theFix;
}
/**
* return the current location of the fix (as a world location). Keep this method, since it's used
* from the fix property editors
*/
public final WorldLocation getFixLocation()
{
return _theFix.getLocation();
}
public final Font getFont()
{
return _theFont;
}
/**
* get the editing information for this type
*/
@Override
public final Editable.EditorType getInfo()
{
String trkName = "Track unset";
if (_trackWrapper != null)
{
trkName = _trackWrapper.getName();
}
if (_myEditor == null)
{
_myEditor = new fixInfo(this, this.getName(), trkName);
}
return _myEditor;
}
public final String getLabel()
{
return _theLabel.getString();
}
public final String getLabelFormat()
{
return _theFormat;
/**
* note, we return null, not the "N/A" value, so that none of the values in the tag list are
* designated as "current value"
*/
}
public final Integer getLabelLocation()
{
return _theLabel.getRelativeLocation();
}
public final boolean getLabelShowing()
{
return _showLabel;
}
public final boolean getCommentShowing()
{
return _showComment;
}
public boolean getLineShowing()
{
return _lineShowing;
}
// watchable (tote) information for this class
@Override
public final WorldLocation getLocation()
{
return _theFix.getLocation();
}
@Override
public String getMultiLineName()
{
return "<u>"
+ _trackWrapper.getName()
+ ":"
+ getName()
+ "</u>\n"
+ GeneralFormat.formatStatus(MWC.Algorithms.Conversions
.Rads2Degs(_theFix.getCourse()), getSpeed(), _theFix.getLocation()
.getDepth());
}
@Override
public String getName()
{
return getLabel();
}
@Override
public Editable getParent()
{
return getTrackWrapper();
}
public TrackSegment getSegment()
{
return _parentSegment;
}
/**
* return the speed (in knots)
*/
@Override
public final double getSpeed()
{
return MWC.Algorithms.Conversions.Yps2Kts(_theFix.getSpeed());
}
/**
* method to get the size of the symbol plotted
*/
public final Double getSymbolScale()
{
return _theLocationWrapper.getSymbolScale();
}
public final boolean getSymbolShowing()
{
return _showSymbol;
}
/**
* return the time of the fix (as long)
*/
@Override
public final HiResDate getTime()
{
return _theFix.getTime();
}
public final WatchableList getTrackWrapper()
{
return _trackWrapper;
}
/**
* indicate that the user has supplied a label for this position fix
*
* @return whether a user label was supplied
*/
public boolean getUserLabelSupplied()
{
return _userLabelSupplied;
}
@Override
public final boolean hasEditor()
{
return true;
}
@Override
public final void paint(final CanvasType dest)
{
/**
* control of the painting functionality has been passed back to the Track object
*/
}
/**
* paint the label using the current settings.
*
* @param dest
* the destination to paint to
*/
public void paintLabel(final CanvasType dest, final Color theCol)
{
// now draw the label
if (getLabelShowing())
{
_theLabel.setColor(theCol);
_theLabel.paint(dest);
}
if(getCommentShowing() && _theCommentBox != null)
{
_theCommentBox.setColor(theCol);
_theCommentBox.paint(dest);
}
}
/**
* paint this shape
*
* @param dest
* @param centre
*/
public void paintMe(final CanvasType dest, final WorldLocation centre,
final Color theColor)
{
if(!getLabelShowing() && !getArrowShowing() && !getSymbolShowing() &&
!getCommentShowing())
{
// ok, they're all off. ignore
return;
}
// take a copy of the color
final Color safeColor = getColor();
// use the provided color
_theLocationWrapper.setColor(theColor);
_theLabel.setColor(theColor);
// // check the color of the location wrapper
// final Color locCol = _theLocationWrapper.getColor();
// if (locCol != getColor())
// _theLocationWrapper.setColor(getColor());
if (getSymbolShowing() && !getArrowShowing())
{
// see if the symbol should be shaded (if the lable is showing)
_theLocationWrapper.setFillSymbol(getLabelShowing());
// override it's location
_theLocationWrapper.setLocation(centre);
// first draw the location (by calling the parenet
_theLocationWrapper.paint(dest);
}
if (getArrowShowing())
{
// ok, have a go at drawing an arrow...
final double direction = (this.getFix().getCourse() + Math.PI / 2);
final double theScale = _theLocationWrapper.getSymbolScale();
final double len = 30d * theScale;
final double angle = MWC.Algorithms.Conversions.Degs2Rads(20);
// move the start point forward, so the centre of the triangle is over the
// point
final Point p0 = dest.toScreen(centre);
final Point p1 = new Point(p0);
p1.translate(-(int) (len / 2d * Math.cos(direction)),
-(int) (len / 2d * Math.sin(direction)));
// now the back corners
final Point p2 = new Point(p1);
p2.translate((int) (len * Math.cos(direction - angle)), (int) (len * Math
.sin(direction - angle)));
final Point p3 = new Point(p1);
p3.translate((int) (len * Math.cos(direction + angle)), (int) (len * Math
.sin(direction + angle)));
dest.fillPolygon(new int[]
{p1.x, p2.x, p3.x}, new int[]
{p1.y, p2.y, p3.y}, 3);
}
// override the label location
_theLabel.setLocation(centre);
_theCommentBox.setLocation(centre);
// and paint the label - if we're asked nicely
paintLabel(dest, theColor);
_theLocationWrapper.setColor(safeColor);
}
/**
* how far away are we from this point? or return null if it can't be calculated
*/
@Override
public final double rangeFrom(final WorldLocation other)
{
return _theFix.getLocation().rangeFrom(other);
}
@FireReformatted
public final void resetColor()
{
// do we know our parent?
if (_trackWrapper != null)
{
// ok, revert to the parent color, we can retrieve
// the color to use from the parent, when we need it
super.setColor(null);
}
}
/**
* the course may have changed, or been assigned. So recalculate where the label should be
*/
@FireReformatted
final public void resetLabelLocation()
{
_theLabel.setRelativeLocation(orientationFor(getCourse()));
// ok, but the comment opposite the label
_theCommentBox.setRelativeLocation(orientationFor(getCourse() + Math.PI));
}
@FireReformatted
public void resetName()
{
// do we have a time?
if (_theFix.getTime() != null)
{
_theLabel.setString(FormatRNDateTime.toShortString(_theFix.getTime()
.getDate().getTime()));
_theFormat = FormatRNDateTime.getExample();
}
else
{
_theLabel.setString("Pending");
}
// forget if there was a user label supplied
this.setUserLabelSupplied(false);
}
public void setArrowShowing(final boolean val)
{
_showArrow = val;
}
@Override
@FireReformatted
public void setColor(final Color theColor)
{
if (theColor != null && !theColor.equals(getColor()))
{
// let the parent do the business
super.setColor(theColor);
// and update the color of the location wrapper
_theLocationWrapper.setColor(getColor());
}
}
/**
* set the course for this observation
*
* @param val
* the course (rads)
*/
public void setCourse(final double val)
{
_theFix.setCourse(val);
}
/**
* change the course
*
*/
public void setCourseDegs(final double val)
{
_theFix.setCourse(MWC.Algorithms.Conversions.Degs2Rads(val));
}
@FireReformatted
public final void setDateTimeGroup(final HiResDate val)
{
_theFix.setTime(val);
}
public void setDepth(final double val)
{
_theFix.getLocation().setDepth(val);
}
public void setDisplayComment(final boolean displayComment)
{
_theCommentBox.setVisible(displayComment);
}
@Override
public void setDTG(final HiResDate date)
{
_theFix.setTime(date);
}
@Override
public void setComment(final String comment)
{
_theCommentBox.setString(comment);
super.setComment(comment);
}
/**
* set the current location of the fix
*/
public final void setFixLocation(final WorldLocation val)
{
// set the central bits
setFixLocationSilent(val);
// also, fire the parent's updated method
super.getSupport().firePropertyChange(PlainWrapper.LOCATION_CHANGED, null,
val);
}
/**
* set the current location of the fix
*/
public final void setFixLocationSilent(final WorldLocation val)
{
_theFix.setLocation(val);
_theLabel.setLocation(val);
_theCommentBox.setLocation(val);
_theLocationWrapper.setLocation(val);
// try to reduce object allocation, if we can...
if (_myArea == null)
{
_myArea = new WorldArea(val, val);
}
else
{
// just reuse our current object
_myArea.setTopLeft(val);
_myArea.setBottomRight(val);
}
// lastly, if we're using a label format that
// includes speed, we've got to update it
if (this.getLabelFormat().equals(MyDateFormatPropertyEditor.DTG_SPEED))
{
this.setLabelFormat(this.getLabelFormat());
}
}
public final void setFont(final Font theFont)
{
_theFont = theFont;
if (_theLabel != null)
{
_theLabel.setFont(getFont());
}
}
@FireReformatted
public final void setLabel(final String val)
{
_theLabel.setString(val);
}
@FireReformatted
public final void setLabelFormat(final String format)
{
// store the value
setLabelFormatSilent(format);
// just check that the user isn't keeping the value as null
if (format == null)
{
return;
}
// check it's a legitimate format
if (!MyDateFormatPropertyEditor.NULL_VALUE.equals(format))
{
final boolean includesSpeed =
MyDateFormatPropertyEditor.DTG_SPEED.equals(format);
final String theFormat;
final String suffix;
if (includesSpeed)
{
// ok, split it
final String[] parts = format.split(" ");
theFormat = parts[0].trim();
final String speedStr =
GeneralFormat.formatOneDecimalPlace(MWC.Algorithms.Conversions
.Yps2Kts(this.getFix().getSpeed()));
suffix = " " + speedStr + "kt";
}
else
{
theFormat = format;
suffix = "";
}
// ok, reformat the label to this format
final java.text.DateFormat df = new GMTDateFormat(theFormat);
final String timeStr = df.format(this.getTime().getDate());
// special handling. See if it's the special SPEED marker
this.setLabel(timeStr + suffix);
}
}
public final void setLabelFormatSilent(final String format)
{
_theFormat = format;
}
// property editor which looks just like the one provided in MWC.GUI, but
// which also has
// a N/A property - which means leave the label as it is
public final void setLabelLocation(final Integer loc)
{
_theLabel.setRelativeLocation(loc);
// if the location is auto, we can handle that
final int newLoc;
switch (loc)
{
case NullableLocationPropertyEditor.BOTTOM:
newLoc = NullableLocationPropertyEditor.TOP;
break;
case NullableLocationPropertyEditor.TOP:
newLoc = NullableLocationPropertyEditor.BOTTOM;
break;
case NullableLocationPropertyEditor.LEFT:
newLoc = NullableLocationPropertyEditor.RIGHT;
break;
case NullableLocationPropertyEditor.RIGHT:
newLoc = NullableLocationPropertyEditor.LEFT;
break;
case NullableLocationPropertyEditor.AUTO:
newLoc = NullableLocationPropertyEditor.AUTO;
break;
default:
newLoc = NullableLocationPropertyEditor.TOP;
break;
}
_theCommentBox.setRelativeLocation(newLoc);
}
@FireReformatted
public final void setLabelShowing(final boolean val)
{
_showLabel = val;
}
@FireReformatted
public final void setCommentShowing(final boolean val)
{
_showComment = val;
}
public void setLineShowing(final boolean val)
{
_lineShowing = val;
}
public void setLocation(final WorldLocation val)
{
_theFix.setLocation(val);
}
public void setSegment(final TrackSegment trackSegment)
{
_parentSegment = trackSegment;
}
/**
* set the speed of this participant (in knots)
*
* @param val
* the speed (knots)
*/
public void setSpeed(final double val)
{
_theFix.setSpeed(MWC.Algorithms.Conversions.Kts2Yps(val));
}
/**
* method to set the size of the symbol plotted
*/
public final void setSymbolScale(final Double val)
{
_theLocationWrapper.setSymbolScale(val);
}
public final void setSymbolShowing(final boolean val)
{
_showSymbol = val;
}
public final void setTrackWrapper(final WatchableList theTrack)
{
if (_trackWrapper != theTrack)
{
_trackWrapper = theTrack;
}
}
/**
* indicate that the user has supplied a label for this position fix
*
* @param yesNo
* whether a user label was supplied
*/
public void setUserLabelSupplied(final boolean yesNo)
{
_userLabelSupplied = yesNo;
}
@Override
public final String toString()
{
return getName();
}
public final boolean
visibleBetween(final HiResDate start, final HiResDate end)
{
return ((this.getTime().greaterThan(start)) && (getTime().lessThan(end)));
}
}
|
package group5.trackerexpress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
// TODO: Auto-generated Javadoc
/**
* The Class EditClaimActivity.
*/
/**
* @author RandyHu
*
*/
public class EditClaimActivity extends Activity {
/** The Claim name. */
private EditText ClaimName;
/** The Claim title. */
private EditText ClaimTitle;
/** The Start date year. */
private EditText StartDateYear;
/** The Start date month. */
private EditText StartDateMonth;
/** The Start date day. */
private EditText StartDateDay;
/** The End date year. */
private EditText EndDateYear;
/** The End date month. */
private EditText EndDateMonth;
/** The End date day. */
private EditText EndDateDay;
/** The Description. */
private EditText Description;
/** The Des name. */
private EditText DesName;
/** The Des rea. */
private EditText DesRea;
/** The Tag name. */
private EditText TagName;
/** The des list view. */
private ListView desListView;
/** The tag list view. */
private ListView tagListView;
/** The value. */
private Editable value;
/** The tags of claim. */
private final HashSet<Tag> tagsOfClaim = new HashSet<Tag>();
/** The check correctness. */
private Boolean checkCorrectness;
/** The Destination. */
private ArrayList<String[]> Destination;
/** The adapter2. */
private ArrayAdapter<String> adapter2;
/** The new destination. */
private final int newDestination = 1;
/** The edit destination. */
private final int editDestination = 2;
/** The do nothing. */
private final int doNothing = 5;
/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_claim);
/**Initialize the dummy destination 2d array which will
be used to store destination and reason of travel for both edit claim and create new claim.*/
Destination = new ArrayList<String[]>();
final Claim newclaim = new Claim("");
/**
* Assign each EditText to a variable.
*/
ClaimName = (EditText) findViewById(R.id.editClaimName);
ClaimTitle = (EditText) findViewById(R.id.editClaimTitle);
StartDateYear = (EditText) findViewById(R.id.editClaimStartDateYear);
StartDateMonth = (EditText) findViewById(R.id.editClaimStartDateMonth);
StartDateDay = (EditText) findViewById(R.id.editClaimStartDateDay);
EndDateYear = (EditText) findViewById(R.id.editClaimEndDateYear);
EndDateMonth = (EditText) findViewById(R.id.editClaimEndDateMonth);
EndDateDay = (EditText) findViewById(R.id.editClaimEndDateDay);
Description = (EditText) findViewById(R.id.editClaimDescription);
desListView = (ListView) findViewById(R.id.listViewDestinations);
tagListView = (ListView) findViewById(R.id.listViewTagsEditClaim);
tagListView.setItemsCanFocus(true);
/**
* On click for add tags button
*/
Button b_add_tag = (Button) findViewById(R.id.buttonEditTags);
b_add_tag.setOnClickListener(new Button.OnClickListener(){
/**
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
getAndSetTag();
}
});
/**
* Tag List Item click listener
*/
tagListView.setOnItemClickListener( new OnItemClickListener() {
/** Make the items in the tag list clickable
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
@Override
public void onItemClick(AdapterView<?> parent,
View view, final int position, long id) {
PopupMenu popup = new PopupMenu(EditClaimActivity.this, view);
popup.getMenuInflater().inflate(R.menu.edit_claim_tag_list_popup, popup.getMenu());
/**
* Popup menu item click listener
*/
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Tag t = (Tag) tagListView.getAdapter().getItem(position);
switch(item.getItemId()){
case R.id.op_edit_claim_delete_tag:
tagsOfClaim.remove(t);
updateTagListView(new ArrayList<Tag>(tagsOfClaim));
break;
default: break;
}
return true;
}
});
popup.show();
}
});
/**
* Get date from Main activity through the controller.
* Get claim id (UUID) if edit claim is selected from Main activity.
*/
final Intent intent = this.getIntent();
final boolean isNewClaim = (boolean) intent.getBooleanExtra("isNewClaim", true);
final ClaimList newclaimlist = ClaimController.getInstance(EditClaimActivity.this).getClaimList();
UUID serialisedId = (UUID) intent.getSerializableExtra("claimUUID");
final Claim claim = ClaimController.getInstance(EditClaimActivity.this).getClaimList().getClaim(serialisedId);
/**
* On click listener for add destination button in EditClaimActivity.
*/
Button editDestinationButton = (Button) findViewById(R.id.buttonAddDestination);
editDestinationButton.setOnClickListener(new View.OnClickListener() {
/** Make add destination button clickable
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
/** check if the user pressed create new claim or edit existing claim button from MainActivity.*/
if (isNewClaim == true){
createDestinationButton(isNewClaim,Destination,newDestination,doNothing);
} else {
Destination = claim.getDestination();
createDestinationButton(isNewClaim, Destination,newDestination,doNothing);
}
}
});
Button done = (Button) findViewById(R.id.buttonCreateClaim);
/**
* Checks if the user wants to edit an existing claim or create a new claim.
* If existing claim, set text to the completed ListViews and ExitTexts.
*/
if (isNewClaim == true){
done.setText("Create Claim");
DestinationListview(desListView,Destination);
} else {
done.setText("Edit Claim");
Destination = claim.getDestination();
ClaimName.setText(claim.getuserName());
ClaimTitle.setText(claim.getClaimName());
if ( claim.getStartDate() != null ){
StartDateYear.setText(String.valueOf(claim.getStartDate().getYYYY()));
StartDateMonth.setText(String.valueOf(claim.getStartDate().getMM()));
StartDateDay.setText(String.valueOf(claim.getStartDate().getDD()));
}
if ( claim.getStartDate() != null ){
EndDateYear.setText(String.valueOf(claim.getEndDate().getYYYY()));
EndDateMonth.setText(String.valueOf(claim.getEndDate().getMM()));
EndDateDay.setText(String.valueOf(claim.getEndDate().getDD()));
}
Description.setText(String.valueOf(claim.getDescription()));
DestinationListview(desListView,Destination);
/** Saving new tags */
ArrayList<Tag> current = TagController.getInstance(this).getTagMap().getTags();
for ( Tag t : tagsOfClaim ){
if ( ! current.contains(t) ){
TagController.getInstance(this).getTagMap().addTag(this, t);
}
}
}
/**
* On item click for the destination and reason ListView.
*/
desListView.setOnItemClickListener(onListClick);
/**
* On click listener for edit claim/create claim button (button name will change depending on what button
* was pressed from the previous activity). Saving the edited/new claim will be triggered only when the
* edit claim/create claim button is pressed.
*/
done.setOnClickListener(new View.OnClickListener() {
/** make edit/create claim button clickable
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
/** this procedure will check if the claim name is repeated */
boolean repeatedClaimName = false;
Claim[] claims = ClaimController.getInstance(EditClaimActivity.this).getClaimList().getAllClaims();
for ( Claim c : claims ){
if ( c.getClaimName().equals( ClaimTitle.getText().toString() )
&& ( isNewClaim || ! c.getUuid().equals(claim.getUuid())) ){
repeatedClaimName = true;
}
}
/** this statement checks if the text fields are valid or not and display error message.*/
if( ClaimName.getText().toString().length() == 0 || ClaimTitle.getText().toString().length() == 0 ){
if ( ClaimName.getText().toString().length() == 0 ){
ClaimName.setError( "Name is required!" );
ClaimName.requestFocus();
}
else if ( ClaimTitle.getText().toString().length() == 0 ){
ClaimTitle.setError( "Title is required!" );
ClaimTitle.requestFocus();
}
} else if (repeatedClaimName) {
ClaimTitle.setError( "Repeated claim name!" );
ClaimTitle.requestFocus();
} else {
/**
* Saves user input into claim class.(calling each method)
*/
Toast.makeText(EditClaimActivity.this, "Updating", Toast.LENGTH_SHORT). show();
if (isNewClaim == true){
editclaim(newclaim);
newclaimlist.addClaim(EditClaimActivity.this, newclaim);
newclaim.setDestination(EditClaimActivity.this, Destination);
} else{
editclaim(claim);
claim.setDestination(EditClaimActivity.this, Destination);
}
/**
* launch MainClaimActivity.
*/
Intent intent = new Intent(EditClaimActivity.this, MainActivity.class);
startActivity(intent);
}
}
});
/**
* On click for Cancel button. Calls "safe guard" method if user accidently
* pressed cancel.
*/
Button cancel = (Button) findViewById(R.id.button_cancel_edit_claim);
cancel.setOnClickListener(new View.OnClickListener() {
/** Make cancel button clickable
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v) {
cancelcheck();
}
});
}
/**
* On click listener for the back button(soft key). Calls "safe guard" method if user accidently
* pressed back button.
* @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//do your stuff
cancelcheck();
}
return super.onKeyDown(keyCode, event);
}
/** Destroy this activity when done.
* @see android.app.Activity#onStop()
*/
@Override
public void onStop(){
super.onStop();
finish();
}
/**
* Gets the and set tag.
* displays a popup autocomplete text view so the user can enter
* a tag name, and then updates the list view
* @return the and set tag
*/
private void getAndSetTag(){
String message = "Enter a new name";
final AutoCompleteTextView input = new AutoCompleteTextView(EditClaimActivity.this);
ArrayList<Tag> tagList = TagController.getInstance(EditClaimActivity.this).getTagMap().getTags();
ArrayList<String> tags = new ArrayList<String>();
for ( int i = 0; i < tagList.size(); i++ ){
tags.add(tagList.get(i).toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EditClaimActivity.this, R.layout.edit_claim_drop_down_item, tags);
input.setAdapter(adapter);
input.setThreshold(1);
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
/**
* @see android.view.View.OnFocusChangeListener#onFocusChange(android.view.View, boolean)
*/
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus){
input.showDropDown();
}
}
});
new AlertDialog.Builder(this)
.setTitle("Create Tag")
.setMessage(message)
.setView(input)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
/**
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int whichButton) {
value = input.getText();
if ( input.getText() != null ){
//Tag newTag = new Tag(input.getText().toString());
Tag newTag;
try {
newTag = TagController.getInstance(getBaseContext()).getTagMap().
searchForTagByString(input.getText().toString());
tagsOfClaim.add(newTag);
updateTagListView(new ArrayList<Tag>(tagsOfClaim));
} catch (IllegalAccessException e) {
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
value = null;
return;
}
boolean notInSet = true;
for ( Tag t : tagsOfClaim ){
if ( t.toString().equals(newTag.toString()) ){
notInSet = false;
}
}
if ( notInSet ){
tagsOfClaim.add(newTag);
}
updateTagListView(new ArrayList<Tag>(tagsOfClaim));
}
/* if (input.getText() == null){
.setError( "Name is required!" );
}
*/
value = null;
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
/**
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int whichButton) {
/** Do nothing */
}
}).show();
}
/**
* Make the items in destination ListView clickable and generate
* a popup box asking user what to do.
*/
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) {
AlertDialog.Builder helperBuilder = new AlertDialog.Builder(EditClaimActivity.this);
helperBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener(){
/** When edit button is pressed, opens the destination popup
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int which){
createDestinationButton(false, Destination,editDestination,position);
}
});
helperBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
/** Back out the activity without doing anything
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which) {
/** Do nothing */
}
});
helperBuilder.setNegativeButton("Delete", new DialogInterface.OnClickListener(){
/** When the delete button is pressed, the item in the dummy listview will be deleted and adapter updated
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which){
String toRemove = adapter2.getItem(position);
adapter2.remove(toRemove);
Destination.remove(position);
adapter2.notifyDataSetChanged();
}
});
AlertDialog helpDialog = helperBuilder.create();
helpDialog.show();
}
};
/**
* Editclaim.
*
* @param claim the claim
* Get info from user and add it to claim.
*/
private void editclaim(final Claim claim) {
// TODO Auto-generated method stub
int mySDateY, mySDateM, mySDateD,myEDateY, myEDateM, myEDateD;
Date d2 = null;
Date d1 = null;
String claimUser = ClaimName.getText().toString();
String Claim_title = ClaimTitle.getText().toString();
String SDateY = StartDateYear.getText().toString();
String SDateM = StartDateMonth.getText().toString();
String SDateD = StartDateDay.getText().toString();
String EDateY = EndDateYear.getText().toString();
String EDateM = EndDateMonth.getText().toString();
String EDateD = EndDateDay.getText().toString();
String Descrip = Description.getText().toString();
/** A check if date is parseable (preventing app from crashing) */
if (ParseHelper.isIntegerParsable(EDateD) &&
ParseHelper.isIntegerParsable(EDateM) &&
ParseHelper.isIntegerParsable(EDateY)){
myEDateD = Integer.parseInt(EDateD);
myEDateM = Integer.parseInt(EDateM);
myEDateY = Integer.parseInt(EDateY);
d2 = new Date(myEDateY, myEDateM, myEDateD);
}
if (ParseHelper.isIntegerParsable(SDateD) &&
ParseHelper.isIntegerParsable(SDateM) &&
ParseHelper.isIntegerParsable(SDateY)){
mySDateD = Integer.parseInt(SDateD);
mySDateM = Integer.parseInt(SDateM);
mySDateY = Integer.parseInt(SDateY);
d1 = new Date(mySDateY, mySDateM, mySDateD);
}
claim.setuserName(this, claimUser);
claim.setClaimName(this, Claim_title);
claim.setStartDate(this, d1);
claim.setEndDate(this, d2);
claim.setDescription(this, Descrip);
for (Tag tag: tagsOfClaim)
claim.getTagsIds().add(tag.getUuid());
ClaimController.getInstance(this).getClaimList().addClaim(this, claim);
}
/**
* Creates the destination button.
*
* @param isNewClaim the is new claim
* @param destination2 the destination2
* @param i the i
* @param position the position
* Create a popup window for entering and editing destination/reason then call save it into the dummy
* 2d destination array.
*/
private void createDestinationButton( final boolean isNewClaim, final ArrayList<String[]> destination2, final int i,final int position) {
AlertDialog.Builder helperBuilder = new AlertDialog.Builder(this);
helperBuilder.setCancelable(false);
helperBuilder.setTitle("Destinations");
LayoutInflater inflater = getLayoutInflater();
View popupview = inflater.inflate(R.layout.activity_popup_destination, null);
helperBuilder.setView(popupview);
DesName = (EditText) popupview.findViewById(R.id.inputDestination);
DesRea = (EditText) popupview.findViewById(R.id.inputDestinationReason);
switch(i){
/** for creating new destination */
case newDestination:
helperBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
/** Once done, add destination into dummy destination
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int which) {
String Des_Name = DesName.getText().toString();
String Des_Rea = DesRea.getText().toString();
editDummyDestination(EditClaimActivity.this, Des_Name, Des_Rea, doNothing, null, newDestination);
}
});
helperBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
/** Return to EditClaimActivity doing nothing
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog helperDialog = helperBuilder.create();
helperDialog.show();
break;
/** for editing a existing destination */
case editDestination:
DesName.setText(destination2.get(position)[0]);
DesRea.setText(destination2.get(position)[1]);
final String oldDestination = destination2.get(position)[0]+" - "+destination2.get(position)[1];
helperBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
/** update destination dummy list
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int which) {
String Des_Name2 = DesName.getText().toString();
String Des_Rea2 = DesRea.getText().toString();
editDummyDestination(EditClaimActivity.this, Des_Name2, Des_Rea2, position, oldDestination,editDestination);
}
});
helperBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
/** Do nothing and return
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog helpDialog = helperBuilder.create();
helpDialog.show();
break;
}
}
/**
* Update tag list view.
*
* @param tagList the tag list
*/
private void updateTagListView( ArrayList<Tag> tagList ){
if ( tagList == null ){
tagList = TagController.getInstance(this).getTagMap().getTags();
}
MainTagListAdapter adapter = new MainTagListAdapter(this, tagList);
tagListView.setAdapter(adapter);
}
/**
* Edits the dummy destination.
*
* @param context the context
* @param place the place
* @param Reason the reason
* @param position the position
* @param oldDestination the old destination
* @param i the i
// Update the adapter and dummy destination arrayList.
*/
public void editDummyDestination(Context context, String place, String Reason, int position, String oldDestination, int i){
String[] travelInfo = new String[2];
travelInfo[0] = place;
travelInfo[1] = Reason;
switch(i){
case newDestination:
adapter2.add(place + " - " + Reason);
adapter2.notifyDataSetChanged();
Destination.add(travelInfo);
break;
case editDestination:
adapter2.insert(place+ " - " + Reason, position);
adapter2.remove(oldDestination);
Destination.set(position,travelInfo);
adapter2.notifyDataSetChanged();
}
}
/**
* Destination listview.
*
* @param myListView the my list view
* @param destination the destination
// set adapter for destination
*/
public void DestinationListview(ListView myListView, ArrayList<String[]> destination){
ArrayList<String> destinationArray = destinationReason(destination);
adapter2 = new ArrayAdapter<String>(this,
R.layout.edit_claim_listview,
destinationArray);
myListView.setAdapter(adapter2);
}
/**
* Destination reason.
*
* @param destination2 the destination2
* @return the array list
// Concatenate destination into one string to display it on simple ListView adapter
*/
public ArrayList<String> destinationReason(ArrayList<String[]> destination2){
final ArrayList<String> destinationreason = new ArrayList<String>();
String destination_reason = "";
for (int i = 0; i< destination2.size(); i++){
destination_reason = destination2.get(i)[0]+ " - " + destination2.get(i)[1];
destinationreason.add(destination_reason);
}
return destinationreason;
}
/**
* Cancelcheck.
*/
public void cancelcheck(){
AlertDialog.Builder helperBuilder = new AlertDialog.Builder(EditClaimActivity.this);
helperBuilder.setCancelable(false);
helperBuilder.setTitle("Warning");
helperBuilder.setMessage("Are you sure you want to exit before saving?");
helperBuilder.setPositiveButton("Proceed", new DialogInterface.OnClickListener(){
/** make Cancel button clickable
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
public void onClick(DialogInterface dialog, int which){
Toast.makeText(EditClaimActivity.this, "Canceling", Toast.LENGTH_SHORT). show();
/** launch MainActivity */
onStop();
}
});
helperBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
/** Do Nothing, return to EditClaimActivity
* @see android.content.DialogInterface.OnClickListener#onClick(android.content.DialogInterface, int)
*/
@Override
public void onClick(DialogInterface dialog, int which){
}
});
AlertDialog helpDialog = helperBuilder.create();
helpDialog.show();
}
}
|
package edu.wustl.query.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.factory.AbstractBizLogicFactory;
import edu.wustl.common.query.pvmanager.impl.PVManagerException;
import edu.wustl.common.querysuite.queryobject.IConstraints;
import edu.wustl.common.querysuite.queryobject.ICustomFormula;
import edu.wustl.common.querysuite.queryobject.IExpression;
import edu.wustl.common.querysuite.queryobject.IParameterizedQuery;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.query.actionForm.SaveQueryForm;
import edu.wustl.query.bizlogic.QueryBizLogic;
import edu.wustl.query.htmlprovider.SavedQueryHtmlProvider;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.global.Utility;
import edu.wustl.query.util.querysuite.QueryModuleConstants;
public class LoadSaveQueryPageAction extends Action
{
@Override
/**
* This action loads all the conditions from the query.
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
String isworkflow= (String)request.getAttribute(Constants.IS_WORKFLOW);
if(isworkflow==null)
{
isworkflow=request.getParameter(Constants.IS_WORKFLOW);
}
String pageOf= (String)request.getAttribute(Constants.PAGE_OF);
if(pageOf==null)
{
pageOf=request.getParameter(Constants.PAGE_OF);
}
request.setAttribute(Constants.PAGE_OF,pageOf);
//System.out.println("");
if(Constants.TRUE.equals(isworkflow))
{
request.setAttribute(Constants.IS_WORKFLOW,Constants.TRUE);
String workflowName= (String)request.getSession().getAttribute(Constants.WORKFLOW_NAME);
request.setAttribute(Constants.WORKFLOW_NAME,workflowName);
}
IQuery queryObject = (IQuery) request.getSession().getAttribute(
Constants.QUERY_OBJECT);
String target = Constants.FAILURE;
boolean isDagEmpty = true;
if (queryObject != null)
{
boolean isShowAll = request.getParameter(Constants.SHOW_ALL) == null ? false : true;
target = loadPage(form, request, queryObject,isShowAll);
IConstraints constraints = queryObject.getConstraints();
for(IExpression exp: constraints)
{
isDagEmpty = false;
}
}
checkIsQueryAlreadyShared(queryObject,request);
if(isDagEmpty)
{
// Handle null query
target = Constants.SUCCESS;
String errorMsg = ApplicationProperties.getValue("query.noLimit.error");
ActionErrors errors = Utility.setActionError(errorMsg,"errors.item");
saveErrors(request, errors);
request.setAttribute(Constants.IS_QUERY_SAVED,Constants.IS_QUERY_SAVED);
}
setErrorMessage(request);
return mapping.findForward(target);
}
/**
* It will check weather the Query is shared or not & set the shared_queries flag in the request
* accordingly.
* @param queryObject query which is to be checked.
* @param request
*/
private void checkIsQueryAlreadyShared(IQuery queryObject, HttpServletRequest request)
{
try
{
QueryBizLogic queryBizLogic = (QueryBizLogic)AbstractBizLogicFactory.getBizLogic(ApplicationProperties.getValue("app.bizLogicFactory"),
"getBizLogic", Constants.ADVANCE_QUERY_INTERFACE_ID);
boolean isShared = queryBizLogic.isSharedQuery((IParameterizedQuery)queryObject);
request.setAttribute(Constants.SAHRED_QUERIES, isShared);
}
catch (BizLogicException e) {
ActionErrors errors = Utility.setActionError(e.getMessage(),"errors.item");
saveErrors(request, errors);
}
}
/**
* This Method generates Html for Save query page
* @param form
* @param request
* @param queryObject
* @param isShowAll
* @return
* @throws PVManagerException
*/
private String loadPage(ActionForm form, HttpServletRequest request,
IQuery queryObject,boolean isShowAll) throws PVManagerException
{
String target;
Map<Integer,ICustomFormula> customFormulaIndexMap = new HashMap<Integer, ICustomFormula>();
String htmlContents = new SavedQueryHtmlProvider().getHTMLForSavedQuery(queryObject, isShowAll,
Constants.SAVE_QUERY_PAGE,customFormulaIndexMap);
request.getSession().setAttribute(QueryModuleConstants.CUSTOM_FORMULA_INDEX_MAP, customFormulaIndexMap);
request.setAttribute(Constants.HTML_CONTENTS, htmlContents);
String showAllLink = isShowAll
? Constants.SHOW_SELECTED_ATTRIBUTE
: Constants.SHOW_ALL_ATTRIBUTE;
request.setAttribute(Constants.SHOW_ALL_LINK, showAllLink);
if (!isShowAll)
{
request.setAttribute(Constants.SHOW_ALL, Constants.TRUE);
}
target = Constants.SUCCESS;
SaveQueryForm savedQueryForm = (SaveQueryForm)form;
if (queryObject.getId() != null && queryObject instanceof ParameterizedQuery)
{
savedQueryForm.setDescription(((ParameterizedQuery)queryObject).getDescription());
savedQueryForm.setTitle(((ParameterizedQuery)queryObject).getName());
}
//the title from GetCount query page should be displayed as default in Save Query page
if (queryObject.getId() == null && queryObject instanceof ParameterizedQuery)
{
savedQueryForm.setTitle(((ParameterizedQuery)queryObject).getName());
}
return target;
}
private void setErrorMessage(HttpServletRequest request)
{
String errorMessage = (String) request.getSession().getAttribute("errorMessageForEditQuery");
if (errorMessage != null)
{
ActionErrors errors = Utility.setActionError(errorMessage,"errors.item");
saveErrors(request, errors);
request.getSession().removeAttribute("errorMessageForEditQuery");
}
}
}
|
package com.redhat.ceylon.compiler.java.runtime;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Indexer;
import com.redhat.ceylon.cmr.api.ArtifactResult;
import com.redhat.ceylon.cmr.api.ArtifactResultType;
import com.redhat.ceylon.cmr.api.DependencyResolver;
import com.redhat.ceylon.cmr.api.JDKUtils;
import com.redhat.ceylon.cmr.api.ModuleDependencyInfo;
import com.redhat.ceylon.cmr.api.ModuleInfo;
import com.redhat.ceylon.cmr.api.RepositoryException;
import com.redhat.ceylon.cmr.impl.AbstractArtifactResult;
import com.redhat.ceylon.cmr.impl.Configuration;
import com.redhat.ceylon.cmr.impl.OSGiDependencyResolver;
import com.redhat.ceylon.cmr.impl.PropertiesDependencyResolver;
import com.redhat.ceylon.cmr.impl.XmlDependencyResolver;
import com.redhat.ceylon.common.Versions;
import com.redhat.ceylon.common.tools.ModuleSpec;
import com.redhat.ceylon.common.tools.ModuleSpec.Option;
import com.redhat.ceylon.compiler.java.codegen.Naming;
import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel;
import com.redhat.ceylon.compiler.java.tools.JarEntryManifestFileObject.OsgiManifest;
public class Main {
private boolean allowMissingModules;
private boolean allowMissingSystem;
private ClassPath classPath;
private Set<ClassPath.Module> visited;
public static Main instance() {
return new Main();
}
private Main() {
}
/**
* When enabled no exceptions will be thrown for not encountering
* proper module dependency information for the module to be loaded
* or any of its dependencies. The system modules still need to be
* present and have proper dependency information.
* @param allowMissingModules If true no exceptions will be thrown
* for missing module dependency information
* @return This object for chaining
*/
public Main allowMissingModules(boolean allowMissingModules) {
this.allowMissingModules = allowMissingModules;
return this;
}
/**
* When enabled no exceptions will be thrown for not encountering
* proper module dependency information for the system modules or
* any of their dependencies.
* @param allowMissingModules If true no exceptions will be thrown
* for missing module dependency information
* @return This object for chaining
*/
public Main allowMissingSystem(boolean allowMissingSystem) {
this.allowMissingSystem = allowMissingSystem;
return this;
}
static class ClassPath {
private static final String METAINF_JBOSSMODULES = "META-INF/jbossmodules/";
private static final String METAINF_MAVEN = "META-INF/maven/";
private static final String MODULE_PROPERTIES = "module.properties";
private static final String MODULE_XML = "module.xml";
private static final String POM_XML = "pom.xml";
@SuppressWarnings("serial")
public class ModuleNotFoundException extends Exception {
public ModuleNotFoundException(String string) {
super(string);
}
}
private enum Type {
CEYLON, JBOSS_MODULES, MAVEN, OSGi, UNKNOWN, JDK;
}
static class Dependency extends AbstractArtifactResult {
public final boolean optional, shared;
public Dependency(String name, String version, boolean optional, boolean shared) {
super(null, name, version);
this.optional = optional;
this.shared = shared;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("Import{ name = ").append(name());
b.append(", version = ").append(version());
b.append(", optional = ").append(optional);
b.append(", shared = ").append(shared);
b.append(" }");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(obj == this)
return true;
if(obj instanceof Dependency == false)
return false;
Dependency other = (Dependency) obj;
return Objects.equals(name(), other.name())
&& Objects.equals(version(), other.version())
&& optional == other.optional
&& shared == other.shared;
}
@Override
public int hashCode() {
int ret = 17;
ret = (ret * 23) + (name() != null ? name().hashCode() : 0);
ret = (ret * 23) + (version() != null ? version().hashCode() : 0);
ret = (ret * 23) + (optional ? 1 : 0);
ret = (ret * 23) + (shared ? 1 : 0);
return ret;
}
@Override
public ArtifactResultType type() {
throw new UnsupportedOperationException();
}
@Override
public List<ArtifactResult> dependencies() throws RepositoryException {
throw new UnsupportedOperationException();
}
@Override
public String repositoryDisplayString() {
throw new UnsupportedOperationException();
}
@Override
protected File artifactInternal() {
throw new UnsupportedOperationException();
}
}
static class Module extends AbstractArtifactResult {
public final File jar;
public final Type type;
public final List<Dependency> dependencies = new LinkedList<Dependency>();
public Module(String name, String version, Type type, File jar) {
super(null, name, version);
this.type = type;
this.jar = jar;
}
public void addDependency(String name, String version, boolean optional, boolean shared) {
dependencies.add(new Dependency(name, version, optional, shared));
}
@Override
public int hashCode() {
int ret = 31;
ret = 37 * ret + name().hashCode();
ret = 37 * ret + (version() != null ? version().hashCode() : 0);
return ret;
}
@Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(obj == this)
return true;
if(obj instanceof Module == false)
return false;
Module other = (Module) obj;
return name().equals(other.name())
&& Objects.equals(version(), other.version());
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("Module{ name = ").append(name());
b.append(", version = ").append(version());
b.append(", jar = ").append(jar);
b.append(", type = ").append(type);
b.append(", dependencies = [");
boolean once = true;
for(Dependency dep : dependencies){
if(once)
once = false;
else
b.append(", ");
b.append(dep);
}
b.append(" ] }");
return b.toString();
}
@Override
public ArtifactResultType type() {
switch(type){
case CEYLON:
case JBOSS_MODULES:
case OSGi:
case JDK:
return ArtifactResultType.CEYLON;
case MAVEN:
return ArtifactResultType.MAVEN;
case UNKNOWN:
default:
return ArtifactResultType.OTHER;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<ArtifactResult> dependencies() throws RepositoryException {
return (List)dependencies;
}
@Override
public String repositoryDisplayString() {
return name()+"/"+version();
}
@Override
protected File artifactInternal() {
return jar;
}
}
private List<File> potentialJars = new LinkedList<File>();
private Map<String,Module> modules = new HashMap<String,Module>();
private static DependencyResolver MavenResolver = getResolver(Configuration.MAVEN_RESOLVER_CLASS);
private static final Module NO_MODULE = new Module("$$$", "$$$", Type.UNKNOWN, null);
ClassPath(){
String classPath = System.getProperty("java.class.path");
String[] classPathEntries = classPath.split(File.pathSeparator);
for(String classPathEntry : classPathEntries){
File entry = new File(classPathEntry);
if(entry.isFile()){
potentialJars.add(entry);
}
}
initJars();
}
// for tests
ClassPath(List<File> potentialJars){
this.potentialJars = potentialJars;
initJars();
}
private List<ZipEntry> findEntries(ZipFile zipFile, String startFolder, String entryName) {
List<ZipEntry> result = new LinkedList<ZipEntry>();
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String name = entry.getName();
if (name.startsWith(startFolder) && name.endsWith(entryName)) {
result.add(entry);
}
}
return result;
}
private ModuleSpec moduleFromEntry(ZipEntry entry) {
String fullName = entry.getName();
if (fullName.startsWith(METAINF_JBOSSMODULES)) {
fullName = fullName.substring(METAINF_JBOSSMODULES.length());
}
if (fullName.endsWith(MODULE_PROPERTIES)) {
fullName = fullName.substring(0, fullName.length() - MODULE_PROPERTIES.length() - 1);
} else if (fullName.endsWith(MODULE_XML)) {
fullName = fullName.substring(0, fullName.length() - MODULE_XML.length() - 1);
}
int p = fullName.lastIndexOf('/');
if (p > 0) {
String name = fullName.substring(0, p);
String version = fullName.substring(p + 1);
if (!name.isEmpty() && !version.isEmpty()) {
name = name.replace('/', '.');
return new ModuleSpec(name, version);
}
}
return null;
}
private static DependencyResolver getResolver(String className) {
try {
ClassLoader cl = Configuration.class.getClassLoader();
return (DependencyResolver) cl.loadClass(className).newInstance();
} catch (Throwable t) {
return null;
}
}
public Module loadModule(String name, String version) throws ModuleNotFoundException{
return loadModule(name, version, false);
}
public Module loadModule(String name, String version, boolean allowMissingModules) throws ModuleNotFoundException{
String key = name + "/" + version;
Module module = modules.get(key);
if(module != null)
return module;
if(JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name)){
module = new Module(name, JDKUtils.jdk.version, Type.JDK, null);
modules.put(key, module);
return module;
}
module = searchJars(name, version);
if (module != null) {
return module;
} else {
if(allowMissingModules){
return new Module(name, version, Type.UNKNOWN, null);
}else{
throw new ModuleNotFoundException("Module "+key+" not found");
}
}
}
// Pre-loads as much modules as possible by going over all potential jar/car files
// in the class path and trying to determine which modules they contain
private void initJars() {
searchJars(null, null);
}
// Goes over all the potential jar/car files in the class path and if a name and
// version were given tries to determine if any of them contain that module.
// If name and version are both `null` it will try to determine the module
// information from the jar/car file itself.
private Module searchJars(String name, String version) {
Module module;
Iterator<File> iterator = potentialJars.iterator();
while(iterator.hasNext()){
File file = iterator.next();
try {
if (name == null && version == null) {
module = initJar(file);
} else {
module = loadJar(file, name, version);
}
} catch (IOException e) {
// faulty jar
iterator.remove();
e.printStackTrace();
System.err.println("Non-zip jar file in classpath: "+file+". Skipping it next time.");
continue;
}
if(module != null){
if (module != NO_MODULE) {
String key = module.name() + "/" + module.version();
modules.put(key, module);
}
iterator.remove();
if (name != null || version != null) {
return module;
}
}
}
return null;
}
private Module initJar(File file) throws IOException {
ZipFile zipFile = new ZipFile(file);
try{
// Try Ceylon module first
List<ZipEntry> moduleDescriptors = findEntries(zipFile, "", Naming.MODULE_DESCRIPTOR_CLASS_NAME+".class");
if(moduleDescriptors.size() == 1) {
try {
return loadCeylonModuleCar(file, zipFile, moduleDescriptors.get(0), null, null);
} catch (IOException ex) {
// Ignore
}
}
// Try JBoss modules next
List<ZipEntry> moduleXmls = findEntries(zipFile, METAINF_JBOSSMODULES, MODULE_XML);
if(moduleXmls.size() == 1) {
ModuleSpec mod = moduleFromEntry(moduleXmls.get(0));
if (mod != null) {
return loadJBossModuleXmlJar(file, zipFile, moduleXmls.get(0), mod.getName(), mod.getVersion());
}
}
List<ZipEntry> moduleProperties = findEntries(zipFile, METAINF_JBOSSMODULES, MODULE_PROPERTIES);
if(moduleProperties.size() == 1) {
ModuleSpec mod = moduleFromEntry(moduleProperties.get(0));
if (mod != null) {
return loadJBossModulePropertiesJar(file, zipFile, moduleProperties.get(0), mod.getName(), mod.getVersion());
}
}
// try Maven
List<ZipEntry> mavenDescriptors = findEntries(zipFile, METAINF_MAVEN, POM_XML);
// TODO: we should try to retrieve the module information (name/version) from the pom.xml entry
// last OSGi
ZipEntry osgiProperties = zipFile.getEntry(JarFile.MANIFEST_NAME);
if(osgiProperties != null){
Module module = loadOsgiJar(file, zipFile, osgiProperties, null, null);
// it's possible we have a MANIFEST but not for the module we're looking for
if(module != null)
return module;
}
if (moduleDescriptors.isEmpty() && moduleXmls.isEmpty() && moduleProperties.isEmpty()
&& mavenDescriptors.isEmpty() && osgiProperties == null) {
// There's nothing we can retrieve from this jar
// let's return a dummy module so the jar will
// get removed from the list of potentials at least
return NO_MODULE;
}
// not found
return null;
}finally{
zipFile.close();
}
}
private Module loadJar(File file, String name, String version) throws IOException {
ZipFile zipFile = new ZipFile(file);
try{
// Modules that have a : MUST be Maven modules
int mavenSeparator = name.indexOf(":");
if(mavenSeparator != -1){
String groupId = name.substring(0, mavenSeparator);
String artifactId = name.substring(mavenSeparator+1);
String descriptorPath = String.format("META-INF/maven/%s/%s/pom.xml", groupId, artifactId);
ZipEntry mavenDescriptor = zipFile.getEntry(descriptorPath);
if(mavenDescriptor != null){
return loadMavenJar(file, zipFile, mavenDescriptor, name, version);
}
}
// Try Ceylon module first
String ceylonPath = name.replace('.', '/');
ZipEntry moduleDescriptor = zipFile.getEntry(ceylonPath+"/"+Naming.MODULE_DESCRIPTOR_CLASS_NAME+".class");
if(moduleDescriptor != null)
return loadCeylonModuleCar(file, zipFile, moduleDescriptor, name, version);
// Special case for Ceylon default module
if(name.equals(com.redhat.ceylon.compiler.typechecker.model.Module.DEFAULT_MODULE_NAME)
&& version == null
&& file.getName().equalsIgnoreCase("default.car"))
return new Module(name, null, Type.CEYLON, file);
// JBoss modules next
ZipEntry moduleXml = zipFile.getEntry("META-INF/jbossmodules/"+ceylonPath+"/"+version+"/module.xml");
if(moduleXml != null)
return loadJBossModuleXmlJar(file, zipFile, moduleXml, name, version);
ZipEntry moduleProperties = zipFile.getEntry("META-INF/jbossmodules/"+ceylonPath+"/"+version+"/module.properties");
if(moduleProperties != null)
return loadJBossModulePropertiesJar(file, zipFile, moduleProperties, name, version);
// try other combinations for Maven
if(MavenResolver != null){
// the case with : has already been taken care of first
int lastDot = name.lastIndexOf('.');
while(lastDot != -1){
String groupId = name.substring(0, lastDot);
String artifactId = name.substring(lastDot+1);
String descriptorPath = String.format("META-INF/maven/%s/%s/pom.xml", groupId, artifactId);
ZipEntry mavenDescriptor = zipFile.getEntry(descriptorPath);
if(mavenDescriptor != null){
return loadMavenJar(file, zipFile, mavenDescriptor, name, version);
}
lastDot = name.lastIndexOf('.', lastDot - 1);
}
}
// last OSGi
ZipEntry osgiProperties = zipFile.getEntry(JarFile.MANIFEST_NAME);
if(osgiProperties != null){
Module module = loadOsgiJar(file, zipFile, osgiProperties, name, version);
// it's possible we have a MANIFEST but not for the module we're looking for
if(module != null)
return module;
}
// not found
return null;
}finally{
zipFile.close();
}
}
private Module loadCeylonModuleCar(File file, ZipFile zipFile, ZipEntry moduleDescriptor, String name, String version) throws IOException {
InputStream inputStream = zipFile.getInputStream(moduleDescriptor);
try{
Indexer indexer = new Indexer();
ClassInfo classInfo = indexer.index(inputStream);
if(classInfo == null)
throw new IOException("Failed to read class info");
Map<DotName, List<AnnotationInstance>> annotations = classInfo.annotations();
DotName moduleAnnotationName = DotName.createSimple(com.redhat.ceylon.compiler.java.metadata.Module.class.getName());
List<AnnotationInstance> moduleAnnotations = annotations.get(moduleAnnotationName);
if(moduleAnnotations == null || moduleAnnotations.size() != 1)
throw new IOException("Missing module annotation: "+annotations);
AnnotationInstance moduleAnnotation = moduleAnnotations.get(0);
AnnotationValue moduleName = moduleAnnotation.value("name");
AnnotationValue moduleVersion = moduleAnnotation.value("version");
if(moduleName == null || moduleVersion == null)
throw new IOException("Invalid module annotation");
if(name != null && !moduleName.asString().equals(name))
throw new IOException("Module name does not match module descriptor");
if(version != null && !moduleVersion.asString().equals(version))
throw new IOException("Module version does not match module descriptor");
name = moduleName.asString();
version = moduleVersion.asString();
Module module = new Module(name, version, Type.CEYLON, file);
AnnotationValue moduleDependencies = moduleAnnotation.value("dependencies");
if(moduleDependencies != null){
for(AnnotationInstance dependency : moduleDependencies.asNestedArray()){
AnnotationValue importName = dependency.value("name");
AnnotationValue importVersion = dependency.value("version");
AnnotationValue importOptional = dependency.value("optional");
AnnotationValue importExport = dependency.value("export");
if(importName == null || importVersion == null)
throw new IOException("Invalid module import");
boolean export = importExport != null ? importExport.asBoolean() : false;
boolean optional = importOptional != null ? importOptional.asBoolean() : false;
module.addDependency(importName.asString(), importVersion.asString(), optional, export);
}
}
return module;
}finally{
inputStream.close();
}
}
private Module loadJBossModulePropertiesJar(File file, ZipFile zipFile, ZipEntry moduleProperties, String name, String version) throws IOException {
return loadJBossModuleJar(file, zipFile, moduleProperties, PropertiesDependencyResolver.INSTANCE, name, version);
}
private Module loadJBossModuleJar(File file, ZipFile zipFile, ZipEntry moduleDescriptor,
DependencyResolver dependencyResolver, String name, String version) throws IOException {
return loadFromResolver(file, zipFile, moduleDescriptor, dependencyResolver, name, version, Type.JBOSS_MODULES);
}
private Module loadFromResolver(File file, ZipFile zipFile, ZipEntry moduleDescriptor,
DependencyResolver dependencyResolver, String name, String version,
Type moduleType) throws IOException {
InputStream inputStream = zipFile.getInputStream(moduleDescriptor);
try{
ModuleInfo moduleDependencies = dependencyResolver.resolveFromInputStream(inputStream);
if (moduleDependencies != null) {
Module module = new Module(name, version, moduleType, file);
for(ModuleDependencyInfo dep : moduleDependencies.getDependencies()){
module.addDependency(dep.getName(), dep.getVersion(), dep.isOptional(), dep.isExport());
}
return module;
}
}finally{
inputStream.close();
}
return null;
}
private Module loadJBossModuleXmlJar(File file, ZipFile zipFile, ZipEntry moduleXml, String name, String version) throws IOException {
return loadJBossModuleJar(file, zipFile, moduleXml, XmlDependencyResolver.INSTANCE, name, version);
}
private Module loadMavenJar(File file, ZipFile zipFile, ZipEntry moduleDescriptor, String name, String version) throws IOException {
return loadFromResolver(file, zipFile, moduleDescriptor, MavenResolver, name, version, Type.MAVEN);
}
private Module loadOsgiJar(File file, ZipFile zipFile, ZipEntry moduleDescriptor, String name, String version) throws IOException {
// first verify that it is indeed for the module we're looking for
InputStream inputStream = zipFile.getInputStream(moduleDescriptor);
try{
Manifest manifest = new Manifest(inputStream);
Attributes attributes = manifest.getMainAttributes();
String bundleName = attributes.getValue(OsgiManifest.Bundle_SymbolicName);
String bundleVersion = attributes.getValue(OsgiManifest.Bundle_Version);
if (name != null && version != null) {
if(!Objects.equals(name, bundleName)|| !Objects.equals(version, bundleVersion))
return null;
} else {
name = bundleName;
version = bundleVersion;
}
}finally{
inputStream.close();
}
return loadFromResolver(file, zipFile, moduleDescriptor, OSGiDependencyResolver.INSTANCE, name, version, Type.OSGi);
}
}
/**
* Sets up the metamodel for the specified module and execute the <code>main</code> method on the
* specified Java class name representing a toplevel Ceylon class or method.
*
* @param module the module name to initialise in the metamodel
* @param version the module version
* @param runClass the Java class name representing a toplevel Ceylon class or method
* @param arguments the arguments to pass to the Ceylon program
*
* @throws RuntimeException if anything wrong happens
*/
public static void runModule(String module, String version, String runClass, String... arguments){
instance().run(module, version, runClass, arguments);
}
/**
* Sets up the metamodel for the specified module and execute the <code>main</code> method on the
* specified Java class name representing a toplevel Ceylon class or method.
*
* @param module the module name to initialise in the metamodel
* @param version the module version
* @param runClass the Java class name representing a toplevel Ceylon class or method
* @param arguments the arguments to pass to the Ceylon program
*
* @throws RuntimeException if anything wrong happens
*/
public void run(String module, String version, String runClass, String... arguments){
setup(module, version);
try {
Class<?> klass = ClassLoader.getSystemClassLoader().loadClass(runClass);
invokeMain(klass, arguments);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/**
* Sets up the metamodel for the specified module and execute the <code>main</code> method on the
* specified Java class representing a toplevel Ceylon class or method.
*
* @param module the module name to initialise in the metamodel
* @param version the module version
* @param runClass the Java class representing a toplevel Ceylon class or method
* @param arguments the arguments to pass to the Ceylon program
*
* @throws RuntimeException if anything wrong happens
*/
public static void runModule(String module, String version, Class<?> runClass, String... arguments){
instance().run(module, version, runClass, arguments);
}
/**
* Sets up the metamodel for the specified module and execute the <code>main</code> method on the
* specified Java class representing a toplevel Ceylon class or method.
*
* @param module the module name to initialise in the metamodel
* @param version the module version
* @param runClass the Java class representing a toplevel Ceylon class or method
* @param arguments the arguments to pass to the Ceylon program
*
* @throws RuntimeException if anything wrong happens
*/
public void run(String module, String version, Class<?> runClass, String... arguments){
setup(module, version);
try {
invokeMain(runClass, arguments);
} catch (NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private static void invokeMain(Class<?> klass, String[] arguments) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method main = klass.getMethod("main", String[].class);
main.invoke(null, (Object)arguments);
}
/**
* Sets up the Ceylon metamodel by adding the specified module to it. This does not run any Ceylon code,
* nor does it reset the metamodel first. You can repeatedly invoke this method to add new Ceylon modules
* to the metamodel.
*
* @param module the module name to load.
* @param version the version to load. Ignored if the module is the default module.
*/
public static void setupMetamodel(String module, String version){
instance().setup(module, version);
}
/**
* Sets up the Ceylon metamodel by adding the specified module to it. This does not run any Ceylon code,
* nor does it reset the metamodel first. You can repeatedly invoke this method to add new Ceylon modules
* to the metamodel.
*
* @param module the module name to load.
* @param version the version to load. Ignored if the module is the default module.
*/
public void setup(String module, String version){
if (classPath == null) {
classPath = new ClassPath();
visited = new HashSet<ClassPath.Module>();
registerInMetamodel("ceylon.language", Versions.CEYLON_VERSION_NUMBER, false, allowMissingSystem);
registerInMetamodel("com.redhat.ceylon.typechecker", Versions.CEYLON_VERSION_NUMBER, false, allowMissingSystem);
registerInMetamodel("com.redhat.ceylon.common", Versions.CEYLON_VERSION_NUMBER, false, allowMissingSystem);
registerInMetamodel("com.redhat.ceylon.module-resolver", Versions.CEYLON_VERSION_NUMBER, false, allowMissingSystem);
registerInMetamodel("com.redhat.ceylon.compiler.java", Versions.CEYLON_VERSION_NUMBER, false, allowMissingSystem);
}
if(module.equals(com.redhat.ceylon.compiler.typechecker.model.Module.DEFAULT_MODULE_NAME))
version = null;
registerInMetamodel(module, version, false, allowMissingModules);
}
/**
* Resets the metamodel. This will impact any Ceylon code running on the same ClassLoader, across
* threads, and will crash them if they are not done running.
*/
public static void resetMetamodel(){
instance().reset();
}
/**
* Resets the metamodel. This will impact any Ceylon code running on the same ClassLoader, across
* threads, and will crash them if they are not done running.
*/
public void reset(){
Metamodel.resetModuleManager();
}
private void registerInMetamodel(String name, String version, boolean optional, boolean allowMissingModules) {
ClassPath.Module module;
try {
module = classPath.loadModule(name, version, allowMissingModules);
} catch (com.redhat.ceylon.compiler.java.runtime.Main.ClassPath.ModuleNotFoundException e) {
if(optional)
return;
throw new RuntimeException(e);
}
if(!visited.add(module))
return;
// skip JDK modules which are already in the metamodel
if(module.type == ClassPath.Type.JDK)
return;
Metamodel.loadModule(name, version, module, ClassLoader.getSystemClassLoader());
// also register its dependencies
for(ClassPath.Dependency dep : module.dependencies)
registerInMetamodel(dep.name(), dep.version(), dep.optional, allowMissingModules);
}
/**
* <p>
* Main entry point, invoke with: <code>moduleSpec</code> <code>mainJavaClassName</code> <code>args*</code>.
* </p>
* <p>
* <b>WARNING:</b> this code will call @{link {@link System#exit(int)} if the arguments
* are incorrect or missing. This is really only intended to be called from the <code>java</code>
* command-line. All it does is parse the arguments and invoke
* @{link {@link Main#runModule(String, String, String, String...)}.
* </p>
*/
public static void main(String[] args) {
int idx = 0;
boolean allowMissingModules = false;
if (args.length > 0 && args[0].equals("--allow-missing-modules")) {
allowMissingModules = true;
idx++;
}
if(args.length < (2 + idx)){
System.err.println("Invalid arguments.");
System.err.println("Usage: \n");
System.err.println(Main.class.getName()+" [--allow-missing-modules] moduleSpec mainJavaClassName args*");
System.exit(1);
}
ModuleSpec moduleSpec = ModuleSpec.parse(args[idx], Option.VERSION_REQUIRED);
String version;
if(moduleSpec.getName().equals(com.redhat.ceylon.compiler.typechecker.model.Module.DEFAULT_MODULE_NAME))
version = null;
else
version = moduleSpec.getVersion();
String[] moduleArgs = Arrays.copyOfRange(args, 2 + idx, args.length);
instance()
.allowMissingModules(allowMissingModules)
.run(moduleSpec.getName(), version, args[idx + 1], moduleArgs);
}
}
|
package com.structurizr;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
public class WorkspaceTests {
private Workspace workspace = new Workspace("Name", "Description");
@Test
public void test_setSource_DoesNotThrowAnException_WhenANullUrlIsSpecified() {
workspace.setSource(null);
}
@Test
public void test_setSource_DoesNotThrowAnException_WhenAnEmptyUrlIsSpecified() {
workspace.setSource("");
}
@Test
public void test_setSource_ThrowsAnException_WhenAnInvalidUrlIsSpecified() {
try {
workspace.setSource("www.somedomain.com");
fail();
} catch (Exception e) {
assertEquals("www.somedomain.com is not a valid URL.", e.getMessage());
}
}
@Test
public void test_setSource_DoesNotThrowAnException_WhenAnValidUrlIsSpecified() {
workspace.setSource("https:
assertEquals("https:
}
@Test
public void test_hasSource_ReturnsFalse_WhenANullSourceIsSpecified() {
workspace.setSource(null);
assertFalse(workspace.hasSource());
}
@Test
public void test_hasSource_ReturnsFalse_WhenAnEmptySourceIsSpecified() {
workspace.setSource(" ");
assertFalse(workspace.hasSource());
}
@Test
public void test_hasSource_ReturnsTrue_WhenAUrlIsSpecified() {
workspace.setSource("https:
assertTrue(workspace.hasSource());
}
@Test
public void test_setApi_DoesNotThrowAnException_WhenANullUrlIsSpecified() {
workspace.setApi(null);
}
@Test
public void test_setApi_DoesNotThrowAnException_WhenAnEmptyUrlIsSpecified() {
workspace.setApi("");
}
@Test
public void test_setApi_ThrowsAnException_WhenAnInvalidUrlIsSpecified() {
try {
workspace.setApi("www.somedomain.com");
fail();
} catch (Exception e) {
assertEquals("www.somedomain.com is not a valid URL.", e.getMessage());
}
}
@Test
public void test_setApi_DoesNotThrowAnException_WhenAnValidUrlIsSpecified() {
workspace.setApi("https:
assertEquals("https:
}
@Test
public void test_hasApi_ReturnsFalse_WhenANullApiIsSpecified() {
workspace.setApi(null);
assertFalse(workspace.hasApi());
}
@Test
public void test_hasApi_ReturnsFalse_WhenAnEmptyApiIsSpecified() {
workspace.setApi(" ");
assertFalse(workspace.hasApi());
}
@Test
public void test_hasApi_ReturnsTrue_WhenAUrlIsSpecified() {
workspace.setApi("https:
assertTrue(workspace.hasApi());
}
@Test
public void test_isEmpty_ReturnsTrue_WhenThereAreNoElementsViewsOrDocumentation() {
workspace = new Workspace("Name", "Description");
assertTrue(workspace.isEmpty());
}
@Test
public void test_isEmpty_ReturnsFalse_WhenThereAreElements() {
workspace = new Workspace("Name", "Description");
workspace.getModel().addPerson("Name", "Description");
assertFalse(workspace.isEmpty());
}
@Test
public void test_isEmpty_ReturnsFalse_WhenThereAreViews() {
workspace = new Workspace("Name", "Description");
workspace.getViews().createEnterpriseContextView("key", "Description");
assertFalse(workspace.isEmpty());
}
@Test
public void test_isEmpty_ReturnsFalse_WhenThereIsDocumentation() throws Exception {
workspace = new Workspace("Name", "Description");
workspace.getDocumentation().addImages(new File("../docs/images"));
assertFalse(workspace.isEmpty());
}
}
|
package com.poco.PoCoRuntime;
public class SequentialExecution extends AbstractExecution implements
Queryable, Matchable {
protected int currentCursor = 0;
protected boolean exhausted = false;
protected boolean currentChildIsZeroPlus = false;
protected boolean currentChildIsOnePlus = false;
public SequentialExecution(String modifier) throws PoCoException {
super(modifier);
}
// use to set the current modifier for the first child before start query,
// and later update modifier while advance cursor
public void getCurrentChildModifier() {
if (this.children.size() > 0 && currentCursor < this.children.size()) {
Class<AbstractExecution> classAE = AbstractExecution.class;
Class<? extends EventResponder> classChild = children.get(
this.currentCursor).getClass();
if (classAE.isAssignableFrom(classChild)) {
// System.out.println("it is assignable from abstractExecution");
currentChildIsZeroPlus = ((AbstractExecution) this.children
.get(this.currentCursor)).isZeroPlus();
currentChildIsOnePlus = ((AbstractExecution) this.children
.get(this.currentCursor)).isOnePlus();
} else {
// now is query the exchange, so isZero and isPlus is the same
}
}
}
public int getCurrentCursor() {
return currentCursor;
}
public boolean isExhausted() {
return exhausted;
}
public boolean isCurrentChildIsZeroPlus() {
return currentChildIsZeroPlus;
}
public boolean isCurrentChildIsOnePlus() {
return currentChildIsOnePlus;
}
/**
* Advances the cursor pointing to the current child to be queried. For
* special cases (i.e. the * modifier), the cursor loops back around to the
* front when we reach the end. while advance cursor, we also should update
* the modifier so that we always get current execution's modifier
*/
protected void advanceCursor() {
if (isZeroPlus || isOnePlus)
currentCursor = (currentCursor + 1) % children.size();
else
currentCursor++;
if (currentCursor >= children.size()) {
exhausted = true;
} else {
// while advance cursor, we also should update the modifier so that
// we always get
// current execution's modifier
getCurrentChildModifier();
}
}
@Override
public SRE query(Event event) {
// Don't do anything without children b
if (children.size() == 0) {
return null;
}
// Also don't do anything if no more children left
if (exhausted) {
return null;
}
getCurrentChildModifier();
EventResponder currentChild = children.get(currentCursor);
if (currentChild.accepts(event)) {
if (!currentChildIsZeroPlus && !currentChildIsOnePlus) {
advanceCursor();
}
resultSRE = currentChild.query(event);
return resultSRE;
} else { //not accepting
if (currentChildIsZeroPlus) {
// We can skip a zero-plus (*) modifier
advanceCursor();
return this.query(event);
} else {
// CurrentChild doesn't accept and can't be skipped
return null;
}
}
}
@Override
public boolean accepts(Event event) {
if (children.size() == 0) {
return false;
}
// The first child of a sequential execution must accept for its parent
// to accept
return children.get(0).accepts(event);
}
@Override
public String toString() {
return "SequentialExecution [currentCursor=" + currentCursor
+ ", exhausted=" + exhausted + ", isZeroPlus=" + isZeroPlus
+ ", isOnePlus=" + isOnePlus + ", children=" + children + "]";
}
}
|
package kodkod.examples.pardinus.decomp;
import java.util.ArrayList;
import java.util.List;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.IntConstant;
import kodkod.ast.IntExpression;
import kodkod.ast.Relation;
import kodkod.ast.Variable;
import kodkod.engine.decomp.DModel;
import kodkod.instance.Bounds;
import kodkod.instance.RelativeBounds;
import kodkod.instance.TupleFactory;
import kodkod.instance.TupleSet;
import kodkod.instance.Universe;
public class HandshakeR implements DModel {
final private Relation hypo;
final private Relation Person, Hilary, Jocelyn, shaken, spouse;
final private Universe u;
final private int persons;
final private Variant2 var;
final private Variant1 counter;
public enum Variant2 {
STATIC,
VARIABLE;
}
public enum Variant1 {
COUNTER,
THEOREM;
}
public HandshakeR(String[] args) {
Person = Relation.unary("Person");
Hilary = Relation.unary("Hilary");
Jocelyn = Relation.unary("Jocelyn");
shaken = Relation.binary("shaken");
spouse = Relation.binary("spouse");
hypo = Relation.unary("hypothesis");
persons = Integer.valueOf(args[0]);
counter = HandshakeR.Variant1.valueOf(args[1]);
var = HandshakeR.Variant2.valueOf(args[2]);
final List<Object> atoms = new ArrayList<Object>((counter == Variant1.THEOREM && var == Variant2.VARIABLE)?2*persons-1:persons);
atoms.add("Hilary");
atoms.add("Jocelyn");
for (int i = 3; i <= persons; i++) {
atoms.add("Person" + i);
}
// if proving theorem with variable persons, integers must be added to the universe
if(counter == Variant1.THEOREM)
if (var == Variant2.VARIABLE)
for (int i = 0; i <= maxInt(); i++)
atoms.add(Integer.valueOf(i));
else
atoms.add(hypo());
u = new Universe(atoms);
}
/**
* Returns the declarations
*
* @return <pre>
* sig Person {spouse: Person }
* one sig Jocelyn, Hilary extends Person {}
*
* fact Spouses {
* all disj p, q: Person {
* // if q is p's spouse, p is q's spouse
* p.spouse = q => q.spouse = p
* // no spouse sharing
* p.spouse != q.spouse
* }
* all p: Person {
* // a person is his or her spouse's spouse
* p.spouse.spouse = p
* // nobody is his or her own spouse
* p != p.spouse
* }
* }
*
* pred Puzzle() {
* // Hilary's spouse is Jocelyn
* Hilary.spouse = Jocelyn
* }
* </pre>
*/
public Formula partition1() {
final Formula f10 = spouse.function(Person, Person);
final Formula f12 = Hilary.one().and(Jocelyn.one());
final Variable p = Variable.unary("p");
final Variable q = Variable.unary("q");
final Formula f1 = p.join(spouse).eq(q).implies(q.join(spouse).eq(p));
final Formula f2 = p.join(spouse).eq(q.join(spouse)).not();
final Formula f3 = p.intersection(q).no().implies(f1.and(f2)).forAll(p.oneOf(Person).and(q.oneOf(Person)));
final Formula f4 = p.join(spouse).join(spouse).eq(p).and(p.eq(p.join(spouse)).not()).forAll(p.oneOf(Person));
final Formula f5 = Hilary.join(spouse).eq(Jocelyn);
Formula res = f10.and(f12).and(f3).and(f4).and(f5);
// if trying to prove theorem, define the integer value of the hypothesis
// if variable, value must be defined at runtime; otherwise it can be calculated statically
if (counter == Variant1.THEOREM) {
final IntExpression nn;
if(var == Variant2.VARIABLE)
nn = ((Person.difference(Hilary)).difference(Jocelyn)).count().divide(IntConstant.constant(2));
else
nn = IntConstant.constant(hypo());
res = res.and(hypo.eq(nn.toExpression()));
}
return res;
}
/**
* Returns the ShakingProtocol fact.
*
* @return <pre>
* sig Person { shaken: set Person}
*
* fact ShakingProtocol {
* // nobody shakes own or spouse's hand
* all p: Person | no (p + p.spouse) & p.shaken
* // if p shakes q, q shakes p
* all p, q: Person | p in q.shaken => q in p.shaken
* }
*
* pred Puzzle() {
* // everyone but Jocelyn has shaken a different number of hands
* all disj p,q: Person - Jocelyn | #p.shaken != #q.shaken
* }
*
* </pre>
*/
public Formula partition2() {
final Formula f0 = shaken.in(Person.product(Person));
final Variable p = Variable.unary("p");
final Variable q = Variable.unary("q");
final Formula f1 = p.union(p.join(spouse)).intersection(p.join(shaken)).no().forAll(p.oneOf(Person));
final Formula f2 = p.in(q.join(shaken)).implies(q.in(p.join(shaken)))
.forAll(p.oneOf(Person).and(q.oneOf(Person)));
final Variable p1 = Variable.unary("p");
final Variable q1 = Variable.unary("q");
final Formula f = p1.eq(q1).not().implies(p1.join(shaken).count().eq(q1.join(shaken).count()).not());
final Expression e = Person.difference(Jocelyn);
final Formula f4 = f.forAll(p1.oneOf(e).and(q1.oneOf(e)));
// if trying to prove theorem, add it to the formula
final Formula f5 = counter == Variant1.COUNTER?f4:(f4.implies((Hilary.join(shaken).count()).toExpression().eq(hypo))).not();
return f0.and(f1).and(f2).and(f5);
}
/**
* Returns a bounds for the given number of persons.
*
* @return a bounds for the given number of persons.
*/
public Bounds bounds1() {
final TupleFactory f = u.factory();
final Bounds b = new Bounds(u);
final TupleSet pb = f.range(f.tuple("Hilary"), f.tuple("Person"+persons));
// if variable, do not bound exactly
if (var == Variant2.VARIABLE) b.bound(Person, pb);
else b.boundExactly(Person, pb);
b.boundExactly(Hilary, f.setOf("Hilary"));
b.boundExactly(Jocelyn, f.setOf("Jocelyn"));
b.bound(spouse, pb.product(pb));
// if proving theorem, define the bounds of the hypothesis
// if variable, integers are part of the universe, must also be bound
if (counter == Variant1.THEOREM) {
final TupleSet ab;
if (var == Variant2.VARIABLE) {
for (int i = 0; i <= maxInt(); i++)
b.boundExactly(i, f.setOf(i));
ab = f.range(f.tuple(Integer.valueOf(0)), f.tuple(Integer.valueOf(maxInt())));
b.bound(hypo, ab);
} else {
b.boundExactly(hypo(), f.setOf(hypo()));
ab = f.setOf(hypo());
b.boundExactly(hypo, ab);
}
}
return b;
}
public Bounds bounds2() {
final TupleFactory f = u.factory();
final RelativeBounds b = new RelativeBounds(u);
b.bound(shaken, new Relation[][]{{Person},{Person}});
return b;
}
@Override
public int getBitwidth() {
return bits(maxInt())+1;
}
private int bits(int n) {
float x = (float) (Math.log(n*2) / Math.log(2));
int y = (int) (1 + Math.floor(x));
return Math.max(3, y);
}
private int maxInt() {
return persons-2;
}
private int hypo() {
return (persons / 2) - 1;
}
public String toString() {
StringBuilder sb = new StringBuilder("Handshake");
sb.append(var == Variant2.VARIABLE?"V":"F");
sb.append(counter == Variant1.COUNTER?"I":"T");
sb.append("-");
sb.append(persons);
return sb.toString();
}
@Override
public String shortName() {
return "Handshake "+persons+" "+counter.name()+" "+var.name();
}
}
|
package org.objectweb.proactive.core.ssh;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
/**
* A minimalistic SSH Client
*
* Args: [-p password] [-l username] [-i identity_file] hostname "cmd"
*
* Pubkey and Password authentications are supported. By default 'id_dsa', 'id_rsa'
* and 'identity' files are tried. If Pubkey authentication fails then password
* authentication is used.
*
*
*/
public class SSHClient {
static final private String OPT_PASSWORD = "p";
static final private String OPT_USERNAME = "l";
static final private String OPT_IDENTITY = "i";
static final private String OPT_HELP = "h";
private static String buildCmdLine(List<String> args) {
StringBuilder cmd = new StringBuilder();
for (String s : args) {
cmd.append(" ");
cmd.append(s);
}
return cmd.toString();
}
public static void printHelp(boolean exit) {
System.out.println("Options:");
System.out.println("\t-" + OPT_USERNAME + "\tusername");
System.out.println("\t-" + OPT_IDENTITY + "\tprivate key");
System.out.println("\t-" + OPT_PASSWORD +
"\tpassword to decrypt the private key");
if (exit) {
System.exit(2);
}
}
public static void main(String[] args) throws ParseException {
Options options = new Options();
options.addOption(OPT_PASSWORD, true,
"Password for password authentication");
options.addOption(OPT_USERNAME, true, "Username");
options.addOption(OPT_IDENTITY, true, "Identity file");
options.addOption(OPT_HELP, false, "Help");
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String username = System.getProperty("user.name");
String password = null;
File identity = null;
String hostname = null;
if (cmd.hasOption(OPT_HELP)) {
printHelp(true);
}
if (cmd.hasOption(OPT_USERNAME)) {
username = cmd.getOptionValue(OPT_USERNAME);
}
if (cmd.hasOption(OPT_PASSWORD)) {
password = cmd.getOptionValue(OPT_PASSWORD);
}
if (cmd.hasOption(OPT_IDENTITY)) {
identity = new File(cmd.getOptionValue(OPT_IDENTITY));
if (!identity.exists()) {
System.err.println("[E] " + identity + " does not exist");
printHelp(true);
}
if (!identity.isFile()) {
System.err.println("[E] " + identity + " is not a file");
printHelp(true);
}
if (!identity.canRead()) {
System.err.println("[E] " + identity +
" is not does not exist");
printHelp(true);
}
}
List<String> remArgs = cmd.getArgList();
if (remArgs.size() == 0) {
System.err.println("[E] You must specify an hostname");
printHelp(true);
}
hostname = remArgs.remove(0);
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = false;
if (identity != null) {
isAuthenticated = conn.authenticateWithPublicKey(username,
identity, null);
} else {
for (String id : SSHKeys.getKeys()) {
File f = new File(id);
if (!(f.exists() && f.isFile() && f.canRead())) {
continue;
}
isAuthenticated = conn.authenticateWithPublicKey(username,
f, null);
System.out.println("Authentication succeeded with " + f);
if (isAuthenticated) {
break;
}
}
}
if (!isAuthenticated) {
isAuthenticated = conn.authenticateWithPassword(username,
password);
}
if (!isAuthenticated) {
System.err.println("[E] Authentication failed");
System.exit(2);
}
conn.setTCPNoDelay(true);
Session sess = conn.openSession();
sess.execCommand(buildCmdLine(remArgs));
InputStream stdout = sess.getStdout();
InputStream stderr = sess.getStderr();
byte[] buffer = new byte[8192];
while (true) {
if ((stdout.available() == 0) && (stderr.available() == 0)) {
/* Even though currently there is no data available, it may be that new data arrives
* and the session's underlying channel is closed before we call waitForCondition().
* This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may
* be set together.
*/
int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA |
ChannelCondition.STDERR_DATA |
ChannelCondition.EOF, 0);
/* Wait no longer than 2 seconds (= 2000 milliseconds) */
if ((conditions & ChannelCondition.TIMEOUT) != 0) {
/* A timeout occured. */
throw new IOException(
"Timeout while waiting for data from peer.");
}
/* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
if ((conditions & ChannelCondition.EOF) != 0) {
/* The remote side won't send us further data... */
if ((conditions &
(ChannelCondition.STDOUT_DATA |
ChannelCondition.STDERR_DATA)) == 0) {
/* ... and we have consumed all data in the local arrival window. */
break;
}
}
/* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */
// You can be paranoid and check that the library is not going nuts:
// if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)
}
/* If you below replace "while" with "if", then the way the output appears on the local
* stdout and stder streams is more "balanced". Addtionally reducing the buffer size
* will also improve the interleaving, but performance will slightly suffer.
* OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
*/
while (stdout.available() > 0) {
int len = stdout.read(buffer);
if (len > 0) { // this check is somewhat paranoid
System.out.write(buffer, 0, len);
}
}
while (stderr.available() > 0) {
int len = stderr.read(buffer);
if (len > 0) { // this check is somewhat paranoid
System.err.write(buffer, 0, len);
}
}
}
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
System.exit(0);
}
}
|
package org.ops4j.pax.exam.it;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import org.osgi.framework.BundleContext;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.RequiresConfiguration;
import org.ops4j.pax.exam.junit.AppliesTo;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.SystemPropertyOption;
import static org.ops4j.pax.exam.CoreOptions.*;
/**
* @author Toni Menzel (tonit)
* @since Jan 8, 2009
*/
@RunWith(JUnit4TestRunner.class)
public class ConfigurationAnnotationTest {
@Configuration
public static Option[] standardConfig() {
return options(
systemProperties(new SystemPropertyOption("standardConfig").value("true"))
);
}
@Configuration
public static Option[] extraConfig() {
return options(
systemProperties(new SystemPropertyOption("extraConfig").value("true"))
);
}
@Configuration
@AppliesTo({".*test3.*", "test4"})
public static Option[] loggingConfig() {
return options(
systemProperties(new SystemPropertyOption("loggingConfig").value("true"))
);
}
@Test
public void test1(final BundleContext bundleContext) {
assertEquals("true", bundleContext.getProperty("standardConfig"));
assertEquals("true", bundleContext.getProperty("extraConfig"));
assertNull(bundleContext.getProperty("loggingConfig"));
}
@Test
@RequiresConfiguration(".*extraConfig.*")
public void test2(final BundleContext bundleContext) {
assertEquals("true", bundleContext.getProperty("extraConfig"));
assertNull(bundleContext.getProperty("loggingConfig"));
assertNull(bundleContext.getProperty("standardConfig"));
}
@Test
public void test4(final BundleContext bundleContext) {
assertEquals("true", bundleContext.getProperty("standardConfig"));
assertEquals("true", bundleContext.getProperty("extraConfig"));
assertEquals("true", bundleContext.getProperty("loggingConfig"));
}
/*
* @Note Toni, Feb, 03, 2009
* What we have here currently is a merge:
* It gets standardConfig because of RequiresConfiguration and loggingConfig because of AppliesTo.
*/
@Test
@RequiresConfiguration(".*standardConfig.*")
public void test3(final BundleContext bundleContext) {
assertEquals("true", bundleContext.getProperty("standardConfig"));
assertNull(bundleContext.getProperty("extraConfig"));
assertEquals("true", bundleContext.getProperty("loggingConfig"));
}
}
|
package org.pentaho.di.ui.spoon.trans;
import java.net.URL;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepStatus;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.gui.XulHelper;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.spoon.Messages;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.XulMessages;
import org.pentaho.di.ui.spoon.delegates.SpoonDelegate;
import org.pentaho.xul.toolbar.XulToolbar;
import org.pentaho.xul.toolbar.XulToolbarButton;
public class TransGridDelegate extends SpoonDelegate {
private static final String XUL_FILE_TRANS_GRID_TOOLBAR = "ui/trans-grid-toolbar.xul";
public static final String XUL_FILE_TRANS_GRID_TOOLBAR_PROPERTIES = "ui/trans-grid-toolbar.properties";
private static final LogWriter log = LogWriter.getInstance();
public static final long REFRESH_TIME = 100L;
public static final long UPDATE_TIME_VIEW = 1000L;
private TransGraph transGraph;
private CTabItem transGridTab;
private TableView transGridView;
private boolean refresh_busy;
private long lastUpdateView;
private XulToolbar toolbar;
private Composite transGridComposite;
private boolean hideInactiveSteps;
/**
* @param spoon
* @param transGraph
*/
public TransGridDelegate(Spoon spoon, TransGraph transGraph) {
super(spoon);
this.transGraph = transGraph;
hideInactiveSteps = false;
}
public void showGridView() {
if (transGridTab==null || transGridTab.isDisposed()) {
addTransGrid();
} else {
transGridTab.dispose();
transGraph.checkEmptyExtraView();
}
}
/**
* Add a grid with the execution metrics per step in a table view
*
*/
public void addTransGrid() {
// First, see if we need to add the extra view...
if (transGraph.extraViewComposite==null || transGraph.extraViewComposite.isDisposed()) {
transGraph.addExtraView();
} else {
if (transGridTab!=null && !transGridTab.isDisposed()) {
// just set this one active and get out...
transGraph.extraViewTabFolder.setSelection(transGridTab);
return;
}
}
transGridTab = new CTabItem(transGraph.extraViewTabFolder, SWT.NONE);
transGridTab.setImage(GUIResource.getInstance().getImageShowGrid());
transGridTab.setText(Messages.getString("Spoon.TransGraph.GridTab.Name"));
transGridComposite = new Composite(transGraph.extraViewTabFolder, SWT.NONE);
transGridComposite.setLayout(new FormLayout());
addToolBar();
addToolBarListeners();
ColumnInfo[] colinf = new ColumnInfo[] {
new ColumnInfo(Messages.getString("TransLog.Column.Stepname"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Copynr"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Read"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Written"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Input"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Output"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Updated"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Rejected"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Errors"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Active"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Time"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.Speed"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
new ColumnInfo(Messages.getString("TransLog.Column.PriorityBufferSizes"), ColumnInfo.COLUMN_TYPE_TEXT, false, true), //$NON-NLS-1$
};
colinf[1].setAllignement(SWT.RIGHT);
colinf[2].setAllignement(SWT.RIGHT);
colinf[3].setAllignement(SWT.RIGHT);
colinf[4].setAllignement(SWT.RIGHT);
colinf[5].setAllignement(SWT.RIGHT);
colinf[6].setAllignement(SWT.RIGHT);
colinf[7].setAllignement(SWT.RIGHT);
colinf[8].setAllignement(SWT.RIGHT);
colinf[9].setAllignement(SWT.RIGHT);
colinf[10].setAllignement(SWT.RIGHT);
colinf[11].setAllignement(SWT.RIGHT);
colinf[12].setAllignement(SWT.RIGHT);
transGridView = new TableView(transGraph.getManagedObject(), transGridComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, 1, true, // readonly!
null, // Listener
spoon.props);
FormData fdView = new FormData();
fdView.left = new FormAttachment(0,0);
fdView.right = new FormAttachment(100,0);
fdView.top = new FormAttachment((Control)toolbar.getNativeObject(),0);
fdView.bottom = new FormAttachment(100,0);
transGridView.setLayoutData(fdView);
// Add a timer to update this view every couple of seconds...
final Timer tim = new Timer("TransGraph: " + transGraph.getMeta().getName());
final AtomicBoolean busy = new AtomicBoolean(false);
TimerTask timtask = new TimerTask()
{
public void run()
{
if (!spoon.getDisplay().isDisposed())
{
spoon.getDisplay().asyncExec(
new Runnable()
{
public void run()
{
if (!busy.get())
{
busy.set(true);
refreshView();
busy.set(false);
}
}
}
);
}
}
};
tim.schedule(timtask, 0L, REFRESH_TIME); // schedule to repeat a couple of times per second to get fast feedback
transGridTab.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent disposeEvent) {
tim.cancel();
}
});
transGridTab.setControl(transGridComposite);
transGraph.extraViewTabFolder.setSelection(transGridTab);
}
private void addToolBar()
{
try {
toolbar = XulHelper.createToolbar(XUL_FILE_TRANS_GRID_TOOLBAR, transGridComposite, TransGridDelegate.this, new XulMessages());
// set the selected icon for the show inactive button.
// This is not a XUL standard apparently
XulToolbarButton onlyActiveButton = toolbar.getButtonById("show-inactive");
if (onlyActiveButton!=null) {
onlyActiveButton.setSelectedImage(GUIResource.getInstance().getImageHideInactive());
}
// Add a few default key listeners
ToolBar toolBar = (ToolBar) toolbar.getNativeObject();
toolBar.addKeyListener(spoon.defKeys);
addToolBarListeners();
toolBar.layout(true, true);
} catch (Throwable t ) {
log.logError(toString(), Const.getStackTracker(t));
new ErrorDialog(transGridComposite.getShell(), Messages.getString("Spoon.Exception.ErrorReadingXULFile.Title"), Messages.getString("Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_GRID_TOOLBAR), new Exception(t));
}
}
public void addToolBarListeners()
{
try
{
// first get the XML document
URL url = XulHelper.getAndValidate(XUL_FILE_TRANS_GRID_TOOLBAR_PROPERTIES);
Properties props = new Properties();
props.load(url.openStream());
String ids[] = toolbar.getMenuItemIds();
for (int i = 0; i < ids.length; i++)
{
String methodName = (String) props.get(ids[i]);
if (methodName != null)
{
toolbar.addMenuListener(ids[i], this, methodName);
}
}
} catch (Throwable t ) {
t.printStackTrace();
new ErrorDialog(transGridComposite.getShell(), Messages.getString("Spoon.Exception.ErrorReadingXULFile.Title"),
Messages.getString("Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_GRID_TOOLBAR_PROPERTIES), new Exception(t));
}
}
public void showHideInactive() {
hideInactiveSteps=!hideInactiveSteps;
// TODO: change icon
XulToolbarButton onlyActiveButton = toolbar.getButtonById("show-inactive");
if (onlyActiveButton!=null) {
onlyActiveButton.setSelection(hideInactiveSteps);
if (hideInactiveSteps) {
onlyActiveButton.setImage(GUIResource.getInstance().getImageHideInactive());
} else {
onlyActiveButton.setImage(GUIResource.getInstance().getImageShowInactive());
}
}
}
private void refreshView()
{
boolean insert = true;
if (transGridView==null || transGridView.isDisposed()) return;
if (refresh_busy) return;
refresh_busy = true;
Table table = transGridView.table;
long time = new Date().getTime();
long msSinceLastUpdate = time - lastUpdateView;
if ( transGraph.trans != null && msSinceLastUpdate > UPDATE_TIME_VIEW )
{
lastUpdateView = time;
int nrSteps = transGraph.trans.nrSteps();
if (hideInactiveSteps) nrSteps = transGraph.trans.nrActiveSteps();
if (table.getItemCount() != nrSteps)
{
table.removeAll();
}
else
{
insert = false;
}
if (nrSteps == 0)
{
if (table.getItemCount() == 0) new TableItem(table, SWT.NONE);
}
int nr = 0;
for (int i = 0; i < transGraph.trans.nrSteps(); i++)
{
BaseStep baseStep = transGraph.trans.getRunThread(i);
//when "Hide active" steps is enabled show only alive steps
//otherwise only those that have not STATUS_EMPTY
if ( (hideInactiveSteps && baseStep.isAlive() ) ||
( !hideInactiveSteps && baseStep.getStatus()!=StepDataInterface.STATUS_EMPTY) )
{
StepStatus stepStatus = new StepStatus(baseStep);
TableItem ti;
if (insert)
{
ti = new TableItem(table, SWT.NONE);
}
else
{
ti = table.getItem(nr);
}
String fields[] = stepStatus.getTransLogFields();
// Anti-flicker: if nothing has changed, don't change it on the screen!
for (int f = 1; f < fields.length; f++)
{
if (!fields[f].equalsIgnoreCase(ti.getText(f)))
{
ti.setText(f, fields[f]);
}
}
// Error lines should appear in red:
if (baseStep.getErrors() > 0)
{
ti.setBackground(GUIResource.getInstance().getColorRed());
}
else
{
if(i%2==0)
ti.setBackground(GUIResource.getInstance().getColorWhite());
else
ti.setBackground(GUIResource.getInstance().getColorBlueCustomGrid());
}
nr++;
}
}
transGridView.setRowNums();
transGridView.optWidth(true);
}
else
{
// We need at least one table-item in a table!
if (table.getItemCount() == 0) new TableItem(table, SWT.NONE);
}
refresh_busy = false;
}
public CTabItem getTransGridTab() {
return transGridTab;
}
}
|
package se.sics.contiki.collect;
import java.util.ArrayList;
import java.util.Hashtable;
public class Node implements Comparable<Node> {
private static final boolean SINGLE_LINK = true;
private SensorDataAggregator sensorDataAggregator;
private ArrayList<SensorData> sensorDataList = new ArrayList<SensorData>();
private ArrayList<Link> links = new ArrayList<Link>();
private final String id;
private final String name;
private int x = -1, y = -1;
private Hashtable<String,Object> objectTable;
private long lastActive;
public Node(String nodeID) {
this.id = nodeID;
this.name = nodeID;
sensorDataAggregator = new SensorDataAggregator(this);
}
public final String getID() {
return id;
}
public final String getName() {
return name;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
public boolean hasLocation() {
return x >= 0 && y >= 0;
}
public long getLastActive() {
return lastActive;
}
public void setLastActive(long lastActive) {
this.lastActive = lastActive;
}
@Override
public int compareTo(Node o) {
String i1 = id;
String i2 = o.getID();
// Shorter id first (4.0 before 10.0)
if (i1.length() == i2.length()) {
return i1.compareTo(i2);
}
return i1.length() - i2.length();
}
public String toString() {
return name;
}
// Attributes
public Object getAttribute(String key) {
return getAttribute(key, null);
}
public Object getAttribute(String key, Object defaultValue) {
if (objectTable == null) {
return null;
}
Object val = objectTable.get(key);
return val == null ? defaultValue : val;
}
public void setAttribute(String key, Object value) {
if (objectTable == null) {
objectTable = new Hashtable<String,Object>();
}
objectTable.put(key, value);
}
public void clearAttributes() {
if (objectTable != null) {
objectTable.clear();
}
}
// SensorData
public SensorDataAggregator getSensorDataAggregator() {
return sensorDataAggregator;
}
public SensorData[] getAllSensorData() {
return sensorDataList.toArray(new SensorData[sensorDataList.size()]);
}
public void removeAllSensorData() {
sensorDataList.clear();
sensorDataAggregator.clear();
}
public SensorData getSensorData(int index) {
return sensorDataList.get(index);
}
public int getSensorDataCount() {
return sensorDataList.size();
}
public boolean addSensorData(SensorData data) {
if (sensorDataList.size() > 0) {
SensorData last = sensorDataList.get(sensorDataList.size() - 1);
// TODO should check seqno!
if (data.getNodeTime() <= last.getNodeTime()) {
// Sensor data already added
System.out.println("SensorData: ignoring (time " + (data.getNodeTime() - last.getNodeTime())
+ "msec): " + data);
return false;
}
}
sensorDataList.add(data);
sensorDataAggregator.addSensorData(data);
return true;
}
// Links
public Link getLink(Node node) {
for(Link l: links) {
if (l.node == node) {
return l;
}
}
// Add new link
Link l = new Link(node);
if (SINGLE_LINK) {
links.clear();
}
links.add(l);
return l;
}
public Link getLink(int index) {
return links.get(index);
}
public int getLinkCount() {
return links.size();
}
public void removeLink(Node node) {
for (int i = 0, n = links.size(); i < n; i++) {
Link l = links.get(i);
if (l.node == node) {
links.remove(i);
break;
}
}
}
public void clearLinks() {
links.clear();
}
}
|
package cz.metacentrum.perun.core.entry;
import cz.metacentrum.perun.core.api.AssignedGroup;
import cz.metacentrum.perun.core.api.AssignedMember;
import cz.metacentrum.perun.core.api.AssignedResource;
import cz.metacentrum.perun.core.api.AuthzResolver;
import cz.metacentrum.perun.core.api.BanOnResource;
import cz.metacentrum.perun.core.api.EnrichedResource;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.ResourceTag;
import cz.metacentrum.perun.core.api.ResourcesManager;
import cz.metacentrum.perun.core.api.RichMember;
import cz.metacentrum.perun.core.api.RichResource;
import cz.metacentrum.perun.core.api.RichUser;
import cz.metacentrum.perun.core.api.Role;
import cz.metacentrum.perun.core.api.Service;
import cz.metacentrum.perun.core.api.ServicesPackage;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.AlreadyAdminException;
import cz.metacentrum.perun.core.api.exceptions.BanAlreadyExistsException;
import cz.metacentrum.perun.core.api.exceptions.BanNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException;
import cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.GroupAlreadyRemovedFromResourceException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotDefinedOnResourceException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.GroupResourceMismatchException;
import cz.metacentrum.perun.core.api.exceptions.GroupResourceStatusException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.PrivilegeException;
import cz.metacentrum.perun.core.api.exceptions.ResourceAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.ResourceExistsException;
import cz.metacentrum.perun.core.api.exceptions.ResourceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ResourceTagAlreadyAssignedException;
import cz.metacentrum.perun.core.api.exceptions.ResourceTagNotAssignedException;
import cz.metacentrum.perun.core.api.exceptions.ResourceTagNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.RoleCannotBeManagedException;
import cz.metacentrum.perun.core.api.exceptions.ServiceAlreadyAssignedException;
import cz.metacentrum.perun.core.api.exceptions.ServiceNotAssignedException;
import cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ServicesPackageNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserNotAdminException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.VoNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.core.bl.ResourcesManagerBl;
import cz.metacentrum.perun.core.impl.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author Slavek Licehammer glory@ics.muni.cz
*/
public class ResourcesManagerEntry implements ResourcesManager {
final static Logger log = LoggerFactory.getLogger(ResourcesManagerEntry.class);
private ResourcesManagerBl resourcesManagerBl;
private PerunBl perunBl;
public ResourcesManagerEntry(PerunBl perunBl) {
this.perunBl = perunBl;
this.resourcesManagerBl = perunBl.getResourcesManagerBl();
}
public ResourcesManagerEntry() {
}
@Override
public Resource getResourceById(PerunSession sess, int id) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
Resource resource = getResourcesManagerBl().getResourceById(sess, id);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getResourceById_int_policy", resource)) {
throw new PrivilegeException(sess, "getResourceById");
}
return resource;
}
@Override
public List<Resource> getResourcesByIds(PerunSession sess, List<Integer> ids) throws PrivilegeException {
Utils.checkPerunSession(sess);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getResourcesByIds_List<Integer>_policy")) {
throw new PrivilegeException(sess, "getResourcesByIds");
}
List<Resource> resources = getResourcesManagerBl().getResourcesByIds(sess, ids);
resources.removeIf(resource -> !AuthzResolver.authorizedInternal(sess, "filter-getResourcesByIds_List<Integer>_policy", resource));
return resources;
}
@Override
public EnrichedResource getEnrichedResourceById(PerunSession sess, int id, List<String> attrNames) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
EnrichedResource eResource = resourcesManagerBl.getEnrichedResourceById(sess, id, attrNames);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getEnrichedResourceById_int_List<String>_policy",
eResource.getResource())) {
throw new PrivilegeException(sess, "getEnrichedResourceById");
}
return resourcesManagerBl.filterOnlyAllowedAttributes(sess, eResource);
}
@Override
public RichResource getRichResourceById(PerunSession sess, int id) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
RichResource rr = getResourcesManagerBl().getRichResourceById(sess, id);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getRichResourceById_int_policy", rr)) {
throw new PrivilegeException(sess, "getRichResourceById");
}
return rr;
}
@Override
public List<RichResource> getRichResourcesByIds(PerunSession sess, List<Integer> ids) throws PrivilegeException {
Utils.checkPerunSession(sess);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getRichResourcesByIds_List<Integer>_policy")) {
throw new PrivilegeException(sess, "getRichResourcesByIds");
}
List<RichResource> richResources = getResourcesManagerBl().getRichResourcesByIds(sess, ids);
richResources.removeIf(richResource -> !AuthzResolver.authorizedInternal(sess, "filter-getRichResourcesByIds_List<Integer>_policy", richResource));
return richResources;
}
@Override
public Resource getResourceByName(PerunSession sess, Vo vo, Facility facility, String name) throws PrivilegeException,
ResourceNotExistsException, VoNotExistsException, FacilityNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
getPerunBl().getFacilitiesManagerBl().checkFacilityExists(sess, facility);
Resource resource = getResourcesManagerBl().getResourceByName(sess, vo, facility, name);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getResourceByName_Vo_Facility_String_policy", Arrays.asList(resource, vo, facility))) {
throw new PrivilegeException(sess, "getResourceByName");
}
return resource;
}
@Override
public Resource createResource(PerunSession sess, Resource resource, Vo vo, Facility facility) throws PrivilegeException, VoNotExistsException, FacilityNotExistsException, ResourceExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
getPerunBl().getFacilitiesManagerBl().checkFacilityExists(sess, facility);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "createResource_Resource_Vo_Facility_policy", Arrays.asList(vo, facility))) {
throw new PrivilegeException(sess, "createResource");
}
return getResourcesManagerBl().createResource(sess, resource, vo, facility);
}
@Override
public Resource copyResource(PerunSession sess, Resource templateResource, Resource destinationResource, boolean withGroups) throws ResourceNotExistsException, PrivilegeException, ResourceExistsException {
Utils.checkPerunSession(sess);
Utils.notNull(templateResource, "Template Resource");
Utils.notNull(destinationResource, "Destination Resource");
getResourcesManagerBl().checkResourceExists(sess, templateResource);
//Authorization
if (!AuthzResolver.authorizedInternal(sess, "copyResource_Resource_Resource_boolean_policy", templateResource) ||
!AuthzResolver.authorizedInternal(sess, "copyResource_Resource_Resource_boolean_policy", destinationResource)) {
throw new PrivilegeException(sess, "copyResource");
}
if(withGroups) {
if(destinationResource.getVoId() != templateResource.getVoId()) {
throw new InternalErrorException("Resources are not from the same VO.");
}
if(!AuthzResolver.authorizedInternal(sess, "withGroups-copyResource_Resource_Resource_boolean_policy", templateResource) ||
!AuthzResolver.authorizedInternal(sess, "withGroups-copyResource_Resource_Resource_boolean_policy", destinationResource)) {
throw new PrivilegeException(sess, "copyResource");
}
}
return getResourcesManagerBl().copyResource(sess, templateResource, destinationResource, withGroups);
}
@Override
public void deleteResource(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException, ResourceAlreadyRemovedException, GroupAlreadyRemovedFromResourceException, FacilityNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "deleteResource_Resource_policy", resource)) {
throw new PrivilegeException(sess, "deleteResource");
}
getResourcesManagerBl().deleteResource(sess, resource);
}
@Override
public void deleteAllResources(PerunSession sess, Vo vo) throws VoNotExistsException, PrivilegeException, ResourceAlreadyRemovedException, GroupAlreadyRemovedFromResourceException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
//Authorization
if (!AuthzResolver.authorizedInternal(sess, "deleteAllResources_Vo_policy", vo)) {
throw new PrivilegeException(sess, "deleteAllResources");
}
getResourcesManagerBl().deleteAllResources(sess, vo);
}
@Override
public Facility getFacility(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getFacility_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getFacility");
}
return getResourcesManagerBl().getFacility(sess, resource);
}
@Override
public Vo getVo(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
Vo vo = getPerunBl().getResourcesManagerBl().getVo(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getVo_Resource_policy", Arrays.asList(vo, resource))) {
throw new PrivilegeException(sess, "getVo");
}
return vo;
}
@Override
public List<Member> getAllowedMembers(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAllowedMembers_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAllowedMembers");
}
return getResourcesManagerBl().getAllowedMembers(sess, resource);
}
@Override
public List<User> getAllowedUsers(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAllowedUsers_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAllowedUsers");
}
return getResourcesManagerBl().getAllowedUsers(sess, resource);
}
@Override
public List<Service> getAssignedServices(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedServices_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAssignedServices");
}
return getResourcesManagerBl().getAssignedServices(sess, resource);
}
@Override
public List<Member> getAssignedMembers(PerunSession sess, Resource resource) throws PrivilegeException {
Utils.checkPerunSession(sess);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedMembers_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAssignedMembers");
}
return getResourcesManagerBl().getAssignedMembers(sess, resource);
}
@Override
public List<AssignedMember> getAssignedMembersWithStatus(PerunSession sess, Resource resource) throws PrivilegeException {
Utils.checkPerunSession(sess);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedMembersWithStatus_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAssignedMembersWithStatus");
}
return getResourcesManagerBl().getAssignedMembersWithStatus(sess, resource);
}
@Override
public List<RichMember> getAssignedRichMembers(PerunSession sess, Resource resource) throws PrivilegeException {
Utils.checkPerunSession(sess);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedRichMembers_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAssignedRichMembers");
}
return getResourcesManagerBl().getAssignedRichMembers(sess, resource);
}
@Override
public void assignGroupToResource(PerunSession sess, Group group, Resource resource, boolean async, boolean assignInactive, boolean autoAssignSubgroups) throws PrivilegeException, GroupNotExistsException, ResourceNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "assignGroupToResource_Group_Resource_policy", Arrays.asList(group, resource))) {
throw new PrivilegeException(sess, "assignGroupToResource");
}
getResourcesManagerBl().assignGroupToResource(sess, group, resource, async, assignInactive, autoAssignSubgroups);
}
@Override
public void assignGroupsToResource(PerunSession perunSession, List<Group> groups, Resource resource, boolean async, boolean assignInactive, boolean autoAssignSubgroups) throws PrivilegeException, GroupNotExistsException, ResourceNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException {
Utils.checkPerunSession(perunSession);
Utils.notNull(groups, "groups");
getResourcesManagerBl().checkResourceExists(perunSession, resource);
// Authorization
for (Group group: groups) {
if (!AuthzResolver.authorizedInternal(perunSession, "assignGroupsToResource_List<Group>_Resource_policy", group, resource)) {
throw new PrivilegeException(perunSession, "assignGroupsToResource");
}
}
getResourcesManagerBl().assignGroupsToResource(perunSession, groups, resource, async, assignInactive, autoAssignSubgroups);
}
@Override
public void assignGroupToResources(PerunSession perunSession, Group group, List<Resource> resources, boolean async, boolean assignInactive, boolean autoAssignSubgroups) throws PrivilegeException, GroupNotExistsException, ResourceNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, GroupResourceMismatchException {
Utils.checkPerunSession(perunSession);
Utils.notNull(resources, "resources");
getPerunBl().getGroupsManagerBl().checkGroupExists(perunSession, group);
for(Resource r: resources) {
getResourcesManagerBl().checkResourceExists(perunSession, r);
}
// Authorization
for (Resource resource: resources) {
if (!AuthzResolver.authorizedInternal(perunSession, "assignGroupToResources_Group_List<Resource>_policy", resource, group)) {
throw new PrivilegeException(perunSession, "assignGroupToResources");
}
}
getResourcesManagerBl().assignGroupToResources(perunSession, group, resources, async, assignInactive, autoAssignSubgroups);
}
@Override
public void removeGroupFromResource(PerunSession sess, Group group, Resource resource) throws PrivilegeException, GroupNotExistsException, ResourceNotExistsException, GroupNotDefinedOnResourceException, GroupAlreadyRemovedFromResourceException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "removeGroupFromResource_Group_Resource_policy", Arrays.asList(group, resource))) {
throw new PrivilegeException(sess, "removeGroupFromResource");
}
getResourcesManagerBl().removeGroupFromResource(sess, group, resource);
}
@Override
public void removeGroupsFromResource(PerunSession perunSession, List<Group> groups, Resource resource) throws PrivilegeException, GroupNotExistsException, ResourceNotExistsException, GroupNotDefinedOnResourceException, GroupAlreadyRemovedFromResourceException {
Utils.checkPerunSession(perunSession);
Utils.notNull(groups, "groups");
getResourcesManagerBl().checkResourceExists(perunSession, resource);
for(Group g: groups) {
getPerunBl().getGroupsManagerBl().checkGroupExists(perunSession, g);
}
// Authorization
for (Group group: groups) {
if (!AuthzResolver.authorizedInternal(perunSession, "removeGroupsFromResource_List<Group>_Resource_policy", group, resource)) {
throw new PrivilegeException(perunSession, "removeGroupsFromResource");
}
}
getResourcesManagerBl().removeGroupsFromResource(perunSession, groups, resource);
}
@Override
public void removeGroupFromResources(PerunSession perunSession, Group group, List<Resource> resources) throws PrivilegeException, GroupNotExistsException, ResourceNotExistsException, GroupNotDefinedOnResourceException, GroupAlreadyRemovedFromResourceException {
Utils.checkPerunSession(perunSession);
Utils.notNull(resources, "resources");
getPerunBl().getGroupsManagerBl().checkGroupExists(perunSession, group);
for(Resource r: resources) {
getResourcesManagerBl().checkResourceExists(perunSession, r);
}
// Authorization
for (Resource resource: resources) {
if (!AuthzResolver.authorizedInternal(perunSession, "removeGroupFromResources_Group_List<Resource>_policy", resource, group)) {
throw new PrivilegeException(perunSession, "removeGroupFromResources");
}
}
getResourcesManagerBl().removeGroupFromResources(perunSession, group, resources);
}
@Override
public List<Group> getAssignedGroups(PerunSession sess, Resource resource) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedGroups_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAssignedGroups");
}
List<Group> assignedGroups = getResourcesManagerBl().getAssignedGroups(sess, resource);
assignedGroups.removeIf(assignedGroup -> !AuthzResolver.authorizedInternal(sess, "filter-getAssignedGroups_Resource_policy", assignedGroup, resource));
return assignedGroups;
}
@Override
public List<Group> getAssignedGroups(PerunSession sess, Resource resource, Member member) throws PrivilegeException, ResourceNotExistsException, MemberNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedGroups_Resource_Member_policy", Arrays.asList(resource, member))) {
throw new PrivilegeException(sess, "getAssignedGroups");
}
return getResourcesManagerBl().getAssignedGroups(sess, resource, member);
}
@Override
public List<Resource> getAssignedResources(PerunSession sess, Group group) throws GroupNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedResources_Group_policy", group)) {
throw new PrivilegeException(sess, "getAssignedResources");
}
return getResourcesManagerBl().getAssignedResources(sess, group).stream()
.filter(resource -> AuthzResolver.authorizedInternal(sess, "filter-getAssignedResources_Group_policy", group, resource))
.collect(Collectors.toList());
}
@Override
public List<RichResource> getAssignedRichResources(PerunSession sess, Group group) throws GroupNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedRichResources_Group_policy", group)) {
throw new PrivilegeException(sess, "getAssignedRichResources");
}
return getResourcesManagerBl().getAssignedRichResources(sess, group).stream()
.filter(resource -> AuthzResolver.authorizedInternal(sess, "filter-getAssignedRichResources_Group_policy", group, resource))
.collect(Collectors.toList());
}
@Override
public void assignService(PerunSession sess, Resource resource, Service service) throws PrivilegeException, ResourceNotExistsException, ServiceNotExistsException, ServiceAlreadyAssignedException, WrongAttributeValueException, WrongReferenceAttributeValueException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "assignService_Resource_Service_policy", Arrays.asList(resource, service))) {
throw new PrivilegeException(sess, "assignService");
}
getResourcesManagerBl().assignService(sess, resource, service);
}
@Override
public void assignServices(PerunSession sess, Resource resource, List<Service> services) throws PrivilegeException, ResourceNotExistsException, ServiceNotExistsException, ServiceAlreadyAssignedException, WrongAttributeValueException, WrongReferenceAttributeValueException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
for (Service service : services) {
getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
}
// Authorization
for (Service service: services) {
if(!AuthzResolver.authorizedInternal(sess, "assignServices_Resource_List<Service>_policy", service, resource)){
throw new PrivilegeException(sess, "assignServices");
}
}
getResourcesManagerBl().assignServices(sess, resource, services);
}
@Override
public void assignServicesPackage(PerunSession sess, Resource resource, ServicesPackage servicesPackage) throws PrivilegeException, ResourceNotExistsException, ServicesPackageNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getServicesManagerBl().checkServicesPackageExists(sess, servicesPackage);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "assignServicesPackage_Resource_ServicesPackage_policy", Arrays.asList(resource, servicesPackage))) {
throw new PrivilegeException(sess, "assignServicesPackage");
}
getResourcesManagerBl().assignServicesPackage(sess, resource, servicesPackage);
}
@Override
public void removeService(PerunSession sess, Resource resource, Service service) throws PrivilegeException, ResourceNotExistsException, ServiceNotExistsException, ServiceNotAssignedException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "removeService_Resource_Service_policy", Arrays.asList(resource, service))) {
throw new PrivilegeException(sess, "removeServices");
}
getResourcesManagerBl().removeService(sess, resource, service);
}
@Override
public void removeServices(PerunSession sess, Resource resource, List<Service> services) throws PrivilegeException, ResourceNotExistsException, ServiceNotExistsException, ServiceNotAssignedException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
for (Service service : services) {
getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
}
// Authorization
for (Service service: services) {
if(!AuthzResolver.authorizedInternal(sess, "removeServices_Resource_List<Service>_policy", service, resource)){
throw new PrivilegeException(sess, "removeServices");
}
}
getResourcesManagerBl().removeServices(sess, resource, services);
}
@Override
public void removeServicesPackage(PerunSession sess, Resource resource, ServicesPackage servicesPackage) throws PrivilegeException, ResourceNotExistsException, ServicesPackageNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getServicesManagerBl().checkServicesPackageExists(sess, servicesPackage);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "removeServicesPackage_Resource_ServicesPackage_policy", Arrays.asList(resource, servicesPackage))) {
throw new PrivilegeException(sess, "removeServicesPackage");
}
getResourcesManagerBl().removeServicesPackage(sess, resource, servicesPackage);
}
@Override
public List<Resource> getResources(PerunSession sess, Vo vo) throws PrivilegeException, VoNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getResources_Vo_policy", vo)) {
throw new PrivilegeException(sess, "getResources");
}
List<Resource> resources = getResourcesManagerBl().getResources(sess, vo);
List<Resource> allowedResources = new ArrayList<>();
for (Resource resource : resources) {
if (AuthzResolver.authorizedInternal(sess, "filter-getResources_Vo_policy", Arrays.asList(vo, resource))) {
allowedResources.add(resource);
}
}
resources = allowedResources;
return resources;
}
@Override
public List<RichResource> getRichResources(PerunSession sess, Vo vo) throws PrivilegeException, VoNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getRichResources_Vo_policy", vo)) {
throw new PrivilegeException(sess, "getRichResources");
}
List<RichResource> resources = getResourcesManagerBl().getRichResources(sess, vo);
List<RichResource> allowedResources = new ArrayList<>();
for (RichResource resource : resources) {
if (AuthzResolver.authorizedInternal(sess, "filter-getRichResources_Vo_policy", Arrays.asList(vo, resource))) {
allowedResources.add(resource);
}
}
resources = allowedResources;
return resources;
}
@Override
public List<EnrichedResource> getEnrichedResourcesForVo(PerunSession sess, Vo vo, List<String> attrNames) throws VoNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getEnrichedResourcesForVo_Vo_policy", vo)) {
throw new PrivilegeException(sess, "getEnrichedResourcesForVo");
}
return getResourcesManagerBl().getEnrichedRichResourcesForVo(sess, vo, attrNames).stream()
.filter(eResource -> AuthzResolver.authorizedInternal(sess,
"filter-getEnrichedResourcesForVo_Vo_policy", vo, eResource.getResource()))
.map(eResource -> getResourcesManagerBl().filterOnlyAllowedAttributes(sess, eResource))
.collect(Collectors.toList());
}
@Override
public List<EnrichedResource> getEnrichedResourcesForFacility(PerunSession sess, Facility facility, List<String> attrNames) throws FacilityNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getFacilitiesManagerBl().checkFacilityExists(sess, facility);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getEnrichedResourcesForFacility_Facility_policy", facility)) {
throw new PrivilegeException(sess, "getEnrichedResourcesForFacility");
}
return getResourcesManagerBl().getEnrichedRichResourcesForFacility(sess, facility, attrNames).stream()
.filter(eResource -> AuthzResolver.authorizedInternal(sess,
"filter-getEnrichedResourcesForFacility_Facility_policy", facility, eResource.getResource()))
.map(eResource -> getResourcesManagerBl().filterOnlyAllowedAttributes(sess, eResource))
.collect(Collectors.toList());
}
@Override
public int getResourcesCount(PerunSession sess, Vo vo) throws PrivilegeException, VoNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getResourcesCount_Vo_policy", vo)) {
throw new PrivilegeException(sess, "getResourcesCount");
}
return getResourcesManagerBl().getResourcesCount(sess, vo);
}
@Override
public int getResourcesCount(PerunSession sess) {
Utils.checkPerunSession(sess);
return getResourcesManagerBl().getResourcesCount(sess);
}
@Override
public List<Resource> getAllowedResources(PerunSession sess, Member member) throws MemberNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAllowedResources_Member_policy", member)) {
throw new PrivilegeException(sess, "getAllowedResources");
}
return getResourcesManagerBl().getAllowedResources(sess, member);
}
@Override
public List<Resource> getAssignedResources(PerunSession sess, Member member) throws PrivilegeException, MemberNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedResources_Member_policy", member)) {
throw new PrivilegeException(sess, "getAssignedResources");
}
return getResourcesManagerBl().getAssignedResources(sess, member);
}
@Override
public List<AssignedResource> getAssignedResourcesWithStatus(PerunSession sess, Member member) throws PrivilegeException, MemberNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedResourcesWithStatus_Member_policy", member)) {
throw new PrivilegeException(sess, "getAssignedResourcesWithStatus");
}
return getResourcesManagerBl().getAssignedResourcesWithStatus(sess, member);
}
@Override
public List<Resource> getAssignedResources(PerunSession sess, Member member, Service service) throws PrivilegeException, MemberNotExistsException, ServiceNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedResources_Member_Service_policy", Arrays.asList(member, service))) {
throw new PrivilegeException(sess, "getAssignedResources");
}
return getResourcesManagerBl().getAssignedResources(sess, member, service);
}
@Override
public List<RichResource> getAssignedRichResources(PerunSession sess, Member member) throws PrivilegeException, MemberNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedRichResources_Member_policy", member)) {
throw new PrivilegeException(sess, "getAssignedRichResources");
}
return getResourcesManagerBl().getAssignedRichResources(sess, member);
}
@Override
public List<RichResource> getAssignedRichResources(PerunSession sess, Member member, Service service) throws PrivilegeException, MemberNotExistsException, ServiceNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getMembersManagerBl().checkMemberExists(sess, member);
getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAssignedRichResources_Member_Service_policy", Arrays.asList(member, service))) {
throw new PrivilegeException(sess, "getAssignedRichResources");
}
return getResourcesManagerBl().getAssignedRichResources(sess, member, service);
}
@Override
public Resource updateResource(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException, ResourceExistsException {
Utils.notNull(sess, "sess");
resourcesManagerBl.checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "updateResource_Resource_policy", resource)) {
throw new PrivilegeException(sess, "updateResource");
}
return resourcesManagerBl.updateResource(sess, resource);
}
@Override
public ResourceTag createResourceTag(PerunSession perunSession, ResourceTag resourceTag, Vo vo) throws PrivilegeException, VoNotExistsException {
Utils.notNull(perunSession, "perunSession");
Utils.notNull(resourceTag, "resourceTag");
getPerunBl().getVosManagerBl().checkVoExists(perunSession, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "createResourceTag_ResourceTag_Vo_policy", vo)) {
throw new PrivilegeException(perunSession, "createResourceTag");
}
return resourcesManagerBl.createResourceTag(perunSession, resourceTag, vo);
}
@Override
public ResourceTag updateResourceTag(PerunSession perunSession, ResourceTag resourceTag) throws PrivilegeException, ResourceTagNotExistsException, VoNotExistsException {
Utils.notNull(perunSession, "perunSession");
Utils.notNull(resourceTag, "resourceTag");
getResourcesManagerBl().checkResourceTagExists(perunSession, resourceTag);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "updateResourceTag_ResourceTag_policy", resourceTag)) {
throw new PrivilegeException(perunSession, "updateResourceTag");
}
return resourcesManagerBl.updateResourceTag(perunSession, resourceTag);
}
@Override
public void deleteResourceTag(PerunSession perunSession, ResourceTag resourceTag) throws PrivilegeException, VoNotExistsException, ResourceTagAlreadyAssignedException, ResourceTagNotExistsException {
Utils.notNull(perunSession, "perunSession");
Utils.notNull(resourceTag, "resourceTag");
getResourcesManagerBl().checkResourceTagExists(perunSession, resourceTag);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "deleteResourceTag_ResourceTag_policy", resourceTag)) {
throw new PrivilegeException(perunSession, "deleteResourceTag");
}
resourcesManagerBl.deleteResourceTag(perunSession, resourceTag);
}
@Override
public void deleteAllResourcesTagsForVo(PerunSession perunSession, Vo vo) throws PrivilegeException, VoNotExistsException, ResourceTagAlreadyAssignedException {
Utils.notNull(perunSession, "perunSession");
getPerunBl().getVosManagerBl().checkVoExists(perunSession, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "deleteAllResourcesTagsForVo_Vo_policy", vo)) {
throw new PrivilegeException(perunSession, "deleteAllResourcesTagsForVo");
}
resourcesManagerBl.deleteAllResourcesTagsForVo(perunSession, vo);
}
@Override
public void assignResourceTagToResource(PerunSession perunSession, ResourceTag resourceTag, Resource resource) throws PrivilegeException, ResourceTagNotExistsException, ResourceNotExistsException, ResourceTagAlreadyAssignedException {
Utils.notNull(perunSession, "perunSession");
Utils.notNull(resourceTag, "resourceTag");
resourcesManagerBl.checkResourceExists(perunSession, resource);
resourcesManagerBl.checkResourceTagExists(perunSession, resourceTag);
if(resourceTag.getVoId() != resource.getVoId()) throw new ConsistencyErrorException("ResourceTag is from other Vo than Resource to which you want to assign it.");
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "assignResourceTagToResource_ResourceTag_Resource_policy", Arrays.asList(resource, resourceTag))) {
throw new PrivilegeException(perunSession, "assignResourceTagToResource");
}
resourcesManagerBl.assignResourceTagToResource(perunSession, resourceTag, resource);
}
@Override
public void removeResourceTagFromResource(PerunSession perunSession, ResourceTag resourceTag, Resource resource) throws PrivilegeException, ResourceTagNotExistsException, ResourceNotExistsException, ResourceTagNotAssignedException {
Utils.notNull(perunSession, "perunSession");
Utils.notNull(resourceTag, "resourceTag");
resourcesManagerBl.checkResourceExists(perunSession, resource);
resourcesManagerBl.checkResourceTagExists(perunSession, resourceTag);
if(resourceTag.getVoId() != resource.getVoId()) throw new ConsistencyErrorException("ResourceTag is from other Vo than Resource to which you want to remove from.");
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "removeResourceTagFromResource_ResourceTag_Resource_policy", Arrays.asList(resource, resourceTag))) {
throw new PrivilegeException(perunSession, "removeResourceTagFromResource");
}
resourcesManagerBl.removeResourceTagFromResource(perunSession, resourceTag, resource);
}
@Override
public void removeAllResourcesTagFromResource(PerunSession perunSession, Resource resource) throws PrivilegeException, ResourceNotExistsException {
Utils.notNull(perunSession, "perunSession");
resourcesManagerBl.checkResourceExists(perunSession, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "removeAllResourcesTagFromResource_Resource_policy", resource)) {
throw new PrivilegeException(perunSession, "removeAllResourcesTagFromResource");
}
resourcesManagerBl.removeAllResourcesTagFromResource(perunSession, resource);
}
@Override
public List<Resource> getAllResourcesByResourceTag(PerunSession perunSession, ResourceTag resourceTag) throws PrivilegeException, VoNotExistsException, ResourceTagNotExistsException {
Utils.notNull(perunSession, "perunSession");
Utils.notNull(resourceTag, "resourceTag");
resourcesManagerBl.checkResourceTagExists(perunSession, resourceTag);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "getAllResourcesByResourceTag_ResourceTag_policy", resourceTag)) {
throw new PrivilegeException(perunSession, "getAllResourcesByResourceTag");
//TODO: what about GROUPADMIN?
}
return resourcesManagerBl.getAllResourcesByResourceTag(perunSession, resourceTag);
}
@Override
public List<ResourceTag> getAllResourcesTagsForVo(PerunSession perunSession, Vo vo) throws PrivilegeException, VoNotExistsException {
Utils.notNull(perunSession, "perunSession");
getPerunBl().getVosManagerBl().checkVoExists(perunSession, vo);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "getAllResourcesTagsForVo_Vo_policy", vo)) {
throw new PrivilegeException(perunSession, "getAllResourcesTagsForVo");
//TODO: what about GROUPADMIN?
}
return resourcesManagerBl.getAllResourcesTagsForVo(perunSession, vo);
}
@Override
public List<ResourceTag> getAllResourcesTagsForResource(PerunSession perunSession, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.notNull(perunSession, "perunSession");
resourcesManagerBl.checkResourceExists(perunSession, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "getAllResourcesTagsForResource_Resource_policy", resource)) {
throw new PrivilegeException(perunSession, "getAllResourcesTagsForResource");
//TODO: What about GROUPADMIN?
}
return resourcesManagerBl.getAllResourcesTagsForResource(perunSession, resource);
}
@Override
public void copyAttributes(PerunSession sess, Resource sourceResource, Resource destinationResource) throws PrivilegeException, ResourceNotExistsException, WrongReferenceAttributeValueException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, sourceResource);
getResourcesManagerBl().checkResourceExists(sess, destinationResource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "copyAttributes_Resource_Resource_policy", sourceResource) ||
!AuthzResolver.authorizedInternal(sess, "copyAttributes_Resource_Resource_policy", destinationResource)) {
throw new PrivilegeException(sess, "copyAttributes");
}
getResourcesManagerBl().copyAttributes(sess, sourceResource, destinationResource);
}
@Override
public void copyServices(PerunSession sess, Resource sourceResource, Resource destinationResource) throws ResourceNotExistsException, PrivilegeException, WrongAttributeValueException, WrongReferenceAttributeValueException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, sourceResource);
getResourcesManagerBl().checkResourceExists(sess, destinationResource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "copyServices_Resource_Resource_policy", sourceResource) ||
!AuthzResolver.authorizedInternal(sess, "copyServices_Resource_Resource_policy", destinationResource)) {
throw new PrivilegeException(sess, "copyServices");
}
getResourcesManagerBl().copyServices(sess, sourceResource, destinationResource);
}
@Override
public void copyGroups(PerunSession sess, Resource sourceResource, Resource destinationResource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, sourceResource);
getResourcesManagerBl().checkResourceExists(sess, destinationResource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "copyGroups_Resource_Resource_policy", sourceResource) ||
!AuthzResolver.authorizedInternal(sess, "copyGroups_Resource_Resource_policy", destinationResource)) {
throw new PrivilegeException(sess, "copyGroups");
}
getResourcesManagerBl().copyGroups(sess, sourceResource, destinationResource);
}
@Override
public List<User> getAdmins(PerunSession perunSession, Resource resource, boolean onlyDirectAdmins) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(perunSession);
getResourcesManagerBl().checkResourceExists(perunSession, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "getAdmins_Resource_boolean_policy", resource)) {
throw new PrivilegeException(perunSession, "getAdmins");
}
return getResourcesManagerBl().getAdmins(perunSession, resource, onlyDirectAdmins);
}
@Override
public List<RichUser> getRichAdmins(PerunSession perunSession, Resource resource, List<String> specificAttributes, boolean allUserAttributes, boolean onlyDirectAdmins) throws UserNotExistsException, PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(perunSession);
getResourcesManagerBl().checkResourceExists(perunSession, resource);
if(!allUserAttributes) Utils.notNull(specificAttributes, "specificAttributes");
// Authorization
if (!AuthzResolver.authorizedInternal(perunSession, "getRichAdmins_Resource_List<String>_boolean_boolean_policy", resource)) {
throw new PrivilegeException(perunSession, "getRichAdmins");
}
return getPerunBl().getUsersManagerBl().filterOnlyAllowedAttributes(perunSession, getResourcesManagerBl().getRichAdmins(perunSession, resource, specificAttributes, allUserAttributes, onlyDirectAdmins));
}
@Override
public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, User user) throws UserNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getPerunBl().getUsersManagerBl().checkUserExists(sess, user);
// Authorization
if(!AuthzResolver.authorizedInternal(sess, "getResourcesWhereUserIsAdmin_User_policy", user)) {
throw new PrivilegeException(sess, "getResourcesWhereUserIsAdmin");
}
return getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, user);
}
@Override
public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, Facility facility, Vo vo, User authorizedUser) throws PrivilegeException, UserNotExistsException, FacilityNotExistsException, VoNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getFacilitiesManagerBl().checkFacilityExists(sess, facility);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
getPerunBl().getUsersManagerBl().checkUserExists(sess, authorizedUser);
//Authorization
if(!AuthzResolver.authorizedInternal(sess, "getResourcesWhereUserIsAdmin_Facility_Vo_User_policy", facility, vo, authorizedUser)){
throw new PrivilegeException(sess, "getResourcesByResourceManager");
}
List<Resource> resources = getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, facility, vo, authorizedUser);
resources.removeIf(resource -> !AuthzResolver.authorizedInternal(sess, "filter-getResourcesWhereUserIsAdmin_Facility_Vo_User_policy", Arrays.asList(vo, facility, resource, authorizedUser)));
return resources;
}
@Override
public List<Resource> getResourcesWhereUserIsAdmin(PerunSession sess, Vo vo, User authorizedUser) throws PrivilegeException, UserNotExistsException, VoNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
getPerunBl().getUsersManagerBl().checkUserExists(sess, authorizedUser);
//Authorization
if(!AuthzResolver.authorizedInternal(sess, "getResourcesWhereUserIsAdmin_Vo_User_policy", vo, authorizedUser)){
throw new PrivilegeException(sess, "getResourcesWhereUserIsAdmin");
}
List<Resource> resources = getResourcesManagerBl().getResourcesWhereUserIsAdmin(sess, vo, authorizedUser);
resources.removeIf(resource -> !AuthzResolver.authorizedInternal(sess, "filter-getResourcesWhereUserIsAdmin_Vo_User_policy", Arrays.asList(vo, resource, authorizedUser)));
return resources;
}
@Override
public List<Resource> getResourcesWhereGroupIsAdmin(PerunSession sess, Facility facility, Vo vo, Group authorizedGroup) throws PrivilegeException, GroupNotExistsException, FacilityNotExistsException, VoNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getFacilitiesManagerBl().checkFacilityExists(sess, facility);
getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, authorizedGroup);
//Authorization
if(!AuthzResolver.authorizedInternal(sess, "getResourcesWhereGroupIsAdmin_Facility_Vo_Group_policy", Arrays.asList(facility, vo)) &&
!AuthzResolver.authorizedInternal(sess, "authorizedGroup-getResourcesWhereGroupIsAdmin_Facility_Vo_Group_policy", authorizedGroup)){
throw new PrivilegeException(sess, "getResourcesByResourceManager");
}
List<Resource> resources = getResourcesManagerBl().getResourcesWhereGroupIsAdmin(sess, facility, vo, authorizedGroup);
resources.removeIf(resource -> !AuthzResolver.authorizedInternal(sess, "filter-getResourcesWhereGroupIsAdmin_Facility_Vo_Group_policy", Arrays.asList(vo, resource, facility)) &&
!AuthzResolver.authorizedInternal(sess, "filter_authorizedGroup-getResourcesWhereGroupIsAdmin_Facility_Vo_Group_policy", authorizedGroup));
return resources;
}
@Override
public List<Group> getAdminGroups(PerunSession sess, Resource resource) throws ResourceNotExistsException, PrivilegeException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getAdminGroups_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getAdminGroups");
}
return getResourcesManagerBl().getAdminGroups(sess, resource);
}
@Override
public void addAdmin(PerunSession sess, Resource resource, User user) throws UserNotExistsException, PrivilegeException, AlreadyAdminException, ResourceNotExistsException, RoleCannotBeManagedException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getUsersManagerBl().checkUserExists(sess, user);
AuthzResolver.setRole(sess, user, resource, Role.RESOURCEADMIN);
}
@Override
public void addAdmin(PerunSession sess, Resource resource, Group group) throws GroupNotExistsException, PrivilegeException, AlreadyAdminException, ResourceNotExistsException, RoleCannotBeManagedException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
AuthzResolver.setRole(sess, group, resource, Role.RESOURCEADMIN);
}
@Override
public void removeAdmin(PerunSession sess, Resource resource, User user) throws UserNotExistsException, PrivilegeException, UserNotAdminException, ResourceNotExistsException, RoleCannotBeManagedException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getUsersManagerBl().checkUserExists(sess, user);
AuthzResolver.unsetRole(sess, user, resource, Role.RESOURCEADMIN);
}
@Override
public void removeAdmin(PerunSession sess, Resource resource, Group group) throws GroupNotExistsException, PrivilegeException, GroupNotAdminException, ResourceNotExistsException, RoleCannotBeManagedException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
AuthzResolver.unsetRole(sess, group, resource, Role.RESOURCEADMIN);
}
@Override
public BanOnResource setBan(PerunSession sess, BanOnResource banOnResource) throws PrivilegeException, BanAlreadyExistsException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
Utils.notNull(banOnResource, "banOnResource");
Resource resource = getResourcesManagerBl().getResourceById(sess, banOnResource.getResourceId());
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "setBan_BanOnResource_policy", resource)) {
throw new PrivilegeException(sess, "setBan");
}
return getResourcesManagerBl().setBan(sess, banOnResource);
}
@Override
public BanOnResource getBanById(PerunSession sess, int banId) throws BanNotExistsException, PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
BanOnResource ban = getResourcesManagerBl().getBanById(sess, banId);
Resource resource = getResourcesManagerBl().getResourceById(sess, ban.getResourceId());
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "resource-getBanById_int_policy", Arrays.asList(resource, ban))) {
throw new PrivilegeException(sess, "getBanById");
}
return ban;
}
@Override
public BanOnResource getBan(PerunSession sess, int memberId, int resourceId) throws BanNotExistsException, PrivilegeException, MemberNotExistsException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
Member member = getPerunBl().getMembersManagerBl().getMemberById(sess, memberId);
Resource resource = getPerunBl().getResourcesManagerBl().getResourceById(sess, resourceId);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "resource-getBan_int_int_policy", Arrays.asList(member, resource))) {
throw new PrivilegeException(sess, "getBan");
}
return getResourcesManagerBl().getBan(sess, memberId, resourceId);
}
@Override
public List<BanOnResource> getBansForMember(PerunSession sess, int memberId) throws MemberNotExistsException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
Member member = getPerunBl().getMembersManagerBl().getMemberById(sess, memberId);
List<BanOnResource> usersBans = getResourcesManagerBl().getBansForMember(sess, memberId);
//Authorization
Iterator<BanOnResource> iterator = usersBans.iterator();
while(iterator.hasNext()) {
BanOnResource banForFiltering = iterator.next();
Resource resource = getResourcesManagerBl().getResourceById(sess, banForFiltering.getResourceId());
if(!AuthzResolver.authorizedInternal(sess, "getBansForMember_int_policy", Arrays.asList(banForFiltering, resource, member))) iterator.remove();
}
return usersBans;
}
@Override
public List<BanOnResource> getBansForResource(PerunSession sess, int resourceId) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
Resource resource = getPerunBl().getResourcesManagerBl().getResourceById(sess, resourceId);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getBansForResource_int_policy", resource)) {
throw new PrivilegeException(sess, "getBansForResource");
}
return getResourcesManagerBl().getBansForResource(sess, resourceId);
}
@Override
public BanOnResource updateBan(PerunSession sess, BanOnResource banOnResource) throws PrivilegeException, MemberNotExistsException, BanNotExistsException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
this.getResourcesManagerBl().checkBanExists(sess, banOnResource.getId());
Member member = getPerunBl().getMembersManagerBl().getMemberById(sess, banOnResource.getMemberId());
Resource resource = getPerunBl().getResourcesManagerBl().getResourceById(sess, banOnResource.getResourceId());
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "updateBan_BanOnResource_policy", Arrays.asList(banOnResource, member, resource))) {
throw new PrivilegeException(sess, "updateBan");
}
banOnResource = getResourcesManagerBl().updateBan(sess, banOnResource);
return banOnResource;
}
@Override
public void removeBan(PerunSession sess, int banId) throws PrivilegeException, BanNotExistsException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
BanOnResource ban = this.getResourcesManagerBl().getBanById(sess, banId);
Resource resource = getResourcesManagerBl().getResourceById(sess, ban.getResourceId());
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "resource-removeBan_int_policy", Arrays.asList(ban, resource))) {
throw new PrivilegeException(sess, "removeBan");
}
getResourcesManagerBl().removeBan(sess, banId);
}
@Override
public void removeBan(PerunSession sess, int memberId, int resourceId) throws BanNotExistsException, PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
BanOnResource ban = this.getResourcesManagerBl().getBan(sess, memberId, resourceId);
Resource resource = getResourcesManagerBl().getResourceById(sess, ban.getResourceId());
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "resource-removeBan_int_int_policy", Arrays.asList(ban, resource))) {
throw new PrivilegeException(sess, "removeBan");
}
getResourcesManagerBl().removeBan(sess, memberId, resourceId);
}
@Override
public void addResourceSelfServiceUser(PerunSession sess, Resource resource, User user) throws PrivilegeException, AlreadyAdminException, ResourceNotExistsException, UserNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getUsersManagerBl().checkUserExists(sess, user);
//Authorization
if (!AuthzResolver.authorizedInternal(sess, "addResourceSelfServiceUser_Resource_User_policy", Arrays.asList(resource, user))) {
throw new PrivilegeException(sess, "addResourceSelfServiceUser");
}
getResourcesManagerBl().addResourceSelfServiceUser(sess, resource, user);
}
@Override
public void addResourceSelfServiceGroup(PerunSession sess, Resource resource, Group group) throws PrivilegeException, AlreadyAdminException, ResourceNotExistsException, GroupNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
//Authorization
if (!AuthzResolver.authorizedInternal(sess, "addResourceSelfServiceGroup_Resource_Group_policy", resource) &&
!AuthzResolver.authorizedInternal(sess, "group-addResourceSelfServiceGroup_Resource_Group_policy", group)) {
throw new PrivilegeException(sess, "addResourceSelfServiceGroup");
}
getResourcesManagerBl().addResourceSelfServiceGroup(sess, resource, group);
}
@Override
public void removeResourceSelfServiceUser(PerunSession sess, Resource resource, User user) throws PrivilegeException, UserNotAdminException, ResourceNotExistsException, UserNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getUsersManagerBl().checkUserExists(sess, user);
//Authorization
if (!AuthzResolver.authorizedInternal(sess, "removeResourceSelfServiceUser_Resource_User_policy", Arrays.asList(resource, user))) {
throw new PrivilegeException(sess, "removeResourceSelfServiceUser");
}
getResourcesManagerBl().removeResourceSelfServiceUser(sess, resource, user);
}
@Override
public void removeResourceSelfServiceGroup(PerunSession sess, Resource resource, Group group) throws PrivilegeException, GroupNotAdminException, ResourceNotExistsException, GroupNotExistsException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
//Authorization
if (!AuthzResolver.authorizedInternal(sess, "removeResourceSelfServiceGroup_Resource_Group_policy", resource) &&
!AuthzResolver.authorizedInternal(sess, "group-removeResourceSelfServiceGroup_Resource_Group_policy", group)) {
throw new PrivilegeException(sess, "removeResourceSelfServiceGroup");
}
getResourcesManagerBl().removeResourceSelfServiceGroup(sess, resource, group);
}
@Override
public List<AssignedResource> getResourceAssignments(PerunSession sess, Group group, List<String> attrNames) throws PrivilegeException, GroupNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getResourceAssignments_Group_policy", group)) {
throw new PrivilegeException(sess, "getResourceAssignments");
}
List<AssignedResource> filteredResources = getResourcesManagerBl().getResourceAssignments(sess, group, attrNames).stream()
.filter(assignedResource -> AuthzResolver.authorizedInternal(sess,
"filter-getResourceAssignments_Group_policy",
assignedResource.getEnrichedResource().getResource(),
group))
.collect(Collectors.toList());
filteredResources.forEach(assignedResource ->
assignedResource.setEnrichedResource(getResourcesManagerBl().filterOnlyAllowedAttributes(sess, assignedResource.getEnrichedResource())));
return filteredResources;
}
@Override
public List<AssignedGroup> getGroupAssignments(PerunSession sess, Resource resource, List<String> attrNames) throws PrivilegeException, ResourceNotExistsException {
Utils.checkPerunSession(sess);
getPerunBl().getResourcesManagerBl().checkResourceExists(sess, resource);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "getGroupAssignments_Resource_policy", resource)) {
throw new PrivilegeException(sess, "getGroupAssignments");
}
List<AssignedGroup> filteredGroups = getResourcesManagerBl().getGroupAssignments(sess, resource, attrNames).stream()
.filter(assignedGroup -> AuthzResolver.authorizedInternal(sess,
"filter-getGroupAssignments_Resource_policy",
assignedGroup.getEnrichedGroup().getGroup(),
resource))
.collect(Collectors.toList());
filteredGroups.forEach(assignedGroup ->
assignedGroup.setEnrichedGroup(getPerunBl().getGroupsManagerBl().filterOnlyAllowedAttributes(sess, assignedGroup.getEnrichedGroup())));
return filteredGroups;
}
@Override
public void activateGroupResourceAssignment(PerunSession sess, Group group, Resource resource, boolean async) throws ResourceNotExistsException, GroupNotExistsException, PrivilegeException, WrongReferenceAttributeValueException, GroupNotDefinedOnResourceException, GroupResourceMismatchException, WrongAttributeValueException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "activateGroupResourceAssignment_Group_Resource_boolean_policy", group, resource)) {
throw new PrivilegeException(sess, "activateGroupResourceAssignment");
}
getResourcesManagerBl().activateGroupResourceAssignment(sess, group, resource, async);
}
@Override
public void deactivateGroupResourceAssignment(PerunSession sess, Group group, Resource resource) throws PrivilegeException, ResourceNotExistsException, GroupNotExistsException, GroupNotDefinedOnResourceException, GroupResourceStatusException {
Utils.checkPerunSession(sess);
getResourcesManagerBl().checkResourceExists(sess, resource);
getPerunBl().getGroupsManagerBl().checkGroupExists(sess, group);
// Authorization
if (!AuthzResolver.authorizedInternal(sess, "deactivateGroupResourceAssignment_Group_Resource_policy", group, resource)) {
throw new PrivilegeException(sess, "deactivateGroupResourceAssignment");
}
getResourcesManagerBl().deactivateGroupResourceAssignment(sess, group, resource);
}
/**
* Gets the resourcesManagerBl for this instance.
*
* @return The resourcesManagerBl.
*/
public ResourcesManagerBl getResourcesManagerBl() {
return this.resourcesManagerBl;
}
/**
* Sets the perunBl for this instance.
*
* @param perunBl The perunBl.
*/
public void setPerunBl(PerunBl perunBl)
{
this.perunBl = perunBl;
}
/**
* Sets the resourcesManagerBl for this instance.
*
* @param resourcesManagerBl The resourcesManagerBl.
*/
public void setResourcesManagerBl(ResourcesManagerBl resourcesManagerBl)
{
this.resourcesManagerBl = resourcesManagerBl;
}
public PerunBl getPerunBl() {
return this.perunBl;
}
}
|
package analysis.dynamicsim;
import gnu.trove.map.hash.TIntDoubleHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.hash.TIntHashSet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.xml.stream.XMLStreamException;
import main.Gui;
import main.util.MutableBoolean;
import odk.lang.FastMath;
public class SimulatorSSACR extends Simulator {
//allows for access to a group number from a reaction ID
private TObjectIntHashMap<String> reactionToGroupMap = null;
//allows for access to a group's min/max propensity from a group ID
private TIntDoubleHashMap groupToMaxValueMap = null;
//allows for access to the minimum/maximum possible propensity in the group from a group ID
private TIntDoubleHashMap groupToPropensityFloorMap = null;
private TIntDoubleHashMap groupToPropensityCeilingMap = null;
//allows for access to the reactionIDs in a group from a group ID
private ArrayList<HashSet<String> > groupToReactionSetList = null;
//allows for access to the group's total propensity from a group ID
private TIntDoubleHashMap groupToTotalGroupPropensityMap = null;
//stores group numbers that are nonempty
private TIntHashSet nonemptyGroupSet = null;
//number of groups including the empty groups and zero-propensity group
private int numGroups = 0;
private static Long initializationTime = new Long(0);
MutableBoolean eventsFlag = new MutableBoolean(false);
MutableBoolean rulesFlag = new MutableBoolean(false);
MutableBoolean constraintsFlag = new MutableBoolean(false);
public SimulatorSSACR(String SBMLFileName, String outputDirectory, double timeLimit,
double maxTimeStep, long randomSeed, JProgressBar progress, double printInterval,
double stoichAmpValue, JFrame running, String[] interestingSpecies, String quantityType)
throws IOException, XMLStreamException {
super(SBMLFileName, outputDirectory, timeLimit, maxTimeStep, randomSeed,
progress, printInterval, initializationTime, stoichAmpValue, running, interestingSpecies, quantityType);
try {
initialize(randomSeed, 1);
} catch (IOException e2) {
e2.printStackTrace();
} catch (XMLStreamException e2) {
e2.printStackTrace();
}
}
/**
* runs the composition and rejection simulation
*/
public void simulate() {
if (sbmlHasErrorsFlag == true)
return;
long initTime2 = System.nanoTime();
final boolean noEventsFlag = (Boolean) eventsFlag.getValue();
final boolean noAssignmentRulesFlag = (Boolean) rulesFlag.getValue();
final boolean noConstraintsFlag = (Boolean) constraintsFlag.getValue();
initializationTime += System.nanoTime() - initTime2;
long initTime3 = System.nanoTime() - initTime2;
//System.err.println("initialization time: " + initializationTime / 1e9f);
//SIMULATION LOOP
//simulate until the time limit is reached
long step1Time = 0;
long step2Time = 0;
long step3aTime = 0;
long step3bTime = 0;
long step4Time = 0;
long step5Time = 0;
long step6Time = 0;
TObjectIntHashMap<String> reactionToTimesFired = new TObjectIntHashMap<String>();
currentTime = 0.0;
double printTime = -0.00001;
//add events to queue if they trigger
if (noEventsFlag == false)
handleEvents(noAssignmentRulesFlag, noConstraintsFlag);
// for (String reactionID : reactionToPropensityMap.keySet())
// System.err.println(reactionID + " " + reactionToPropensityMap.get(reactionID));
while (currentTime < timeLimit && cancelFlag == false) {
//if a constraint fails
if (constraintFailureFlag == true) {
JOptionPane.showMessageDialog(Gui.frame, "Simulation Canceled Due To Constraint Failure",
"Constraint Failure", JOptionPane.ERROR_MESSAGE);
return;
}
//EVENT HANDLING
//trigger and/or fire events, etc.
if (noEventsFlag == false) {
HashSet<String> affectedReactionSet = fireEvents(noAssignmentRulesFlag, noConstraintsFlag);
//recalculate propensties/groups for affected reactions
if (affectedReactionSet.size() > 0) {
boolean newMinPropensityFlag = updatePropensities(affectedReactionSet);
if (newMinPropensityFlag == true)
reassignAllReactionsToGroups();
else
updateGroups(affectedReactionSet);
}
}
//prints the initial (time == 0) data
if (currentTime >= printTime) {
if (printTime < 0)
printTime = 0.0;
try {
printToTSD(printTime);
bufferedTSDWriter.write(",\n");
} catch (IOException e) {
e.printStackTrace();
}
printTime += printInterval;
}
//update progress bar
progress.setValue((int)((currentTime / timeLimit) * 100.0));
//STEP 1: generate random numbers
//long step1Initial = System.nanoTime();
double r1 = randomNumberGenerator.nextDouble();
double r2 = randomNumberGenerator.nextDouble();
double r3 = randomNumberGenerator.nextDouble();
double r4 = randomNumberGenerator.nextDouble();
//step1Time += System.nanoTime() - step1Initial;
//STEP 2: calculate delta_t, the time till the next reaction execution
//long step2Initial = System.nanoTime();
double delta_t = FastMath.log(1 / r1) / totalPropensity;
//step2Time += System.nanoTime() - step2Initial;
//STEP 3A: select a group
//long step3aInitial = System.nanoTime();
int selectedGroup = selectGroup(r2);
//this happens when there aren't any nonempty groups
if (selectedGroup == 0) {
currentTime = printTime + printInterval/2;
continue;
}
//step3aTime += System.nanoTime() - step3aInitial;
//STEP 3B: select a reaction within the group
//long step3bInitial = System.nanoTime();
String selectedReactionID = selectReaction(selectedGroup, r3, r4);
//step3bTime += System.nanoTime() - step3bInitial;
//System.err.println(selectedReactionID + " " + reactionToPropensityMap.get(selectedReactionID));
//STEP 4: perform selected reaction and update species counts
//long step4Initial = System.nanoTime();
performReaction(selectedReactionID, noAssignmentRulesFlag, noConstraintsFlag);
//step4Time += System.nanoTime() - step4Initial;
//STEP 5: compute affected reactions' new propensities and update total propensity
//long step5Initial = System.nanoTime();
//create a set (precludes duplicates) of reactions that the selected reaction's species affect
HashSet<String> affectedReactionSet = getAffectedReactionSet(selectedReactionID, noAssignmentRulesFlag);
boolean newMinPropensityFlag = updatePropensities(affectedReactionSet);
//step5Time += System.nanoTime() - step5Initial;
//STEP 6: re-assign affected reactions to appropriate groups
//long step6Initial = System.nanoTime();
//if there's a new minPropensity, then the group boundaries change
//so re-calculate all groups
if (newMinPropensityFlag == true)
reassignAllReactionsToGroups();
else
updateGroups(affectedReactionSet);
//step6Time += System.nanoTime() - step6Initial;
//update time for next iteration
currentTime += delta_t;
if (variableToIsInAssignmentRuleMap != null &&
variableToIsInAssignmentRuleMap.containsKey("time"))
performAssignmentRules(variableToAffectedAssignmentRuleSetMap.get("time"));
//add events to queue if they trigger
if (noEventsFlag == false) {
handleEvents(noAssignmentRulesFlag, noConstraintsFlag);
if (!triggeredEventQueue.isEmpty() && (triggeredEventQueue.peek().fireTime <= currentTime))
currentTime = triggeredEventQueue.peek().fireTime;
}
while ((currentTime > printTime) && (printTime < timeLimit)) {
try {
printToTSD(printTime);
bufferedTSDWriter.write(",\n");
} catch (IOException e) {
e.printStackTrace();
}
// for (String speciesID : speciesIDSet)
// if (speciesID.contains("ROW"))
// System.err.println(speciesID + " " + variableToValueMap.get(speciesID));
// System.err.println();
// System.err.println();
printTime += printInterval;
running.setTitle("Progress (" + (int)((currentTime / timeLimit) * 100.0) + "%)");
}
} //end simulation loop
// System.err.println("total time: " + String.valueOf((initializationTime + System.nanoTime() -
// initTime2 - initTime3) / 1e9f));
// System.err.println("total step 1 time: " + String.valueOf(step1Time / 1e9f));
// System.err.println("total step 2 time: " + String.valueOf(step2Time / 1e9f));
// System.err.println("total step 3a time: " + String.valueOf(step3aTime / 1e9f));
// System.err.println("total step 3b time: " + String.valueOf(step3bTime / 1e9f));
// System.err.println("total step 4 time: " + String.valueOf(step4Time / 1e9f));
// System.err.println("total step 5 time: " + String.valueOf(step5Time / 1e9f));
// System.err.println("total step 6 time: " + String.valueOf(step6Time / 1e9f));
if (cancelFlag == false) {
//print the final species counts
try {
printToTSD(printTime);
}
catch (IOException e) {
e.printStackTrace();
}
try {
bufferedTSDWriter.write(')');
bufferedTSDWriter.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
// System.err.println("grid " + diffCount);
// System.err.println((double) diffCount / (double) totalCount);
// System.err.println("membrane " + memCount);
// System.err.println((double) memCount / (double) totalCount);
// System.err.println("total " + totalCount);
}
/**
* initializes data structures local to the SSA-CR method
* calculates initial propensities and assigns reactions to groups
*
* @param noEventsFlag
* @param noAssignmentRulesFlag
* @param noConstraintsFlag
*
* @throws IOException
* @throws XMLStreamException
*/
private void initialize(long randomSeed, int runNumber)
throws IOException, XMLStreamException {
reactionToGroupMap = new TObjectIntHashMap<String>((int) (numReactions * 1.5));
groupToMaxValueMap = new TIntDoubleHashMap();
groupToPropensityFloorMap = new TIntDoubleHashMap();
groupToPropensityCeilingMap = new TIntDoubleHashMap();
groupToReactionSetList = new ArrayList<HashSet<String> >();
groupToTotalGroupPropensityMap = new TIntDoubleHashMap();
nonemptyGroupSet = new TIntHashSet();
eventsFlag = new MutableBoolean(false);
rulesFlag = new MutableBoolean(false);
constraintsFlag = new MutableBoolean(false);
setupArrays();
setupSpecies();
setupParameters();
setupInitialAssignments();
setupRules();
setupConstraints();
if (numEvents == 0)
eventsFlag.setValue(true);
else
eventsFlag.setValue(false);
if (numAssignmentRules == 0)
rulesFlag.setValue(true);
else
rulesFlag.setValue(false);
if (numConstraints == 0)
constraintsFlag.setValue(true);
else
constraintsFlag.setValue(false);
//STEP 0A: calculate initial propensities (including the total)
setupReactions();
//STEP OB: create and populate initial groups
createAndPopulateInitialGroups();
setupEvents();
setupForOutput(randomSeed, runNumber);
if (dynamicBoolean == true) {
setupGrid();
createModelCopy();
}
HashSet<String> comps = new HashSet<String>();
comps.addAll(componentToLocationMap.keySet());
bufferedTSDWriter.write("(" + "\"" + "time" + "\"");
//if there's an interesting species, only those get printed
if (interestingSpecies.size() > 0) {
for (String speciesID : interestingSpecies)
bufferedTSDWriter.write(", \"" + speciesID + "\"");
}
else {
for (String speciesID : speciesIDSet) {
bufferedTSDWriter.write(", \"" + speciesID + "\"");
}
if (dynamicBoolean == true) {
//print compartment location IDs
for (String componentLocationID : componentToLocationMap.keySet()) {
String locationX = componentLocationID + "__locationX";
String locationY = componentLocationID + "__locationY";
bufferedTSDWriter.write(", \"" + locationX + "\", \"" + locationY + "\"");
}
}
//print compartment IDs (for sizes)
for (String componentID : compartmentIDSet) {
bufferedTSDWriter.write(", \"" + componentID + "\"");
}
//print nonconstant parameter IDs
for (String parameterID : nonconstantParameterIDSet) {
try {
bufferedTSDWriter.write(", \"" + parameterID + "\"");
} catch (IOException e) {
e.printStackTrace();
}
}
}
bufferedTSDWriter.write("),\n");
// for (String reactionID : reactionToPropensityMap.keySet()) {
// if (reactionToPropensityMap.get(reactionID) > 0) {
// System.err.println("ID: " + reactionID);
// System.err.println("formula " + reactionToFormulaMap.get(reactionID).toFormula());
// System.err.println("propensity " + reactionToPropensityMap.get(reactionID));
// System.err.println();
// System.err.println();
// for (String variableID : variableToValueMap.keySet()) {
// System.err.println("id " + variableID);
// System.err.println("value " + variableToValueMap.get(variableID));
// System.err.println();
// System.err.println();
}
/**
* creates the appropriate number of groups and associates reactions with groups
*/
private void createAndPopulateInitialGroups() {
//create groups
int currentGroup = 1;
double groupPropensityCeiling = 2 * minPropensity;
groupToPropensityFloorMap.put(1, minPropensity);
while (groupPropensityCeiling < maxPropensity) {
groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling);
groupToPropensityFloorMap.put(currentGroup + 1, groupPropensityCeiling);
groupToMaxValueMap.put(currentGroup, 0.0);
groupPropensityCeiling *= 2;
++currentGroup;
}
//if there are no non-zero groups
if (minPropensity == 0) {
numGroups = 1;
groupToReactionSetList.add(new HashSet<String>(500));
}
else {
numGroups = currentGroup + 1;
groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling);
groupToMaxValueMap.put(currentGroup, 0.0);
//start at 0 to make a group for zero propensities
for (int groupNum = 0; groupNum < numGroups; ++groupNum) {
groupToReactionSetList.add(new HashSet<String>(500));
groupToTotalGroupPropensityMap.put(groupNum, 0.0);
}
}
//assign reactions to groups
for (String reaction : reactionToPropensityMap.keySet()) {
double propensity = reactionToPropensityMap.get(reaction);
org.openmali.FastMath.FRExpResultf frexpResult = org.openmali.FastMath.frexp((float) (propensity / minPropensity));
int group = frexpResult.exponent;
groupToTotalGroupPropensityMap.adjustValue(group, propensity);
groupToReactionSetList.get(group).add(reaction);
reactionToGroupMap.put(reaction, group);
if (propensity > groupToMaxValueMap.get(group))
groupToMaxValueMap.put(group, propensity);
}
//find out which (if any) groups are empty
//this is done so that empty groups are never chosen during simulation
for (int groupNum = 1; groupNum < numGroups; ++groupNum) {
if (groupToReactionSetList.get(groupNum).isEmpty())
continue;
nonemptyGroupSet.add(groupNum);
}
}
/**
* cancels the current run
*/
protected void cancel() {
cancelFlag = true;
}
/**
* clears data structures for new run
*/
protected void clear() {
variableToValueMap.clear();
reactionToPropensityMap.clear();
if (numEvents > 0) {
triggeredEventQueue.clear();
untriggeredEventSet.clear();
eventToPriorityMap.clear();
eventToDelayMap.clear();
}
reactionToGroupMap.clear();
reactionToFormulaMap.clear();
groupToMaxValueMap.clear();
groupToPropensityFloorMap.clear();
groupToPropensityCeilingMap.clear();
groupToReactionSetList.clear();
groupToTotalGroupPropensityMap.clear();
nonemptyGroupSet.clear();
speciesIDSet.clear();
componentToLocationMap.clear();
componentToReactionSetMap.clear();
componentToVariableSetMap.clear();
componentToEventSetMap.clear();
compartmentIDSet.clear();
nonconstantParameterIDSet.clear();
minRow = Integer.MAX_VALUE;
minCol = Integer.MAX_VALUE;
maxRow = Integer.MIN_VALUE;
maxCol = Integer.MIN_VALUE;
//get rid of things that were created dynamically this run
//or else dynamically created stuff will still be in the model next run
if (dynamicBoolean == true) {
resetModel();
}
}
/**
* removes a component's reactions from reactionToGroupMap and groupToReactionSetList
*/
protected void eraseComponentFurther(HashSet<String> reactionIDs) {
for (String reactionID : reactionIDs) {
int group = reactionToGroupMap.get(reactionID);
reactionToGroupMap.remove(reactionID);
groupToReactionSetList.get(group).remove(reactionID);
}
}
/**
* assigns all reactions to (possibly new) groups
* this is called when the minPropensity changes, which
* changes the groups' floor/ceiling propensity values
*/
private void reassignAllReactionsToGroups() {
int currentGroup = 1;
double groupPropensityCeiling = 2 * minPropensity;
//re-calulate and store group propensity floors/ceilings
groupToPropensityCeilingMap.clear();
groupToPropensityFloorMap.clear();
groupToPropensityFloorMap.put(1, minPropensity);
while (groupPropensityCeiling <= maxPropensity) {
groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling);
groupToPropensityFloorMap.put(currentGroup + 1, groupPropensityCeiling);
groupPropensityCeiling *= 2;
++currentGroup;
}
groupToPropensityCeilingMap.put(currentGroup, groupPropensityCeiling);
int newNumGroups = currentGroup + 1;
//allocate memory if the number of groups expands
if (newNumGroups > numGroups) {
for (int groupNum = numGroups; groupNum < newNumGroups; ++groupNum)
groupToReactionSetList.add(new HashSet<String>(500));
}
//clear the reaction set for each group
//start at 1, as the zero propensity group isn't going to change
for (int groupNum = 1; groupNum < newNumGroups; ++groupNum) {
groupToReactionSetList.get(groupNum).clear();
groupToMaxValueMap.put(groupNum, 0.0);
groupToTotalGroupPropensityMap.put(groupNum, 0.0);
}
numGroups = newNumGroups;
totalPropensity = 0;
//assign reactions to groups
for (String reaction : reactionToPropensityMap.keySet()) {
double propensity = reactionToPropensityMap.get(reaction);
totalPropensity += propensity;
//the zero-propensity group doesn't need altering
if (propensity == 0.0) continue;
org.openmali.FastMath.FRExpResultf frexpResult = org.openmali.FastMath.frexp((float) (propensity / minPropensity));
int group = frexpResult.exponent;
groupToReactionSetList.get(group).add(reaction);
reactionToGroupMap.put(reaction, group);
groupToTotalGroupPropensityMap.adjustValue(group, propensity);
if (propensity > groupToMaxValueMap.get(group))
groupToMaxValueMap.put(group, propensity);
}
//find out which (if any) groups are empty
//this is done so that empty groups are never chosen during simulation
nonemptyGroupSet.clear();
for (int groupNum = 1; groupNum < numGroups; ++groupNum) {
if (groupToReactionSetList.get(groupNum).isEmpty())
continue;
nonemptyGroupSet.add(groupNum);
}
}
/**
* chooses a random number between 0 and the total propensity
* then it finds which nonempty group this number belongs to
*
* @param r2 random number
* @return the group selected
*/
private int selectGroup(double r2) {
if (nonemptyGroupSet.size() == 0)
return 0;
double randomPropensity = r2 * (totalPropensity);
double runningTotalGroupsPropensity = 0.0;
int selectedGroup = 1;
//finds the group that the random propensity lies in
//it keeps adding the next group's total propensity to a running total
//until the running total is greater than the random propensity
for (; selectedGroup < numGroups; ++selectedGroup) {
runningTotalGroupsPropensity += groupToTotalGroupPropensityMap.get(selectedGroup);
if (randomPropensity < runningTotalGroupsPropensity && nonemptyGroupSet.contains(selectedGroup))
break;
}
return selectedGroup;
}
/**
* from the selected group, a reaction is chosen randomly/uniformly
* a random number between 0 and the group's max propensity is then chosen
* if this number is not less than the chosen reaction's propensity,
* the reaction is rejected and the process is repeated until success occurs
*
* @param selectedGroup the group to choose a reaction from
* @param r3
* @param r4
* @return the chosen reaction's ID
*/
private String selectReaction(int selectedGroup, double r3, double r4) {
HashSet<String> reactionSet = groupToReactionSetList.get(selectedGroup);
double randomIndex = FastMath.floor(r3 * reactionSet.size());
int indexIter = 0;
Iterator<String> reactionSetIterator = reactionSet.iterator();
while (reactionSetIterator.hasNext() && indexIter < randomIndex) {
reactionSetIterator.next();
++indexIter;
}
String selectedReactionID = reactionSetIterator.next();
double reactionPropensity = reactionToPropensityMap.get(selectedReactionID);
//this is choosing a value between 0 and the max propensity in the group
double randomPropensity = r4 * groupToMaxValueMap.get(selectedGroup);
//loop until there's no reaction rejection
//if the random propensity is higher than the selected reaction's propensity, another random reaction is chosen
while (randomPropensity > reactionPropensity) {
r3 = randomNumberGenerator.nextDouble();
r4 = randomNumberGenerator.nextDouble();
randomIndex = (int) FastMath.floor(r3 * reactionSet.size());
indexIter = 0;
reactionSetIterator = reactionSet.iterator();
while (reactionSetIterator.hasNext() && (indexIter < randomIndex)) {
reactionSetIterator.next();
++indexIter;
}
selectedReactionID = reactionSetIterator.next();
reactionPropensity = reactionToPropensityMap.get(selectedReactionID);
randomPropensity = r4 * groupToMaxValueMap.get(selectedGroup);
}
return selectedReactionID;
}
/**
* does a minimized initialization process to prepare for a new run
*/
protected void setupForNewRun(int newRun) {
try {
setupSpecies();
} catch (IOException e) {
e.printStackTrace();
}
setupInitialAssignments();
setupParameters();
setupRules();
setupConstraints();
totalPropensity = 0.0;
numGroups = 0;
minPropensity = Double.MAX_VALUE;
maxPropensity = Double.MIN_VALUE;
if (numEvents == 0)
eventsFlag.setValue(true);
else
eventsFlag.setValue(false);
if (numAssignmentRules == 0)
rulesFlag.setValue(true);
else
rulesFlag.setValue(false);
if (numConstraints == 0)
constraintsFlag.setValue(true);
else
constraintsFlag.setValue(false);
//STEP 0A: calculate initial propensities (including the total)
setupReactions();
//STEP OB: create and populate initial groups
createAndPopulateInitialGroups();
setupEvents();
setupForOutput(0, newRun);
if (dynamicBoolean == true) {
setupGrid();
//print compartment location IDs
for (String componentLocationID : componentToLocationMap.keySet()) {
String locationX = componentLocationID + "__locationX";
String locationY = componentLocationID + "__locationY";
try {
bufferedTSDWriter.write(", \"" + locationX + "\", \"" + locationY + "\"");
} catch (IOException e) {
e.printStackTrace();
}
}
//print compartment IDs (for sizes)
for (String componentID : compartmentIDSet) {
try {
bufferedTSDWriter.write(", \"" + componentID + "\"");
} catch (IOException e) {
e.printStackTrace();
}
}
//print nonconstant parameter IDs
for (String parameterID : nonconstantParameterIDSet) {
try {
bufferedTSDWriter.write(", \"" + parameterID + "\"");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
bufferedTSDWriter.write("),\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* updates the groups
*/
protected void updateAfterDynamicChanges() {
reassignAllReactionsToGroups();
}
/**
* updates the groups of the reactions affected by the recently performed reaction
* ReassignAllReactionsToGroups() is called instead when all reactions need changing
*
* @param affectedReactionSet the set of reactions affected by the recently performed reaction
*/
private void updateGroups(HashSet<String> affectedReactionSet) {
//update the groups for all of the affected reactions
//their propensities have changed and they may need to go into a different group
for (String affectedReactionID : affectedReactionSet) {
double newPropensity = reactionToPropensityMap.get(affectedReactionID);
int oldGroup = reactionToGroupMap.get(affectedReactionID);
if (newPropensity == 0.0) {
HashSet<String> oldReactionSet = groupToReactionSetList.get(oldGroup);
//update group collections
//zero propensities go into group 0
oldReactionSet.remove(affectedReactionID);
reactionToGroupMap.put(affectedReactionID, 0);
groupToReactionSetList.get(0).add(affectedReactionID);
if (oldReactionSet.size() == 0)
nonemptyGroupSet.remove(oldGroup);
}
//if the new propensity != 0.0 (ie, new group != 0)
else {
//if it's outside of the old group's boundaries
if (newPropensity > groupToPropensityCeilingMap.get(oldGroup) ||
newPropensity < groupToPropensityFloorMap.get(oldGroup)) {
org.openmali.FastMath.FRExpResultf frexpResult = org.openmali.FastMath.frexp((float) (newPropensity / minPropensity));
int group = frexpResult.exponent;
//if the group is one that currently exists
if (group < numGroups) {
HashSet<String> newGroupReactionSet = groupToReactionSetList.get(group);
HashSet<String> oldGroupReactionSet = groupToReactionSetList.get(oldGroup);
//update group collections
oldGroupReactionSet.remove(affectedReactionID);
reactionToGroupMap.put(affectedReactionID, group);
newGroupReactionSet.add(affectedReactionID);
groupToTotalGroupPropensityMap.adjustValue(group, newPropensity);
//if the group that the reaction was just added to is now nonempty
if (newGroupReactionSet.size() == 1)
nonemptyGroupSet.add(group);
if (oldGroupReactionSet.size() == 0)
nonemptyGroupSet.remove(oldGroup);
if (newPropensity > groupToMaxValueMap.get(group))
groupToMaxValueMap.put(group, newPropensity);
}
//this means the propensity goes into a group that doesn't currently exist
else {
//groupToReactionSetList is a list, so the group needs to be the index
for (int iter = numGroups; iter <= group; ++iter) {
if (iter >= groupToReactionSetList.size())
groupToReactionSetList.add(new HashSet<String>(500));
groupToTotalGroupPropensityMap.put(iter, 0.0);
}
numGroups = group + 1;
HashSet<String> oldReactionSet = groupToReactionSetList.get(oldGroup);
//update group collections
groupToTotalGroupPropensityMap.adjustValue(group, newPropensity);
groupToReactionSetList.get(oldGroup).remove(affectedReactionID);
reactionToGroupMap.put(affectedReactionID, group);
groupToReactionSetList.get(group).add(affectedReactionID);
nonemptyGroupSet.add(group);
groupToMaxValueMap.put(group, newPropensity);
if (oldReactionSet.size() == 0)
nonemptyGroupSet.remove(oldGroup);
}
}
//if it's within the old group's boundaries (ie, group isn't changing)
else {
//maintain current group
if (newPropensity > groupToMaxValueMap.get(oldGroup))
groupToMaxValueMap.put(oldGroup, newPropensity);
groupToTotalGroupPropensityMap.adjustValue(oldGroup, newPropensity);
}
}
}
}
/**
* updates the propensities of the reactions affected by the recently performed reaction
* @param affectedReactionSet the set of reactions affected by the recently performed reaction
* @return whether or not there's a new minPropensity (if there is, all reaction's groups need to change)
*/
private boolean updatePropensities(HashSet<String> affectedReactionSet) {
boolean newMinPropensityFlag = false;
//loop through the affected reactions and update the propensities
for (String affectedReactionID : affectedReactionSet) {
boolean notEnoughMoleculesFlag = false;
HashSet<StringDoublePair> reactantStoichiometrySet =
reactionToReactantStoichiometrySetMap.get(affectedReactionID);
if (reactantStoichiometrySet == null)
continue;
//check for enough molecules for the reaction to occur
for (StringDoublePair speciesAndStoichiometry : reactantStoichiometrySet) {
String speciesID = speciesAndStoichiometry.string;
double stoichiometry = speciesAndStoichiometry.doub;
//if there aren't enough molecules to satisfy the stoichiometry
if (variableToValueMap.get(speciesID) < stoichiometry) {
notEnoughMoleculesFlag = true;
break;
}
}
double newPropensity = 0.0;
if (notEnoughMoleculesFlag == false)
newPropensity = evaluateExpressionRecursive(reactionToFormulaMap.get(affectedReactionID));
//stoichiometry amplification -- alter the propensity
if (affectedReactionID.contains("_Diffusion_") && stoichAmpBoolean == true)
newPropensity *= (1.0 / stoichAmpGridValue);
if (newPropensity > 0.0 && newPropensity < minPropensity) {
minPropensity = newPropensity;
newMinPropensityFlag = true;
}
if (newPropensity > maxPropensity)
maxPropensity = newPropensity;
double oldPropensity = reactionToPropensityMap.get(affectedReactionID);
int oldGroup = reactionToGroupMap.get(affectedReactionID);
//remove the old propensity from the group's total
//later on, the new propensity is added to the (possibly new) group's total
groupToTotalGroupPropensityMap.adjustValue(oldGroup, -oldPropensity);
//add the difference of new v. old propensity to the total propensity
totalPropensity += newPropensity - oldPropensity;
reactionToPropensityMap.put(affectedReactionID, newPropensity);
}
return newMinPropensityFlag;
}
}
|
package items;
import com.jogamp.opengl.util.texture.Texture;
import game.Building;
import game.PlayerMotion;
import game.PlayerStats;
import inventory.Bag;
import inventory.Item;
import inventory.PlayerAttributes;
import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;
public class SpeedBox implements Item {
private Texture textureItem;
private float itemX, itemY, itemZ;
private float playerX, playerY, playerZ;
private float angle, y_angle;
private boolean grabbed;
private double T;
private Bag bag;
private static PlayerAttributes p;
private int frames;
public SpeedBox(GL2 gl, GLU glu, float x, float y, float z, Bag bag,
PlayerAttributes p) {
textureItem = Building.setupTexture(gl, "textureItem.png");
this.itemX = x;
this.itemY = y;
this.itemZ = z;
PlayerMotion.registerPlayerWatcher(this);
this.bag = bag;
SpeedBox.p = p;
grabbed = false;
frames = 0;
}
public SpeedBox() {
// dummy constructor for DummyItem
}
public void draw(GL2 gl, GLU glu) {
frames++;
T = T + 0.05;
if (grabConditions()) {
grabbed = true;
bag.addItem(this);
}
if (!grabbed) {
drawItem(gl, glu);
}
}
private boolean grabConditions() {
if ((itemX - 3 < playerX && itemZ - 3 < playerZ)
&& (itemX + 5 > playerX) && (itemZ + 5 > playerZ)
&& (grabbed == false))
return true;
else
return false;
}
public boolean grabbed() {
return grabbed;
}
public double getLocationX() {
return itemX;
}
public double getLocationY() {
return itemY;
}
public double getLocationZ() {
return itemZ;
}
public void SetLocation(int x, int y, int z) {
this.itemX = x;
this.itemY = y;
this.itemZ = z;
}
public void setAngle(int angle) {
this.angle = angle;
}
public double getAngle() {
return angle;
}
public void use() {
float currentSpeed = p.getStepSize();
int duration = 130;
// calls PlayerAttributes
p.setStepSize(currentSpeed + 1.5f, duration);
}
public String getType() {
return "Speed";
}
public void drawItem(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
gl.glPushMatrix();
gl.glTranslated(itemX, Math.sin(Math.toRadians(T * 360 + 180)) + 2,
itemZ);
// gl.glRotated(Math.toRadians(15*frames), Math.toRadians(15*frames),
// Math.toRadians(15*frames), 1);
// gl.glTranslated(-itemX, -(Math.sin(Math.toRadians(T*360+180 ))+2),
// -itemZ);
gl.glRotated(5*T,1,5*T,1);
textureItem.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(-2.5f, 0, 0);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 0, 0);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(2.5f, 5, 0);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 5, 0);
gl.glEnd();
gl.glBegin(GL2.GL_QUADS);
// cw as viewed from front, so can be seen as ccw from back
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(-2.5f, 0, 0);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 5, 0);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(2.5f, 5, 0);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 0, 0);
gl.glEnd();
// backwall
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(-2.5f, 0, -5);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 0, -5);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(2.5f, 5, -5);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 5, -5);
gl.glEnd();
gl.glBegin(GL2.GL_QUADS);// good side of quesiton mark
// cw as viewed from front, so can be seen as ccw from back
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 0, -5);
gl.glTexCoord2f(0f, 1f);
gl.glVertex3f(-2.5f, 5, -5);
gl.glTexCoord2f(1f, 1f);
gl.glVertex3f(2.5f, 5, -5);
gl.glTexCoord2f(1f, 0f);
gl.glVertex3f(2.5f, 0, -5);
gl.glEnd();
// leftwall
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(-2.5f, 0, 0);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(-2.5f, 5, 0);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(-2.5f, 5, -5);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 0, -5);
gl.glEnd();
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(-2.5f, 0, 0);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 0, -5);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(-2.5f, 5, -5);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(-2.5f, 5, 0);
gl.glEnd();
// Rightwall
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(2.5f, 0, 0);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 5, 0);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(2.5f, 5, -5);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(2.5f, 0, -5);
gl.glEnd();
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(2.5f, 0, 0);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(2.5f, 0, -5);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(2.5f, 5, -5);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 5, 0);
gl.glEnd();
// floor
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(2.5f, 0, 0);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 0, -5);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(-2.5f, 0, -5);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 0, 0);
gl.glEnd();
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(2.5f, 0, 0);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 0, 0);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(-2.5f, 0, -5);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 0, -5);
gl.glEnd();
// ceiling
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(2.5f, 5, 0);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 5, -5);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(-2.5f, 5, -5);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(-2.5f, 5, 0);
gl.glEnd();
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 2f);
gl.glVertex3f(2.5f, 5, 0);
gl.glTexCoord2f(0f, 0f);
gl.glVertex3f(0f, 5, 0);
gl.glTexCoord2f(3f, 0f);
gl.glVertex3f(0f, 5, -5);
gl.glTexCoord2f(3f, 2f);
gl.glVertex3f(2.5f, 5, -5);
gl.glEnd();
gl.glPopMatrix();
gl.glDisable(GL2.GL_CULL_FACE);
gl.glDisable(GL2.GL_TEXTURE_2D);
}
@Override
public void playerMoved(float x, float y, float z, float angle, float y_angle,PlayerStats s) {
// GET CURRENT POSITION OF PLAYER
this.playerX = x;
this.playerY = y;
this.playerZ = z;
this.angle = angle;
}
@Override
public void draw(GL2 gl, GLU glu, float x, float y, float z) {
// TODO Auto-generated method stub
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Flattener {
@SuppressWarnings("unchecked")
public List<Object> flatten(List<Object> list) {
return (List<Object>) list.stream()
.filter(Objects::nonNull)
.reduce(new ArrayList<>(), (previousAccumulatedElem, currentElem) -> accumulate((List<Object>) previousAccumulatedElem, currentElem));
}
@SuppressWarnings("unchecked")
private List<Object> accumulate(List<Object> previousAccumulatedElem, Object currentElem) {
if (currentElem instanceof List) {
previousAccumulatedElem.addAll(flatten((List<Object>) currentElem));
} else {
previousAccumulatedElem.add(currentElem);
}
return previousAccumulatedElem;
}
}
|
/*
* $Log: SoapWrapperPipe.java,v $
* Revision 1.7 2012-02-28 13:26:56 europe\m168309
* added soapNamespace attribute
*
* Revision 1.6 2011/12/23 16:02:40 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added soapBodyStyleSheet attribute
*
* Revision 1.5 2011/12/15 10:52:11 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added soapHeaderStyleSheet, removeOutputNamespaces and outputNamespace attribute
*
* Revision 1.4 2011/11/30 13:52:00 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* adjusted/reversed "Upgraded from WebSphere v5.1 to WebSphere v6.1"
*
* Revision 1.1 2011/10/19 14:49:53 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* Upgraded from WebSphere v5.1 to WebSphere v6.1
*
* Revision 1.2 2011/09/23 11:33:25 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* added attributes encodingStyle and serviceNamespace
*
* Revision 1.1 2011/09/14 14:14:01 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org>
* first version
*
*
*/
package nl.nn.adapterframework.soap;
import java.io.IOException;
import java.util.Map;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.commons.lang.StringUtils;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.PipeLineSession;
import nl.nn.adapterframework.core.PipeRunException;
import nl.nn.adapterframework.core.PipeRunResult;
import nl.nn.adapterframework.core.PipeStartException;
import nl.nn.adapterframework.parameters.ParameterResolutionContext;
import nl.nn.adapterframework.pipes.FixedForwardPipe;
import nl.nn.adapterframework.util.DomBuilderException;
import nl.nn.adapterframework.util.TransformerPool;
import nl.nn.adapterframework.util.XmlUtils;
public class SoapWrapperPipe extends FixedForwardPipe {
private String direction = "wrap";
private String soapHeaderSessionKey = null;
private String encodingStyle = null;
private String serviceNamespace = null;
private String soapHeaderStyleSheet = null;
private String soapBodyStyleSheet = null;
private boolean removeOutputNamespaces = false;
private String outputNamespace = null;
private String soapNamespace = null;
private SoapWrapper soapWrapper = null;
private TransformerPool soapHeaderTp = null;
private TransformerPool soapBodyTp = null;
private TransformerPool removeOutputNamespacesTp = null;
private TransformerPool outputNamespaceTp = null;
public void configure() throws ConfigurationException {
super.configure();
soapWrapper = SoapWrapper.getInstance();
if (StringUtils.isNotEmpty(getSoapHeaderStyleSheet())) {
soapHeaderTp = TransformerPool.configureTransformer0(getLogPrefix(null), null, null, getSoapHeaderStyleSheet(), "xml", false, getParameterList(), true);
}
if (StringUtils.isNotEmpty(getSoapBodyStyleSheet())) {
soapBodyTp = TransformerPool.configureTransformer0(getLogPrefix(null), null, null, getSoapBodyStyleSheet(), "xml", false, getParameterList(), true);
}
try {
if (isRemoveOutputNamespaces()) {
String removeOutputNamespaces_xslt = XmlUtils.makeRemoveNamespacesXslt(true, false);
removeOutputNamespacesTp = new TransformerPool(removeOutputNamespaces_xslt);
}
if (StringUtils.isNotEmpty(getOutputNamespace())) {
String outputNamespace_xslt = XmlUtils.makeAddRootNamespaceXslt(getOutputNamespace(), true, false);
outputNamespaceTp = new TransformerPool(outputNamespace_xslt);
}
} catch (TransformerConfigurationException e) {
throw new ConfigurationException(getLogPrefix(null) + "cannot create transformer", e);
}
}
public void start() throws PipeStartException {
super.start();
if (soapHeaderTp != null) {
try {
soapHeaderTp.open();
} catch (Exception e) {
throw new PipeStartException(getLogPrefix(null)+"cannot start SOAP Header TransformerPool", e);
}
}
if (soapBodyTp != null) {
try {
soapBodyTp.open();
} catch (Exception e) {
throw new PipeStartException(getLogPrefix(null)+"cannot start SOAP Body TransformerPool", e);
}
}
if (removeOutputNamespacesTp != null) {
try {
removeOutputNamespacesTp.open();
} catch (Exception e) {
throw new PipeStartException(getLogPrefix(null)+"cannot start Remove Output Namespaces TransformerPool", e);
}
}
if (outputNamespaceTp != null) {
try {
outputNamespaceTp.open();
} catch (Exception e) {
throw new PipeStartException(getLogPrefix(null)+"cannot start Output Namespace TransformerPool", e);
}
}
}
public void stop() {
super.stop();
if (soapHeaderTp != null) {
soapHeaderTp.close();
}
if (soapBodyTp != null) {
soapBodyTp.close();
}
if (removeOutputNamespacesTp != null) {
removeOutputNamespacesTp.close();
}
if (outputNamespaceTp != null) {
outputNamespaceTp.close();
}
}
public PipeRunResult doPipe(Object input, PipeLineSession session) throws PipeRunException {
String result;
try {
if ("wrap".equalsIgnoreCase(getDirection())) {
String soapHeader = null;
if (soapHeaderTp != null) {
ParameterResolutionContext prc = new ParameterResolutionContext("<dummy/>", session);
Map parameterValues = null;
if (getParameterList()!=null) {
parameterValues = prc.getValueMap(getParameterList());
}
soapHeader = soapHeaderTp.transform(prc.getInputSource(), parameterValues);
} else {
if (StringUtils.isNotEmpty(getSoapHeaderSessionKey())) {
soapHeader = (String) session.get(getSoapHeaderSessionKey());
}
}
String payload;
if (outputNamespaceTp != null) {
payload = outputNamespaceTp.transform(input.toString(), null, true);
} else {
payload = input.toString();
}
if (soapBodyTp != null) {
ParameterResolutionContext prc = new ParameterResolutionContext(payload, session);
Map parameterValues = null;
if (getParameterList()!=null) {
parameterValues = prc.getValueMap(getParameterList());
}
payload = soapBodyTp.transform(prc.getInputSource(), parameterValues);
}
result = wrapMessage(payload, soapHeader);
} else {
result = unwrapMessage(input.toString());
if (StringUtils.isEmpty(result)) {
throw new PipeRunException(this, getLogPrefix(session) + "SOAP Body is empty or message is not a SOAP Message");
}
if (soapWrapper.getFaultCount(input.toString()) > 0) {
throw new PipeRunException(this, getLogPrefix(session) + "SOAP Body contains SOAP Fault");
}
if (StringUtils.isNotEmpty(getSoapHeaderSessionKey())) {
String soapHeader = soapWrapper.getHeader(input.toString());
session.put(getSoapHeaderSessionKey(), soapHeader);
}
if (removeOutputNamespacesTp != null) {
result = removeOutputNamespacesTp.transform(result, null, true);
}
}
} catch (Throwable t) {
throw new PipeRunException(this, getLogPrefix(session) + " Unexpected exception during (un)wrapping ", t);
}
return new PipeRunResult(getForward(), result);
}
protected String unwrapMessage(String messageText) throws DomBuilderException, TransformerException, IOException {
return soapWrapper.getBody(messageText);
}
protected String wrapMessage(String message, String soapHeader) throws DomBuilderException, TransformerException, IOException {
return soapWrapper.putInEnvelope(message, getEncodingStyle(), getServiceNamespace(), soapHeader, null, getSoapNamespace());
}
public String getDirection() {
return direction;
}
public void setDirection(String string) {
direction = string;
}
public void setSoapHeaderSessionKey(String string) {
soapHeaderSessionKey = string;
}
public String getSoapHeaderSessionKey() {
return soapHeaderSessionKey;
}
public void setEncodingStyle(String string) {
encodingStyle = string;
}
public String getEncodingStyle() {
return encodingStyle;
}
public void setServiceNamespace(String string) {
serviceNamespace = string;
}
public String getServiceNamespace() {
return serviceNamespace;
}
public void setSoapHeaderStyleSheet(String string){
this.soapHeaderStyleSheet = string;
}
public String getSoapHeaderStyleSheet() {
return soapHeaderStyleSheet;
}
public void setSoapBodyStyleSheet(String string){
this.soapBodyStyleSheet = string;
}
public String getSoapBodyStyleSheet() {
return soapBodyStyleSheet;
}
public void setRemoveOutputNamespaces(boolean b) {
removeOutputNamespaces = b;
}
public boolean isRemoveOutputNamespaces() {
return removeOutputNamespaces;
}
public void setOutputNamespace(String string) {
outputNamespace = string;
}
public String getOutputNamespace() {
return outputNamespace;
}
public void setSoapNamespace(String string) {
soapNamespace = string;
}
public String getSoapNamespace() {
return soapNamespace;
}
}
|
package com.intellij.codeInspection;
import com.google.gson.stream.JsonWriter;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.openapi.application.ApplicationStarter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@NonNls
final class StaticAnalysisExcludedPlugins implements ApplicationStarter {
List<String> pluginsToInclude = Arrays.asList(
"java",
"java-ide-customization",
"Hibernate",
"android",
"smali",
"ant",
"BeanValidation",
"CDI",
"uiDesigner",
"StrutsAssistant",
"JavaEE",
"CSS",
"FreeMarker",
"devkit",
"htmltools",
"maven",
"aop-common",
"w3validators",
"sql",
"StrutsAssistant",
"GwtStudio",
"Seam",
"junit",
"WebServices",
"IntelliLang",
"jsp",
"xpath",
"JSF",
"weblogicIntegration",
"Spring",
"SpringBatch",
"SpringData",
"SpringIntegration",
"SpringMVC",
"SpringSecurity",
"SpringWebflow",
"SpringWebServices",
"eclipse",
"testng",
"struts2",
"Velocity",
"Guice",
"Uml",
"PersistenceSupport",
"ToString",
"DatabaseTools",
"properties",
"BeanValidation",
"java-i18n",
"SpellChecker",
"Groovy",
"structuralsearch",
"gradle",
"Kotlin"
);
@Override
public String getCommandName() {
return "saExcluded";
}
@Override
public int getRequiredModality() {
return NOT_IN_EDT;
}
@Override
public void main(@NotNull List<String> args) {
try {
Writer out;
if (args.size() == 2) {
Path outFile = Paths.get(args.get(1));
Files.createDirectories(outFile.getParent());
out = Files.newBufferedWriter(outFile);
}
else {
// noinspection UseOfSystemOutOrSystemErr,IOResourceOpenedButNotSafelyClosed
out = new OutputStreamWriter(System.out, StandardCharsets.UTF_8);
}
List<? extends IdeaPluginDescriptor> plugins = PluginManagerCore.getLoadedPlugins();
List<String> pluginIds = new ArrayList<>(plugins.size());
List<String> toExclude = new ArrayList<>(plugins.size());
for (IdeaPluginDescriptor plugin : plugins) {
Path path = plugin.getPluginPath();
String pathName = path.getName(path.getNameCount() - 1).getFileName().toString();
String id = plugin.getPluginId().getIdString();
pluginIds.add(id + "; " + pathName + "; " + path + "\n");
if (!pluginsToInclude.contains(pathName)) {
toExclude.add(id + "\n");
}
}
pluginIds.sort(null);
toExclude.sort(null);
try (out) {
pluginIds.forEach(it -> {
try {
out.write(it, 0, it.length() );
}
catch (IOException e) {
//noinspection UseOfSystemOutOrSystemErr
e.printStackTrace(System.err);
System.exit(1);
}
});
out.write("\n To exclude: \n \n");
toExclude.forEach(it -> {
try {
out.write(it, 0, it.length() );
}
catch (IOException e) {
//noinspection UseOfSystemOutOrSystemErr
e.printStackTrace(System.err);
System.exit(1);
}
});
}
}
catch (IOException e) {
//noinspection UseOfSystemOutOrSystemErr
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
private static void writeList(@NotNull JsonWriter writer, String name, @NotNull List<String> elements) throws IOException {
writer.name(name).beginArray();
for (String module : elements) {
writer.value(module);
}
writer.endArray();
}
}
|
package jade.domain;
//#APIDOC_EXCLUDE_FILE
//#MIDP_EXCLUDE_FILE
import java.util.Vector;
import java.util.Date;
import jade.util.leap.HashMap;
import jade.util.leap.ArrayList;
import jade.util.leap.List;
import jade.util.leap.Iterator;
import jade.util.leap.Properties;
import jade.util.Logger;
import java.net.InetAddress;
import jade.core.AID;
import jade.core.behaviours.*;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.FIPAAgentManagement.InternalError;
import jade.domain.JADEAgentManagement.*;
import jade.domain.KBManagement.*;
import jade.domain.DFGUIManagement.*;
import jade.domain.DFGUIManagement.GetDescription; // Explicitly imported to avoid conflict with FIPA management ontology
//#PJAVA_EXCLUDE_BEGIN
import jade.domain.introspection.AMSSubscriber;
import jade.domain.introspection.Event;
import jade.domain.introspection.IntrospectionVocabulary;
import jade.domain.introspection.DeadAgent;
//#PJAVA_EXCLUDE_END
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.ISO8601;
import jade.gui.GuiAgent;
import jade.gui.GuiEvent;
import jade.proto.SubscriptionResponder;
import jade.proto.AchieveREInitiator;
import jade.content.*;
import jade.content.lang.*;
import jade.content.lang.sl.*;
import jade.content.onto.basic.*;
/**
<p>
Standard <em>Directory Facilitator</em> agent. This class implements
<em><b>FIPA</b></em> <em>DF</em> agent. <b>JADE</b> applications
cannot use this class directly, but interact with it through
<em>ACL</em> message passing. The <code>DFService</code> class provides
a number of static methods that facilitate this task.
More <em>DF</em> agents can be created
by application programmers to divide a platform into many
<em><b>Agent Domains</b></em>.
<p>
A DF agent accepts a number of optional configuration parameters that can be set
either as command line options or within a properties file (to be passed to
the DF as an argument).
</p>
<table border="1" cellspacing="0">
<tr>
<th>Parameter</th>
<th>Description</th>
</tr>
<tr>
<td>
<code>jade_domain_df_autocleanup</code>
</td>
<td>
If set to <code>true</code>, indicates that the DF will automatically
clean up registrations as soon as an agent terminates. The default is <code>false</code>
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_maxleasetime</code>
</td>
<td>
Indicates the maximum lease time (in millisecond) that the DF will grant for agent
description registrations (defaults to infinite).
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_maxresult</code>
</td>
<td>
Indicates the maximum number of items found in a search operation that the DF
will return to the requester (defaults to 100).
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_db-default</code>
</td>
<td>
If set to <code>true</code>, indicates that the DF will store its catalogue into an internal HSQL database,
running within the same VM. (The HSQL jar files have to added to the Java CLASSPATH)
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_db-url</code>
</td>
<td>
Indicates the JDBC URL of the database the DF will store its catalogue into.
This parameter is ignored if <code>jade_domain_df_db-default</code> is set. If neither this parameter nor
<code>jade_domain_df_db-default</code> is specified the DF will keep its catalogue in memory.
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_db-driver</code>
</td>
<td>
Indicates the JDBC driver to be used to access the DF database (defaults to the ODBC-JDBC bridge). This parameter
is ignored if <code>jade_domain_df_db-url</code> is not set or <code>jade_domain_df_db-default</code> is set.
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_db-username</code>,
<code>jade_domain_df_db-password</code>
</td>
<td>
Indicate the username and password to be used to access the DF database (default to null).
These parameters are ignored if <code>jade_domain_df_db-url</code> is not set or
<code>jade_domain_df_db-default</code> is set.
</td>
</tr>
<td>
<code>jade_domain_df_db-cleantables</code>
</td>
<td>
If set to <code>true</code>, indicates that the DF will clean the content of all pre-existing database tables,
used by the DF. This parameter is ignored if the catalogue is not stored in a database.
</td>
</tr>
<tr>
<td>
<code>jade_domain_df_kb-factory</code>
</td>
<td>
Indicates the name of the factory class that
should be used to create the knowledge base objects for the DF. The class has to be
a sub class of jade.domain.DFKBFactory.
</td>
</tr>
</table>
<p>
For instance the following command line will launch a JADE main container
with a DF that will store its catalogue into a database accessible at
URL jdbc:odbc:dfdb and that will keep agent registrations for 1 hour at most.
<code>
java jade.Boot -gui -jade_domain_df_db-url jdbc:odbc:dfdb -jade_domain_df_maxleasetime 3600000
</code>
<p>
Each DF has a GUI but, by default, it is not visible. The GUI of the
agent platform includes a menu item that allows to show the GUI of the
default DF.
In order to show the GUI, you should simply send the following message
to each DF agent: <code>(request :content (action DFName (SHOWGUI))
:ontology JADE-Agent-Management :protocol fipa-request)</code>
@see DFService
@author Giovanni Rimassa - Universita' di Parma
@author Tiziana Trucco - TILAB S.p.A.
@author Elisabetta Cortese - TILAB S.p.A.
@author Giovanni Caire - TILAB
@author Roland Mungenast - Profactor
@version $Date$ $Revision$
*/
public class df extends GuiAgent implements DFGUIAdapter {
// FIXME The size of the cache must be read from the Profile
private final static int SEARCH_ID_CACHE_SIZE = 16;
private jade.util.HashCache searchIdCache = new jade.util.HashCache(SEARCH_ID_CACHE_SIZE);
private int searchIdCnt = 0;
// The DF federated with this DF
private List children = new ArrayList();
// The DF this DF is federated with
private List parents = new ArrayList();
// Maps a parent DF to the description used by this DF to federate with that parent
private HashMap dscDFParentMap = new HashMap();
// Maps an action that is being serviced by a Behaviour to the
// request message that activated the Behaviour and the notification message
// to be sent back (as soon as the Behaviour will complete) to the requester
private HashMap pendingRequests = new HashMap();
// The GUI of this DF
private DFGUIInterface gui;
// Current description of this df
private DFAgentDescription myDescription = null;
private Codec codec = new SLCodec();
private DFFipaAgentManagementBehaviour fipaRequestResponder;
private DFJadeAgentManagementBehaviour jadeRequestResponder;
private DFAppletManagementBehaviour appletRequestResponder;
private SubscriptionResponder dfSubscriptionResponder;
//#PJAVA_EXCLUDE_BEGIN
private AMSSubscriber amsSubscriber;
//#PJAVA_EXCLUDE_END
// Configuration parameter keys
private static final String AUTOCLEANUP = "jade_domain_df_autocleanup";
private static final String MAX_LEASE_TIME = "jade_domain_df_maxleasetime";
private static final String MAX_RESULTS = "jade_domain_df_maxresult";
private static final String DB_DRIVER = "jade_domain_df_db-driver";
private static final String DB_URL = "jade_domain_df_db-url";
private static final String DB_USERNAME = "jade_domain_df_db-username";
private static final String DB_PASSWORD = "jade_domain_df_db-password";
private static final String KB_FACTORY = "jade_domain_df_kb-factory";
private static final String DB_DEFAULT = "jade_domain_df_db-default";
private static final String CLEANTABLES = "jade_domain_df_db-cleantables";
// Limit of searchConstraints.maxresult
// FIPA Agent Management Specification doc num: SC00023J (6.1.4 Search Constraints)
// a negative value of maxresults indicates that the sender agent is willing to receive
// all available results
private static final String DEFAULT_MAX_RESULTS = "100";
/*
* This is the actual value for the limit on the maximum number of results to be
* returned in case of an ulimited search. This value is read from the Profile,
* if no value is set in the Profile, then DEFAULT_MAX_RESULTS is used instead.
*/
private int maxResultLimit = Integer.parseInt(DEFAULT_MAX_RESULTS);
private Date maxLeaseTime = null;
private KB agentDescriptions = null;
private KBSubscriptionManager subManager = null;
private Logger logger = Logger.getMyLogger(this.getClass().getName());
/*
* WebService Integration Gateway (WSIG) requirements
* added by Whitestein Technologies AG,
* Contributor(s): Jozef Nagy (jna at whitestein.com)
*/
// AID of the WebService Integration Gateway
private AID gatewayAID = null;
// a gateway agent's name
private static final String GATEWAY_LOCAL_NAME = "wsig";
/*
* End: WSIG requirements
*/
/**
Default constructor. This constructor does nothing; however,
applications can create their own DF agents using regular
platform management commands. Moreover, customized versions of
a Directory Facilitator agent can be built subclassing this
class and exploiting its protected interface.
*/
public df() {
}
/**
This method starts all behaviours needed by <em>DF</em> agent to
perform its role within <em><b>JADE</b></em> agent platform.
*/
protected void setup() {
//#PJAVA_EXCLUDE_BEGIN
// Read configuration:
// If an argument is specified, it indicates the name of a properties
// file where to read DF configuration from. Otherwise configuration
// properties are read from the Profile.
// Values in a property file override those in the profile if
// both are specified.
String sAutocleanup = getProperty(AUTOCLEANUP, null);
String sMaxLeaseTime = getProperty(MAX_LEASE_TIME, null);
String sMaxResults = getProperty(MAX_RESULTS, DEFAULT_MAX_RESULTS);
String dbUrl = getProperty(DB_URL, null);
String dbDriver = getProperty(DB_DRIVER, null);
String dbUsername = getProperty(DB_USERNAME, null);
String dbPassword = getProperty(DB_PASSWORD, null);
String kbFactClass = getProperty(KB_FACTORY, null);
String sDBDefault = getProperty(DB_DEFAULT, null);
String sCleanTables = getProperty(CLEANTABLES, null);
DFKBFactory kbFactory = new DFKBFactory(); // set default factory
Object[] args = this.getArguments();
if(args != null && args.length > 0) {
Properties p = new Properties();
try {
p.load((String) args[0]);
sMaxLeaseTime = p.getProperty(MAX_LEASE_TIME, sMaxLeaseTime);
sMaxResults = p.getProperty(MAX_RESULTS, sMaxResults);
dbUrl = p.getProperty(DB_URL, dbUrl);
dbDriver = p.getProperty(DB_DRIVER, dbDriver);
dbUsername = p.getProperty(DB_USERNAME, dbUsername);
dbPassword = p.getProperty(DB_PASSWORD, dbPassword);
kbFactClass = p.getProperty(KB_FACTORY, kbFactClass);
sDBDefault = p.getProperty(DB_DEFAULT, sDBDefault);
}
catch (Exception e) {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"Error loading configuration from file "+args[0]+" ["+e+"].");
}
}
// Convert max lease time into a Date
try {
maxLeaseTime = new Date(Long.parseLong(sMaxLeaseTime));
}
catch (Exception e) {
// Keep default
}
// Convert max results into a number
try {
maxResultLimit = Integer.parseInt(sMaxResults);
if(maxResultLimit < 0){
maxResultLimit = Integer.parseInt(DEFAULT_MAX_RESULTS);
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"The maxResult parameter of the DF Search Constraints can't be a negative value. It has been set to the default value: " + DEFAULT_MAX_RESULTS);
}else if(maxResultLimit > Integer.parseInt(DEFAULT_MAX_RESULTS)){
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"Setting the maxResult of the DF Search Constraint to large values can cause low performance or system crash !! It has been set to the default value: " + DEFAULT_MAX_RESULTS);
}
}
catch (Exception e) {
// Keep default
}
// Instantiate the knowledge base
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"DF KB configuration:");
// Load class factory (if specified by the user)
if (kbFactClass != null) {
Class c = null;
try {
c = Class.forName(kbFactClass);
Object o = c.newInstance();
if (o != null && o instanceof DFKBFactory) {
kbFactory = (DFKBFactory)o;
if(logger.isLoggable(Logger.INFO))
logger.log(Logger.INFO,"Using class " + c.getName() + " as KB factory for the DF.");
} else {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"The class " + c.getName() + " is not a valid class factory for the DF.");
}
} catch (Exception e) {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE, "Error loading class " + kbFactClass + ". "+e);
}
if(logger.isLoggable(Logger.CONFIG)){
logger.log(Logger.CONFIG,"- KB class factory = " + kbFactory.getClass().getName());
}
}
// persistent KB
boolean cleanTables = false;
if (sCleanTables != null) {
try {
cleanTables = Boolean.valueOf(sCleanTables).booleanValue();
} catch (Exception e) {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"Parsing error for parameter " + CLEANTABLES, e);
}
}
boolean dbDefault = false;
if (sDBDefault != null) {
try {
dbDefault = Boolean.valueOf(sDBDefault).booleanValue();
} catch (Exception e) {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"Parsing error for parameter " + DB_DEFAULT, e);
}
}
if (dbDefault) {
if(logger.isLoggable(Logger.CONFIG)){
logger.log(Logger.CONFIG,"- Type = persistent");
logger.log(Logger.CONFIG,"- Using internal HSQL database");
}
try {
agentDescriptions = kbFactory.getDFDBKB(maxResultLimit, null, null, null, null, cleanTables);
}
catch (Exception e) {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"Error creating persistent KB based on HSQLDB ["+e+"]. Use a volatile KB.");
}
}
if (agentDescriptions == null && dbUrl != null) {
if(logger.isLoggable(Logger.CONFIG)){
logger.log(Logger.CONFIG,"- Type = persistent");
logger.log(Logger.CONFIG,"- DB url = "+dbUrl);
logger.log(Logger.CONFIG,"- DB driver = "+dbDriver);
logger.log(Logger.CONFIG,"- DB username = "+dbUsername);
logger.log(Logger.CONFIG,"- DB password = "+dbPassword);
}
try {
agentDescriptions = kbFactory.getDFDBKB(maxResultLimit, dbDriver, dbUrl, dbUsername, dbPassword, cleanTables);
}
catch (Exception e) {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"Error creating persistent KB ["+e+"]. Use a volatile KB.");
e.printStackTrace();
}
}
// volatile KB
if (agentDescriptions == null){
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"- Type = volatile");
agentDescriptions = kbFactory.getDFMemKB(maxResultLimit);
}
if(logger.isLoggable(Logger.CONFIG)){
logger.log(Logger.CONFIG,"- Max lease time = "+(maxLeaseTime != null ? ISO8601.toRelativeTimeString(maxLeaseTime.getTime()) : "infinite"));
logger.log(Logger.CONFIG,"- Max search result = "+maxResultLimit);
}
//#PJAVA_EXCLUDE_END
/*#PJAVA_INCLUDE_BEGIN
agentDescriptions = new DFMemKB(Integer.parseInt(getProperty(MAX_RESULTS, DEFAULT_MAX_RESULTS)));
#PJAVA_INCLUDE_END*/
// Initiate the SubscriptionManager used by the DF
subManager = new KBSubscriptionManager(agentDescriptions);
subManager.setContentManager(getContentManager());
// Register languages and ontologies
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0);
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL1);
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL2);
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL);
getContentManager().registerOntology(FIPAManagementOntology.getInstance());
getContentManager().registerOntology(JADEManagementOntology.getInstance());
getContentManager().registerOntology(DFAppletOntology.getInstance());
// Create and add behaviours
MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST);
MessageTemplate mt1 = null;
// Behaviour dealing with FIPA management actions
mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName()));
fipaRequestResponder = new DFFipaAgentManagementBehaviour(this, mt1);
addBehaviour(fipaRequestResponder);
// Behaviour dealing with JADE management actions
mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(JADEManagementOntology.getInstance().getName()));
jadeRequestResponder = new DFJadeAgentManagementBehaviour(this, mt1);
addBehaviour(jadeRequestResponder);
// Behaviour dealing with DFApplet management actions
mt1 = MessageTemplate.and(mt, MessageTemplate.MatchOntology(DFAppletOntology.getInstance().getName()));
appletRequestResponder = new DFAppletManagementBehaviour(this, mt1);
addBehaviour(appletRequestResponder);
// Behaviour dealing with subscriptions
mt1 = MessageTemplate.and(
MessageTemplate.MatchOntology(FIPAManagementOntology.getInstance().getName()),
MessageTemplate.or(MessageTemplate.MatchPerformative(ACLMessage.SUBSCRIBE), MessageTemplate.MatchPerformative(ACLMessage.CANCEL)));
dfSubscriptionResponder = new SubscriptionResponder(this, mt1, subManager) {
// If the CANCEL message has a meaningful content, use it.
// Otherwise deregister the Subscription with the same convID (default)
protected ACLMessage handleCancel(ACLMessage cancel) throws FailureException {
try {
Action act = (Action) myAgent.getContentManager().extractContent(cancel);
ACLMessage subsMsg = (ACLMessage)act.getAction();
Subscription s = createSubscription(subsMsg);
mySubscriptionManager.deregister(s);
s.close();
}
catch(Exception e) {
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Unknown CANCEL content. Use default handler");
super.handleCancel(cancel);
}
return null;
}
};
addBehaviour(dfSubscriptionResponder);
// Set the DFDescription of thie DF
setDescriptionOfThisDF(getDefaultDescription());
// Set lease policy and subscription responder to the knowledge base
agentDescriptions.setSubscriptionResponder(dfSubscriptionResponder);
agentDescriptions.setLeaseManager(new LeaseManager() {
public Date getLeaseTime(Object item){
return ((DFAgentDescription) item).getLeaseTime();
}
public void setLeaseTime(Object item, Date lease){
((DFAgentDescription) item).setLeaseTime(lease);
}
/**
* Grant a lease to this request according to the
* policy of the DF: if the requested lease is
* greater than the max lease policy of this DF, then
* the granted lease is set to the max of the DF.
**/
public Object grantLeaseTime(Object item){
if (maxLeaseTime != null) {
Date lease = getLeaseTime(item);
long current = System.currentTimeMillis();
if ( (lease != null && lease.getTime() > (current+maxLeaseTime.getTime())) ||
( (lease == null) && (maxLeaseTime != null))) {
// the first condition of this if considers the case when the agent requestes a leasetime greater than the policy of this DF. The second condition, instead, considers the case when the agent requests an infinite leasetime and the policy of this DF does not allow infinite leases.
setLeaseTime(item, new Date(current+maxLeaseTime.getTime()));
}
}
return item;
}
public boolean isExpired(Date lease){
return (lease != null && (lease.getTime() <= System.currentTimeMillis()));
}
} );
// Prepare the default description of this DF (used for federations)
myDescription = getDefaultDescription();
//#PJAVA_EXCLUDE_BEGIN
boolean autocleanup = false;
try {
autocleanup = Boolean.valueOf(sAutocleanup).booleanValue();
}
catch (Exception e) {e.printStackTrace();}
if (autocleanup) {
logger.log(Logger.CONFIG,"Autocleanup activated");
// Finally add the behaviour that listens for AMS notifications
// about dead agents.
amsSubscriber = new AMSSubscriber() {
protected void installHandlers(java.util.Map handlersTable) {
handlersTable.put(IntrospectionVocabulary.DEADAGENT, new EventHandler() {
public void handle(Event ev) {
try {
DeadAgent da = (DeadAgent)ev;
AID id = da.getAgent();
DFAgentDescription dfd = new DFAgentDescription();
dfd.setName(id);
DFDeregister(dfd);
}
catch (Exception e) {
// Just do nothing
}
}
});
}
};
addBehaviour(amsSubscriber);
}
//#PJAVA_EXCLUDE_END
} // End of method setup()
/**
Cleanup <em>DF</em> on exit. This method performs all necessary
cleanup operations during agent shutdown.
*/
protected void takeDown() {
//#PJAVA_EXCLUDE_BEGIN
if (amsSubscriber != null) {
// Unsubscribe from the AMS
send(amsSubscriber.getCancel());
}
//#PJAVA_EXCLUDE_END
if(gui != null) {
gui.disposeAsync();
}
DFAgentDescription dfd = new DFAgentDescription();
dfd.setName(getAID());
Iterator it = parents.iterator();
while(it.hasNext()) {
AID parentName = (AID)it.next();
try {
DFService.deregister(this, parentName, dfd);
}
catch(FIPAException fe) {
fe.printStackTrace();
}
}
}
// Recursive search
/**
Add the behaviour handling a recursive search.
If constraints contains a null search_id, then a new one is generated and
the new search_id is stored into searchIdCache
for later check (i.e. to avoid search loops).
*/
private void performRecursiveSearch(List localResults, DFAgentDescription dfd, SearchConstraints constraints, Search action){
int maxRes = getActualMaxResults(constraints);
int maxDep = constraints.getMaxDepth().intValue();
// Create the new SearchConstraints.
SearchConstraints newConstr = new SearchConstraints();
// Max-depth decreased by 1
newConstr.setMaxDepth(new Long ((long) (maxDep - 1)));
// Max-results decreased by the number of items found locally
newConstr.setMaxResults(new Long((long) (maxRes - localResults.size())));
// New globally unique search-id unless already present
String searchId = constraints.getSearchId();
if (searchId == null) {
searchId = getName() + String.valueOf(searchIdCnt++) + System.currentTimeMillis();
if (searchIdCnt >= SEARCH_ID_CACHE_SIZE) {
searchIdCnt = 0;
}
searchIdCache.add(searchId);
}
newConstr.setSearchId(searchId);
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Activating recursive search: "+localResults.size()+" item(s) found locally. "+maxRes+" expected. Search depth is "+maxDep+". Search ID is "+searchId+". Propagating search to "+children.size()+" federated DF(s)");
// Add the behaviour handling the search on federated DFs
addBehaviour(new RecursiveSearchHandler(localResults, dfd, newConstr, action));
}
/**
Inner class RecursiveSearchHandler.
This is a behaviour handling recursive searches i.e. searches that
must be propagated to children (federated) DFs.
*/
private class RecursiveSearchHandler extends AchieveREInitiator {
private static final long DEFAULTTIMEOUT = 300000; // 5 minutes
private List results;
private DFAgentDescription template;
private SearchConstraints constraints;
private Search action;
private int maxExpectedResults;
private int receivedResults;
/**
Construct a new RecursiveSearchHandler.
@param results The search results. Initially this includes the items found
locally.
@param template The DFAgentDescription used as tamplate for the search.
@param constraints The constraints for the search to be propagated.
@param action The original Search action. This is used as a key to retrieve
the incoming REQUEST message.
*/
private RecursiveSearchHandler(List results, DFAgentDescription template, SearchConstraints constraints, Search action) {
super(df.this, null);
this.results = results;
this.template = template;
this.constraints = constraints;
this.action = action;
maxExpectedResults = constraints.getMaxResults().intValue();
receivedResults = 0;
}
/**
We broadcast the search REQUEST to all children (federated) DFs in parallel.
*/
protected Vector prepareRequests(ACLMessage request) {
Vector requests = null;
ACLMessage incomingRequest = (ACLMessage) pendingRequests.get(action);
if (incomingRequest != null) {
Date deadline = incomingRequest.getReplyByDate();
if (deadline == null) {
deadline = new Date(System.currentTimeMillis() + DEFAULTTIMEOUT);
}
requests = new Vector(children.size());
Iterator it = children.iterator();
while (it.hasNext()) {
AID childDF = (AID) it.next();
ACLMessage msg = DFService.createRequestMessage(myAgent, childDF, FIPAManagementVocabulary.SEARCH, template, constraints);
msg.setReplyByDate(deadline);
requests.addElement(msg);
}
}
return requests;
}
/**
As long as we receive the replies we update the results. If we reach the
max-results we send back the notification to the requester and discard
successive replies.
*/
protected void handleInform(ACLMessage inform) {
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Recursive search result received from "+inform.getSender().getName()+".");
int cnt = 0;
if (receivedResults < maxExpectedResults) {
try {
DFAgentDescription[] dfds = DFService.decodeResult(inform.getContent());
for (int i = 0; i < dfds.length; ++i) {
// We add the item only if not already present
if (addResult(dfds[i])) {
receivedResults++;
cnt++;
if (receivedResults >= maxExpectedResults) {
sendPendingNotification(action, results);
}
}
}
}
catch (Exception e) {
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"WARNING: Error decoding reply from federated DF "+inform.getSender().getName()+" during recursive search ["+e.toString()+"].");
}
}
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,cnt+" new items found in recursive search.");
}
protected void handleRefuse(ACLMessage refuse) {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"REFUSE received from federated DF "+refuse.getSender().getName()+" during recursive search.");
}
protected void handleFailure(ACLMessage failure) {
// FIXME: In general this is due to a federation loop (search-id already used)
// In this case no warning must be printed --> We should use FINE log level in that case
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"FAILURE received from federated DF "+failure.getSender().getName()+" during recursive search.");
}
protected void handleNotUnderstood(ACLMessage notUnderstood) {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"NOT_UNDERSTOOD received from federated DF "+notUnderstood.getSender().getName()+" during recursive search.");
}
protected void handleOutOfSequence(ACLMessage msg) {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"Out of sequence message "+ACLMessage.getPerformative(msg.getPerformative())+" received from "+msg.getSender().getName()+" during recursive search.");
}
public int onEnd() {
// Send back the notification to the originator of the
// search (unless already sent)
if (receivedResults < maxExpectedResults) {
sendPendingNotification(action, results);
}
return super.onEnd();
}
private boolean addResult(DFAgentDescription newDfd) {
Iterator it = results.iterator();
while (it.hasNext()) {
DFAgentDescription dfd = (DFAgentDescription) it.next();
if (dfd.getName().equals(newDfd.getName())) {
return false;
}
}
results.add(newDfd);
return true;
}
} // END of inner class RecursiveSearchHandler
// Methods actually accessing the DF Knowledge base
void DFRegister(DFAgentDescription dfd) throws AlreadyRegistered {
//checkMandatorySlots(FIPAAgentManagementOntology.REGISTER, dfd);
Object old = agentDescriptions.register(dfd.getName(), dfd);
if(old != null)
throw new AlreadyRegistered();
if(isADF(dfd)) {
if(logger.isLoggable(Logger.INFO))
logger.log(Logger.INFO,"Added federation "+dfd.getName().getName()+" --> "+getName());
children.add(dfd.getName());
try {
gui.addChildren(dfd.getName());
} catch (Exception ex) {}
}
// for subscriptions
subManager.handleChange(dfd);
try{ //refresh the GUI if shown, exception thrown if the GUI was not shown
gui.addAgentDesc(dfd.getName());
gui.showStatusMsg("Registration of agent: " + dfd.getName().getName() + " done.");
}catch(Exception ex){}
}
//this method is called into the prepareResponse of the DFFipaAgentManagementBehaviour to perform a Deregister action
void DFDeregister(DFAgentDescription dfd) throws NotRegistered {
//checkMandatorySlots(FIPAAgentManagementOntology.DEREGISTER, dfd);
Object old = agentDescriptions.deregister(dfd.getName());
if(old == null)
throw new NotRegistered();
if (children.remove(dfd.getName()))
try {
gui.removeChildren(dfd.getName());
} catch (Exception e) {}
try{
// refresh the GUI if shown, exception thrown if the GUI was not shown
// this refresh must be here, otherwise the GUI is not synchronized with
// registration/deregistration made without using the GUI
gui.removeAgentDesc(dfd.getName(),df.this.getAID());
gui.showStatusMsg("Deregistration of agent: " + dfd.getName().getName() +" done.");
}catch(Exception e1){}
}
void DFModify(DFAgentDescription dfd) throws NotRegistered {
// checkMandatorySlots(FIPAAgentManagementOntology.MODIFY, dfd);
Object old = agentDescriptions.register(dfd.getName(), dfd);
if(old == null) {
// Rollback
agentDescriptions.deregister(dfd.getName());
throw new NotRegistered();
}
// for subscription
subManager.handleChange(dfd);
try{
gui.removeAgentDesc(dfd.getName(), df.this.getAID());
gui.addAgentDesc(dfd.getName());
gui.showStatusMsg("Modify of agent: "+dfd.getName().getName() + " done.");
}catch(Exception e){}
}
List DFSearch(DFAgentDescription dfd, int maxResults) {
return agentDescriptions.search(dfd, maxResults);
}
// Methods serving the actions of the FIPA Management ontology
/**
Serve the Register action of the FIPA management ontology.
Package scoped since it is called by DFFipaAgentManagementBehaviour.
*/
void registerAction(Register r, AID requester) throws FIPAException {
DFAgentDescription dfd = (DFAgentDescription) r.getDescription();
// Check mandatory slots
DFService.checkIsValid(dfd, true);
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester.getName()+" requesting action Register for "+dfd.getName());
// Avoid autoregistration
if (dfd.getName().equals(getAID())) {
throw new Unauthorised();
}
// Do it
DFRegister(dfd);
/*
* WebService Integration Gateway (WSIG) requirements
* added by Whitestein Technologies AG,
* Contributor(s): Jozef Nagy (jna at whitestein.com)
*/
if ( null == gatewayAID && isAGateway( dfd ) ) {
// The WSIG is registered
gatewayAID = dfd.getName();
}
/*
* End: WSIG requirements
*/
}
/**
Serve the Deregister action of the FIPA management ontology.
Package scoped since it is called by DFFipaAgentManagementBehaviour.
*/
void deregisterAction(Deregister d, AID requester) throws FIPAException {
DFAgentDescription dfd = (DFAgentDescription) d.getDescription();
// Check mandatory slots
DFService.checkIsValid(dfd, false);
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester.getName()+" requesting action Deregister for "+dfd.getName());
// Do it
DFDeregister(dfd);
/*
* WebService Integration Gateway (WSIG) requirements
* added by Whitestein Technologies AG,
* Contributor(s): Jozef Nagy (jna at whitestein.com)
*/
if (dfd.getName().equals(gatewayAID)) {
// The WSIG is deregistered
gatewayAID = null;
}
/*
* End: WSIG requirements
*/
}
/**
Serve the Modify action of the FIPA management ontology.
Package scoped since it is called by DFFipaAgentManagementBehaviour.
*/
void modifyAction(Modify m, AID requester) throws FIPAException {
DFAgentDescription dfd = (DFAgentDescription) m.getDescription();
// Check mandatory slots
DFService.checkIsValid(dfd, true);
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester.getName()+" requesting action Modify for "+dfd.getName());
// Do it
DFModify(dfd);
}
/**
Serve the Search action of the FIPA management ontology.
Package scoped since it is called by DFFipaAgentManagementBehaviour.
@return the List of descriptions matching the template specified
in the Search action. If no description is found an empty List
is returned. In case a recursive search is required it returns
null to indicate that the result is not yet available.
*/
List searchAction(Search s, AID requester) throws FIPAException {
DFAgentDescription dfd = (DFAgentDescription) s.getDescription();
SearchConstraints constraints = s.getConstraints();
List result = null;
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester.getName()+" requesting action Search");
// Avoid loops in searching on federated DFs
checkSearchId(constraints.getSearchId());
int maxResult = getActualMaxResults(constraints);
// Search locally
result = DFSearch(dfd, maxResult);
// Note that if the local search produced more results than
// required, we don't even consider the recursive search
// regardless of the maxDepth parameter.
if(result.size() < maxResult) {
// Check if the search has to be propagated
Long maxDepth = constraints.getMaxDepth();
if ( (children.size() > 0) && (maxDepth != null) && (maxDepth.intValue() > 0) ) {
// Start a recursive search.
performRecursiveSearch(result, dfd, constraints, s);
// The final result will be available at a later time.
return null;
}
}
return result;
}
// Methods serving the actions of the JADE Management ontology
/**
Serve the ShowGui action of the JADE management ontology.
Package scoped since it is called by DFJadeAgentManagementBehaviour.
@exception FailureException If the GUI is already visible or some
error occurs creating the GUI.
*/
void showGuiAction(ShowGui sg, AID requester) throws FailureException {
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester.getName()+" requesting action ShowGui");
if (!showGui()){
throw new FailureException("Gui_is_being_shown_already");
}
}
// Methods serving the actions of the DF-Applet ontology
/**
Serve the GetParents action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
List getParentsAction(GetParents action, AID requester) {
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action GetParents.");
return parents;
}
/**
Serve the GetDescription action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
List getDescriptionAction(GetDescription action, AID requester) {
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action GetDescription.");
// FIXME: This embeds the description into a list since the Applet still expects a List
List tmp = new ArrayList();
tmp.add(getDescriptionOfThisDF());
return tmp;
}
/**
Serve the GetDescriptionUsed action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
List getDescriptionUsedAction(GetDescriptionUsed action, AID requester) {
AID parent = action.getParentDF();
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action GetDescriptionUsed to federate with "+parent.getName());
// FIXME: This embeds the description into a list since the Applet still expects a List
List tmp = new ArrayList();
tmp.add(getDescriptionOfThisDF(parent));
return tmp;
}
/**
Serve the Federate action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
void federateAction(final Federate action, AID requester) {
AID remoteDF = action.getDf();
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action Federate with DF "+remoteDF.getName());
Register r = new Register();
DFAgentDescription tmp = action.getDescription();
final DFAgentDescription dfd = (tmp != null ? tmp : getDescriptionOfThisDF());
r.setDescription(dfd);
Behaviour b = new RemoteDFRequester(remoteDF, r) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
addParent(getRemoteDF(), dfd);
}
sendPendingNotification(action, result);
return 0;
}
};
addBehaviour(b);
}
/**
Serve the RegisterWith action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
void registerWithAction(final RegisterWith action, AID requester){
AID remoteDF = action.getDf();
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action RegisterWith on DF "+remoteDF.getName());
Register r = new Register();
final DFAgentDescription dfd = action.getDescription();
r.setDescription(dfd);
Behaviour b = new RemoteDFRequester(remoteDF, r) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
if(dfd.getName().equals(myAgent.getAID())) {
// The registered agent is the DF itself --> This is a federation
addParent(getRemoteDF(), dfd);
}
}
sendPendingNotification(action, result);
return 0;
}
};
addBehaviour(b);
}
/**
Serve the DeregisterFrom action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
void deregisterFromAction(final DeregisterFrom action, AID requester){
AID remoteDF = action.getDf();
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action DeregisterFrom on DF "+remoteDF.getName());
Deregister d = new Deregister();
final DFAgentDescription dfd = action.getDescription();
d.setDescription(dfd);
Behaviour b = new RemoteDFRequester(remoteDF, d) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
if(dfd.getName().equals(myAgent.getAID())) {
// The deregistered agent is the DF itself --> Remove a federation
removeParent(getRemoteDF());
}
}
sendPendingNotification(action, result);
return 0;
}
};
addBehaviour(b);
}
/**
Serve the ModifyOn action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
void modifyOnAction(final ModifyOn action, AID requester){
AID remoteDF = action.getDf();
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action ModifyOn on DF "+remoteDF.getName());
Modify m = new Modify();
m.setDescription(action.getDescription());
Behaviour b = new RemoteDFRequester(remoteDF, m) {
public int onEnd() {
sendPendingNotification(action, getResult());
return 0;
}
};
addBehaviour(b);
}
/**
Serve the SearchOn action of the DF-Applet ontology
Package scoped since it is called by DFAppletManagementBehaviour.
*/
void searchOnAction(final SearchOn action, AID requester){
AID remoteDF = action.getDf();
if(logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG,"Agent "+requester+" requesting action SearchOn on DF "+remoteDF.getName());
Search s = new Search();
s.setDescription(action.getDescription());
s.setConstraints(action.getConstraints());
Behaviour b = new RemoteDFRequester(remoteDF, s) {
public int onEnd() {
sendPendingNotification(action, getResult());
return 0;
}
};
addBehaviour(b);
}
//#APIDOC_EXCLUDE_BEGIN
// GUI Management: DFGUIAdapter interface implementation
protected void onGuiEvent(GuiEvent ev) {
try
{
switch(ev.getType()) {
case DFGUIAdapter.EXIT: {
gui.disposeAsync();
gui = null;
doDelete();
break;
}
case DFGUIAdapter.CLOSEGUI: {
gui.disposeAsync();
gui = null;
break;
}
case DFGUIAdapter.REGISTER: {
AID df = (AID) ev.getParameter(0);
final DFAgentDescription dfd = (DFAgentDescription) ev.getParameter(1);
DFService.checkIsValid(dfd, true);
if (getAID().equals(df)) {
// Register an agent with this DF
DFRegister(dfd);
}
else {
// Register an agent with another DF.
gui.showStatusMsg("Processing your request & waiting for result...");
Register r = new Register();
r.setDescription(dfd);
Behaviour b = new RemoteDFRequester(df, r) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
gui.showStatusMsg("Registration request processed. Ready for new request");
if(dfd.getName().equals(myAgent.getAID())) {
// The registered agent is the DF itself --> This is a federation
addParent(getRemoteDF(), dfd);
}
}
else {
gui.showStatusMsg("Error processing request. "+((InternalError) result).getMessage());
}
return 0;
}
};
addBehaviour(b);
}
break;
}
case DFGUIAdapter.DEREGISTER: {
AID df = (AID) ev.getParameter(0);
final DFAgentDescription dfd = (DFAgentDescription) ev.getParameter(1);
DFService.checkIsValid(dfd, false);
if (getAID().equals(df)) {
// Deregister an agent with this DF
DFDeregister(dfd);
}
else {
// Deregister an agent with another DF.
gui.showStatusMsg("Processing your request & waiting for result...");
Deregister d = new Deregister();
d.setDescription(dfd);
Behaviour b = new RemoteDFRequester(df, d) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
gui.showStatusMsg("Deregistration request processed. Ready for new request");
if(dfd.getName().equals(myAgent.getAID())) {
// The deregistered agent is the DF itself --> Remove a federation
removeParent(getRemoteDF());
}
else {
gui.removeSearchResult(dfd.getName());
}
}
else {
gui.showStatusMsg("Error processing request. "+((InternalError) result).getMessage());
}
return 0;
}
};
addBehaviour(b);
}
break;
}
case DFGUIAdapter.MODIFY: {
AID df = (AID) ev.getParameter(0);
DFAgentDescription dfd = (DFAgentDescription) ev.getParameter(1);
DFService.checkIsValid(dfd, true);
if (getAID().equals(df)) {
// Modify the description of an agent with this DF
DFModify(dfd);
}
else {
// Modify the description of an agent with another DF
gui.showStatusMsg("Processing your request & waiting for result...");
Modify m = new Modify();
m.setDescription(dfd);
Behaviour b = new RemoteDFRequester(df, m) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
gui.showStatusMsg("Modification request processed. Ready for new request");
}
else {
gui.showStatusMsg("Error processing request. "+((InternalError) result).getMessage());
}
return 0;
}
};
addBehaviour(b);
}
break;
}
case DFGUIAdapter.SEARCH: {
AID df = (AID) ev.getParameter(0);
DFAgentDescription dfd = (DFAgentDescription) ev.getParameter(1);
SearchConstraints sc = (SearchConstraints)ev.getParameter(2);
// Note that we activate a RemoteDFBehaviour even if the DF to perform
// the search on is the local DF. This allows handling recursive
// search (if needed) correctly
gui.showStatusMsg("Processing your request & waiting for result...");
Search s = new Search();
s.setDescription(dfd);
s.setConstraints(sc);
Behaviour b = new RemoteDFRequester(df, s) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
gui.showStatusMsg("Search request processed. Ready for new request");
gui.refreshLastSearchResults((List) result, getRemoteDF());
}
else {
gui.showStatusMsg("Error processing request. "+((InternalError) result).getMessage());
}
return 0;
}
};
addBehaviour(b);
break;
}
case DFGUIAdapter.FEDERATE: {
AID df = (AID) ev.getParameter(0);
final DFAgentDescription dfd = (DFAgentDescription) ev.getParameter(1);
gui.showStatusMsg("Processing your request & waiting for result...");
Register r = new Register();
r.setDescription(dfd);
Behaviour b = new RemoteDFRequester(df, r) {
public int onEnd() {
Object result = getResult();
if (!(result instanceof InternalError)) {
gui.showStatusMsg("Federation request processed. Ready for new request");
addParent(getRemoteDF(), dfd);
}
else {
gui.showStatusMsg("Error processing request. "+((InternalError) result).getMessage());
}
return 0;
}
};
addBehaviour(b);
break;
}
} // END of switch
} // END of try
catch(FIPAException fe) {
gui.showStatusMsg("Error processing request. "+fe.getMessage());
fe.printStackTrace();
}
}
//#APIDOC_EXCLUDE_END
/**
This method returns the descriptor of an agent registered with the DF.
*/
public DFAgentDescription getDFAgentDsc(AID name) throws FIPAException
{
DFAgentDescription template = new DFAgentDescription();
template.setName(name);
List l = agentDescriptions.search(template);
if(l.isEmpty())
return null;
else
return (DFAgentDescription)l.get(0);
}
/**
* This method returns the current description of this DF
*/
public DFAgentDescription getDescriptionOfThisDF() {
return myDescription;
}
/**
* This method returns the description of this df used to federate with the given parent
*/
public DFAgentDescription getDescriptionOfThisDF(AID parent) {
return (DFAgentDescription)dscDFParentMap.get(parent);
}
// Utility methods
/**
This method make visible the GUI of the DF.
@return true if the GUI was not visible already, false otherwise.
*/
protected boolean showGui() {
if (gui == null)
{
try{
Class c = Class.forName("jade.tools.dfgui.DFGUI");
gui = (DFGUIInterface)c.newInstance();
gui.setAdapter(df.this); //this method must be called to avoid reflection (the constructor of the df gui has no parameters).
DFAgentDescription matchEverything = new DFAgentDescription();
List agents = agentDescriptions.search(matchEverything);
List AIDList = new ArrayList();
Iterator it = agents.iterator();
while(it.hasNext())
AIDList.add(((DFAgentDescription)it.next()).getName());
gui.refresh(AIDList.iterator(), parents.iterator(), children.iterator());
gui.setVisible(true);
return true;
}catch(Exception e){e.printStackTrace();}
}
return false;
}
/**
* This method creates the DFAgent descriptor for this df used to federate with other df.
*/
private DFAgentDescription getDefaultDescription() {
DFAgentDescription out = new DFAgentDescription();
out.setName(getAID());
out.addOntologies(FIPAManagementOntology.getInstance().getName());
out.addLanguages(FIPANames.ContentLanguage.FIPA_SL0);
out.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST);
ServiceDescription sd = new ServiceDescription();
sd.setName("df-service");
sd.setType("fipa-df");
sd.addOntologies(FIPAManagementOntology.getInstance().getName());
sd.addLanguages(FIPANames.ContentLanguage.FIPA_SL0);
sd.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST);
try{
sd.setOwnership(InetAddress.getLocalHost().getHostName());
}catch (java.net.UnknownHostException uhe){
sd.setOwnership("unknown");
}
out.addServices(sd);
return out;
}
/**
* This method set the description of the df according to the DFAgentDescription passed.
* The programmers can call this method to provide a different initialization of the description of the df they are implementing.
* The method is called inside the setup of the agent and set the df description using a default description.
*/
protected void setDescriptionOfThisDF(DFAgentDescription dfd) {
myDescription = dfd;
myDescription.setName(getAID());
if (!isADF(myDescription)) {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"The description set for this DF does not include a \"fipa-df\" service.");
}
}
/**
* This method can be used to add a parent (a DF this DF is federated with).
* @param dfName the parent df (the df with which this df has been registered)
* @param dfd the description used by this df to register with the parent.
*/
protected void addParent(AID dfName, DFAgentDescription dfd)
{
parents.add(dfName);
if(gui != null) // the gui can be null if this method is called in order to manage a request made by the df-applet.
gui.addParent(dfName);
dscDFParentMap.put(dfName,dfd); //update the table of corrispondence between parents and description of this df used to federate.
}
/**
this method can be used to remove a parent (a DF with which this DF is federated).
*/
protected void removeParent(AID dfName)
{
parents.remove(dfName);
if(gui != null) //the gui can be null is this method is called in order to manage a request from the df applet
gui.removeParent(dfName);
dscDFParentMap.remove(dfName);
}
/**
Store the request message
related to an action that is being processed by a Behaviour.
This information will be used by the Behaviour to send back the
notification to the requester.
*/
void storePendingRequest(Object key, ACLMessage request) {
pendingRequests.put(key, request);
}
/**
Send the notification related to an action that has been processed
by a Behaviour.
*/
private void sendPendingNotification(Concept action, Object result) {
ACLMessage request = (ACLMessage) pendingRequests.remove(action);
if (request != null) {
ACLMessage notification = request.createReply();
ContentElement ce = null;
Action act = new Action(getAID(), action);
if (result instanceof InternalError) {
// Some error occurred during action processing
notification.setPerformative(ACLMessage.FAILURE);
ContentElementList cel = new ContentElementList();
cel.add(act);
cel.add((Predicate) result);
ce = cel;
}
else {
// Action processing was OK
notification.setPerformative(ACLMessage.INFORM);
if (result != null) {
ce = new Result(act, result);
}
else {
ce = new Done(act);
}
}
try {
getContentManager().fillContent(notification, ce);
send(notification);
AID receiver = (AID) notification.getAllReceiver().next();
if(logger.isLoggable(Logger.FINE))
logger.log(Logger.FINE,"Notification sent back to "+receiver.getName());
}
catch (Exception e) {
// Should never happen
if(logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE,"Error encoding pending notification content.");
e.printStackTrace();
}
}
else {
if(logger.isLoggable(Logger.WARNING))
logger.log(Logger.WARNING,"Processed action request not found.");
}
}
/**
* @return
* <ul>
* <li> 1 if constraints.maxResults == null (according to FIPA specs)
* <li> LIMIT_MAXRESULT if constraints.maxResults < 0 (the FIPA specs requires it to be
* infinite, but for practical reason we prefer to limit it)
* <li> constraints.maxResults otherwise
* </ul>
**/
private int getActualMaxResults(SearchConstraints constraints) {
int maxResult = (constraints.getMaxResults() == null ? 1 : constraints.getMaxResults().intValue());
maxResult = (maxResult < 0 ? maxResultLimit : maxResult); // limit the max num of results
return maxResult;
}
/**
Check if this search must be served, i.e. if it has not yet been received.
In particular the value of search_id must be different from any prior value that was received.
If search_id is not null and it has not yet been received, search_id is
added into the cache.
@exception FIPAException if the search id is already in the cache.
*/
private void checkSearchId(String searchId) throws FIPAException {
if (searchId != null) {
if (searchIdCache.contains(searchId)) {
throw new InternalError("search-id already served");
}
else {
searchIdCache.add(searchId);
}
}
}
private boolean isADF(DFAgentDescription dfd) {
try {
return ((ServiceDescription)dfd.getAllServices().next()).getType().equalsIgnoreCase("fipa-df");
} catch (Exception e) {
return false;
}
}
/*
* WebService Integration Gateway (WSIG) requirements
* added by Whitestein Technologies AG,
* Contributor(s): Jozef Nagy (jna at whitestein.com)
*/
/**
* adds a Web Service Integration Gateway's AID into notification's receivers.
* When no gateway is registered or an requester is a gateway itself,
* the notification is not changed.
* The method is only used by DFFipaAgentManagementBehaviour.
*
* @param request an original request
* @param notification a reply for a request
*/
void addGatewayIfNeeded( ACLMessage request, ACLMessage notification ) {
// please, inform also WebService Integration Gateway
// avoid a duplication in receivers
if ( null != gatewayAID
&&
! isFromGatewayRegistered( request ) ) {
notification.addReceiver( gatewayAID );
}
}
/**
* checks, if a request is from a gateway registered
*
* @param request a request
* @return true, if a request is from a gateway registered
*/
private boolean isFromGatewayRegistered( ACLMessage request ) {
return request.getSender().equals( gatewayAID );
}
/**
* checks, if a description is from a Web Service Integration Gateway.
* Any agent named by GATEWAY_LOCAL_NAME is a gateway.
*
* @param dfd a description
* @return true, if a description is from a gateway
*/
private boolean isAGateway(DFAgentDescription dfd) {
//FIXME an identification must be changed
return dfd.getName().getLocalName().equalsIgnoreCase(GATEWAY_LOCAL_NAME);
}
/*
* End: WSIG requirements
*/
}
|
package org.unitime.timetable.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.unitime.commons.web.Web;
import org.unitime.timetable.form.ExamInfoForm;
import org.unitime.timetable.model.TimetableManager;
import org.unitime.timetable.model.dao.ExamDAO;
import org.unitime.timetable.solver.WebSolver;
import org.unitime.timetable.solver.exam.ui.ExamInfoModel;
/**
* @author Tomas Muller
*/
public class ExamInfoAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ExamInfoForm myForm = (ExamInfoForm) form;
// Check Access
if (!Web.isLoggedIn( request.getSession() )) {
throw new Exception ("Access Denied.");
}
String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op"));
ExamInfoModel model = (ExamInfoModel)request.getSession().getAttribute("ExamInfo.model");
if (model==null) {
model = new ExamInfoModel();
request.getSession().setAttribute("ExamInfo.model", model);
}
if (op==null && model.getExam()!=null && request.getParameter("examId")==null) {
op="Apply";
}
if ("Apply".equals(op)) {
myForm.save(request.getSession());
} else if ("Refresh".equals(op)) {
myForm.reset(mapping, request);
}
myForm.load(request.getSession());
myForm.setModel(model);
model.apply(request, myForm);
if (op==null) {
model.clear(TimetableManager.getManager(Web.getUser(request.getSession())));
} else if ("Apply".equals(op)) {
model.refreshRooms();
model.refreshSuggestions();
} if ("Search Deeper".equals(op)) {
myForm.setDepth(myForm.getDepth()+1);
myForm.save(request.getSession());
model.refreshSuggestions();
} else if ("Search Longer".equals(op)) {
myForm.setTimeout(2*myForm.getTimeout());
myForm.save(request.getSession());
model.refreshSuggestions();
}
model.setSolver(WebSolver.getExamSolver(request.getSession()));
if (request.getParameter("examId")!=null) {
model.setExam(new ExamDAO().get(Long.valueOf(request.getParameter("examId"))));
myForm.save(request.getSession());
}
if (model.getExam()==null) throw new Exception("No exam given.");
if ("Select".equals(op)) {
if (request.getParameter("period")!=null)
model.setPeriod(Long.valueOf(request.getParameter("period")));
if (request.getParameter("room")!=null)
model.setRooms(request.getParameter("room"));
if (request.getParameter("suggestion")!=null)
model.setSuggestion(Integer.parseInt(request.getParameter("suggestion")));
if (request.getParameter("delete")!=null)
model.delete(Long.valueOf(request.getParameter("delete")));
}
if ("Assign".equals(op)) {
String message = model.assign();
if (message==null || message.trim().length()==0) {
myForm.setOp("Close");
} else {
myForm.setMessage(message);
}
}
if ("Close".equals(op)) {
myForm.setOp("Close");
}
/*
BackTracker.markForBack(
request,
"examInfo.do?examId=" + model.getExam().getExamId(),
"Exam Info ("+ model.getExam().getExamName() +")",
true, false);
*/
return mapping.findForward("show");
}
}
|
package com.cloud.api.commands;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.api.BaseCmd;
import com.cloud.api.ServerApiException;
import com.cloud.dc.VlanVO;
import com.cloud.dc.Vlan.VlanType;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InternalErrorException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.network.IPAddressVO;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
public class AssociateIPAddrCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmd.class.getName());
private static final String s_name = "associateipaddressresponse";
private static final List<Pair<Enum, Boolean>> s_properties = new ArrayList<Pair<Enum, Boolean>>();
static {
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.DOMAIN_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.USER_ID, Boolean.FALSE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ZONE_ID, Boolean.TRUE));
s_properties.add(new Pair<Enum, Boolean>(BaseCmd.Properties.ONE_TO_ONE_NAT, Boolean.FALSE));
}
public String getName() {
return s_name;
}
public static String getResultObjectName() {
return "addressinfo";
}
public List<Pair<Enum, Boolean>> getProperties() {
return s_properties;
}
@Override
public List<Pair<String, Object>> execute(Map<String, Object> params) {
Long zoneId = (Long)params.get(BaseCmd.Properties.ZONE_ID.getName());
Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName());
Long userId = (Long)params.get(BaseCmd.Properties.USER_ID.getName());
String accountName = (String)params.get(BaseCmd.Properties.ACCOUNT.getName());
Long domainId = (Long)params.get(BaseCmd.Properties.DOMAIN_ID.getName());
String newIpAddr = null;
String errorDesc = null;
Long accountId = null;
boolean isAdmin = false;
if ((account == null) || isAdmin(account.getType())) {
isAdmin = true;
if (domainId != null) {
if ((account != null) && !getManagementServer().isChildDomain(account.getDomainId(), domainId)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid domain id (" + domainId + ") given, unable to associate IP address.");
}
if (accountName != null) {
Account userAccount = getManagementServer().findAccountByName(accountName, domainId);
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new ServerApiException(BaseCmd.ACCOUNT_ERROR, "Unable to find account " + accountName + " in domain " + domainId);
}
}
} else if (account != null) {
// the admin is acquiring an IP address
accountId = account.getId();
domainId = account.getDomainId();
} else {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Account information is not specified.");
}
} else {
accountId = account.getId();
domainId = account.getDomainId();
}
if (userId == null) {
userId = Long.valueOf(1);
}
try {
newIpAddr = getManagementServer().associateIpAddress(userId.longValue(), accountId.longValue(), domainId.longValue(), zoneId.longValue());
} catch (ResourceAllocationException rae) {
if (rae.getResourceType().equals("vm")) throw new ServerApiException (BaseCmd.VM_ALLOCATION_ERROR, rae.getMessage());
else if (rae.getResourceType().equals("ip")) throw new ServerApiException (BaseCmd.IP_ALLOCATION_ERROR, rae.getMessage());
} catch (InvalidParameterValueException ex1) {
s_logger.error("error associated IP Address with userId: " + userId, ex1);
throw new ServerApiException (BaseCmd.NET_INVALID_PARAM_ERROR, ex1.getMessage());
} catch (InsufficientAddressCapacityException ex2) {
throw new ServerApiException (BaseCmd.NET_IP_ASSOC_ERROR, ex2.getMessage());
} catch (InternalErrorException ex3){
throw new ServerApiException (BaseCmd.NET_IP_ASSOC_ERROR, ex3.getMessage());
} catch (Exception ex4) {
throw new ServerApiException (BaseCmd.NET_IP_ASSOC_ERROR, "Unable to associate IP address");
}
if (newIpAddr == null) {
s_logger.warn("unable to associate IP address for user " + ((errorDesc != null) ? (", reason: " + errorDesc) : null));
throw new ServerApiException(BaseCmd.NET_IP_ASSOC_ERROR, "unable to associate IP address for user " + ((errorDesc != null) ? (", reason: " + errorDesc) : null));
}
List<Pair<String, Object>> embeddedObject = new ArrayList<Pair<String, Object>>();
List<Pair<String, Object>> returnValues = new ArrayList<Pair<String, Object>>();
try {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.IP_ADDRESS.getName(), newIpAddr));
List<IPAddressVO> ipAddresses = getManagementServer().listPublicIpAddressesBy(accountId.longValue(), true, null, null);
IPAddressVO ipAddress = null;
for (Iterator<IPAddressVO> iter = ipAddresses.iterator(); iter.hasNext();) {
IPAddressVO current = iter.next();
if (current.getAddress().equals(newIpAddr)) {
ipAddress = current;
break;
}
}
if (ipAddress == null) {
return returnValues;
}
if (ipAddress.getAllocated() != null) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ALLOCATED.getName(), getDateString(ipAddress.getAllocated())));
}
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_ID.getName(), Long.valueOf(ipAddress.getDataCenterId()).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ZONE_NAME.getName(), getManagementServer().findDataCenterById(ipAddress.getDataCenterId()).getName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.IS_SOURCE_NAT.getName(), Boolean.valueOf(ipAddress.isSourceNat()).toString()));
//get account information
Account accountTemp = getManagementServer().findAccountById(ipAddress.getAccountId());
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.ACCOUNT.getName(), accountTemp.getAccountName()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN_ID.getName(), accountTemp.getDomainId()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.DOMAIN.getName(), getManagementServer().findDomainIdById(accountTemp.getDomainId()).getName()));
VlanVO vlan = getManagementServer().findVlanById(ipAddress.getVlanDbId());
boolean forVirtualNetworks = vlan.getVlanType().equals(VlanType.VirtualNetwork);
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.FOR_VIRTUAL_NETWORK.getName(), forVirtualNetworks));
//show this info to admin only
if (isAdmin == true) {
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.VLAN_DB_ID.getName(), Long.valueOf(ipAddress.getVlanDbId()).toString()));
returnValues.add(new Pair<String, Object>(BaseCmd.Properties.VLAN_ID.getName(), vlan.getVlanId()));
}
embeddedObject.add(new Pair<String, Object>("publicipaddress", new Object[] { returnValues } ));
} catch (Exception ex) {
s_logger.error("error!", ex);
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal Error encountered while assigning IP address " + newIpAddr + " to account " + accountId);
}
return embeddedObject;
}
}
|
package gruppn.kasslr;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import gruppn.kasslr.model.VocabularyItem;
public class GalleryFragment extends Fragment {
private static final String DEBUG_TAG = "GalleryFragment";
private static final FileFilter FILTER = new FileFilter() {
@Override
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".jpg");
}
};
private Kasslr app;
private GridView gridGallery;
private int itemCount = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
app = (Kasslr) getActivity().getApplication();
gridGallery = (GridView) getActivity().findViewById(R.id.grid_gallery_photos);
gridGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
VocabularyItem item = (VocabularyItem) adapterView.getItemAtPosition(i);
app.setSharedBitmap(((BitmapDrawable) ((ImageView) view).getDrawable()).getBitmap());
Intent intent = new Intent(getActivity(), EditItemActivity.class);
intent.putExtra(EditItemActivity.EXTRA_ITEM_INDEX, app.getShelf().getItems().indexOf(item));
String transition = getString(R.string.transition_add_word);
ActivityOptionsCompat options = ActivityOptionsCompat
.makeSceneTransitionAnimation(getActivity(), view, transition);
ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
}
});
}
@Override
public void onResume() {
super.onResume();
// Populate gallery
loadItems();
}
private void loadItems() {
if (itemCount != app.getShelf().getItems().size()) {
new LoadItemsTask().execute(app.getShelf().getItems());
}
}
private class ItemAdapter extends BaseAdapter {
private Context mContext;
private VocabularyItem[] mItems;
public ItemAdapter(Context c, VocabularyItem[] items) {
mContext = c;
mItems = items;
}
@Override
public int getCount() {
return mItems.length;
}
@Override
public VocabularyItem getItem(int position) {
return mItems[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
int width;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
width = ((GridView) parent).getColumnWidth();
} else {
width = parent.getWidth() / ((GridView) parent).getNumColumns() - R.dimen.gallery_spacing;
}
int height = width * 4 / 3;
ImageView imageView;
if (view == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(width, height));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.setTransitionName(getString(R.string.transition_add_word));
}
} else {
imageView = (ImageView) view;
}
File imageFile = app.getImageFile(mItems[position]);
Picasso.with(mContext).load(imageFile).fit().into(imageView);
return imageView;
}
}
private class LoadItemsTask extends AsyncTask<List<VocabularyItem>, Void, ItemAdapter> {
@Override
protected ItemAdapter doInBackground(List<VocabularyItem>... lists) {
if (lists.length == 0) {
Log.e(DEBUG_TAG, "No list supplied to LoadItemsTask");
return null;
}
// Get last modified date for each item
final List<VocabularyItem> itemList = lists[0];
VocabularyItem[] items = itemList.toArray(new VocabularyItem[itemList.size()]);
final long[] lastModified = new long[items.length];
for (int i = 0; i < items.length; i++) {
lastModified[i] = app.getImageFile(items[i]).lastModified();
}
// Sort items by date
Log.d(DEBUG_TAG, "Start sorting items");
Arrays.sort(items, new Comparator<VocabularyItem>() {
@Override
public int compare(VocabularyItem x, VocabularyItem y) {
long a = lastModified[itemList.indexOf(x)];
long b = lastModified[itemList.indexOf(y)];
return a == b ? 0 : a > b ? 1 : -1;
}
});
Log.d(DEBUG_TAG, "Finished sorting items");
return new ItemAdapter(getActivity(), items);
}
@Override
protected void onPostExecute(ItemAdapter itemAdapter) {
if (itemAdapter != null) {
gridGallery.setAdapter(itemAdapter);
itemCount = itemAdapter.getCount();
}
}
}
}
|
package com.example.beer;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
public class BeerController {
private BeerRepository repository;
public BeerController(BeerRepository repository) {
this.repository = repository;
}
@GetMapping("/good-beers")
@CrossOrigin(origins = "http://localhost:4200")
public Collection<Beer> goodBeers() {
return repository.findAll().stream()
.filter(this::isGreat)
.collect(Collectors.toList());
}
private boolean isGreat(Beer beer) {
return !beer.getName().equals("Budweiser") &&
!beer.getName().equals("Coors Light") &&
!beer.getName().equals("PBR");
}
}
|
package org.gluu.oxtrust.util;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.gluu.oxtrust.ldap.service.AttributeService;
import org.gluu.oxtrust.ldap.service.GroupService;
import org.gluu.oxtrust.ldap.service.IGroupService;
import org.gluu.oxtrust.ldap.service.IPersonService;
import org.gluu.oxtrust.ldap.service.OrganizationService;
import org.gluu.oxtrust.ldap.service.PersonService;
import org.gluu.oxtrust.model.GluuCustomPerson;
import org.gluu.oxtrust.model.GluuGroup;
import org.gluu.oxtrust.model.scim.ScimCustomAttributes;
import org.gluu.oxtrust.model.scim.ScimData;
import org.gluu.oxtrust.model.scim.ScimEntitlements;
import org.gluu.oxtrust.model.scim.ScimEntitlementsPatch;
import org.gluu.oxtrust.model.scim.ScimGroup;
import org.gluu.oxtrust.model.scim.ScimGroupMembers;
import org.gluu.oxtrust.model.scim.ScimPerson;
import org.gluu.oxtrust.model.scim.ScimPersonAddresses;
import org.gluu.oxtrust.model.scim.ScimPersonAddressesPatch;
import org.gluu.oxtrust.model.scim.ScimPersonEmails;
import org.gluu.oxtrust.model.scim.ScimPersonEmailsPatch;
import org.gluu.oxtrust.model.scim.ScimPersonGroups;
import org.gluu.oxtrust.model.scim.ScimPersonGroupsPatch;
import org.gluu.oxtrust.model.scim.ScimPersonIms;
import org.gluu.oxtrust.model.scim.ScimPersonImsPatch;
import org.gluu.oxtrust.model.scim.ScimPersonPatch;
import org.gluu.oxtrust.model.scim.ScimPersonPhones;
import org.gluu.oxtrust.model.scim.ScimPersonPhonesPatch;
import org.gluu.oxtrust.model.scim.ScimPersonPhotos;
import org.gluu.oxtrust.model.scim.ScimPersonPhotosPatch;
import org.gluu.oxtrust.model.scim.ScimRoles;
import org.gluu.oxtrust.model.scim.ScimRolesPatch;
import org.gluu.oxtrust.model.scim.Scimx509Certificates;
import org.gluu.oxtrust.model.scim.Scimx509CertificatesPatch;
import org.hibernate.internal.util.StringHelper;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.log.Log;
import org.xdi.ldap.model.GluuBoolean;
import org.xdi.ldap.model.GluuStatus;
import org.xdi.model.GluuAttribute;
@Name("copyUtils")
public class CopyUtils implements Serializable {
private static final String GLUU_STATUS = "gluuStatus";
private static final String OX_TRUST_PHOTOS_TYPE = "oxTrustPhotosType";
private static final String OX_TRUST_PHONE_TYPE = "oxTrustPhoneType";
private static final String OX_TRUST_ADDRESS_PRIMARY = "oxTrustAddressPrimary";
private static final String OX_TRUST_ADDRESS_TYPE = "oxTrustAddressType";
private static final String OX_TRUST_COUNTRY = "oxTrustCountry";
private static final String OX_TRUST_POSTAL_CODE = "oxTrustPostalCode";
private static final String OX_TRUST_REGION = "oxTrustRegion";
private static final String OX_TRUST_LOCALITY = "oxTrustLocality";
private static final String OX_TRUST_ADDRESS_FORMATTED = "oxTrustAddressFormatted";
private static final String OX_TRUST_STREET = "oxTrustStreet";
private static final String OX_TRUST_EMAIL_PRIMARY = "oxTrustEmailPrimary";
private static final String OX_TRUST_EMAIL_TYPE = "oxTrustEmailType";
private static final String OX_TRUST_META_LOCATION = "oxTrustMetaLocation";
private static final String OX_TRUST_META_VERSION = "oxTrustMetaVersion";
private static final String OX_TRUST_META_LAST_MODIFIED = "oxTrustMetaLastModified";
private static final String OX_TRUST_META_CREATED = "oxTrustMetaCreated";
private static final String OX_TRUSTX509_CERTIFICATE = "oxTrustx509Certificate";
private static final String OX_TRUST_ENTITLEMENTS = "oxTrustEntitlements";
private static final String OX_TRUST_ROLE = "oxTrustRole";
private static final String OX_TRUST_ACTIVE = "oxTrustActive";
private static final String OX_TRUST_LOCALE = "locale";
private static final String OX_TRUST_TITLE = "oxTrustTitle";
private static final String OX_TRUST_USER_TYPE = "oxTrustUserType";
private static final String OX_TRUST_PHOTOS = "oxTrustPhotos";
private static final String OX_TRUST_IMS_VALUE = "oxTrustImsValue";
private static final String OX_TRUST_PHONE_VALUE = "oxTrustPhoneValue";
private static final String OX_TRUST_ADDRESSES = "oxTrustAddresses";
private static final String OX_TRUST_EMAIL = "oxTrustEmail";
private static final String OX_TRUST_PROFILE_URL = "oxTrustProfileURL";
private static final String OX_TRUST_NICK_NAME = "nickName";
private static final String OX_TRUST_EXTERNAL_ID = "oxTrustExternalId";
private static final String OX_TRUSTHONORIFIC_SUFFIX = "oxTrusthonorificSuffix";
private static final String OX_TRUSTHONORIFIC_PREFIX = "oxTrusthonorificPrefix";
private static final String OX_TRUST_MIDDLE_NAME = "middleName";
private static final long serialVersionUID = -1715995162448707004L;
@Logger
private static Log log;
/**
* Copy data from ScimPerson object to GluuCustomPerson object "Reda"
*
* @param source
* @param destination
* @return
* @throws Exception
*/
public static GluuCustomPerson copy(ScimPerson source, GluuCustomPerson destination, boolean isUpdate) throws Exception {
if (source == null || !isValidData(source, isUpdate)) {
return null;
}
IPersonService personService1 = PersonService.instance();
if (destination == null) {
log.trace(" creating a new GluuCustomPerson instant ");
destination = new GluuCustomPerson();
}
if (isUpdate) {
personService1.addCustomObjectClass(destination);
if (StringUtils.isNotEmpty(source.getUserName())) {
log.trace(" setting userName ");
destination.setUid(source.getUserName());
}
if (StringUtils.isNotEmpty(source.getName().getGivenName())) {
log.trace(" setting givenname ");
destination.setGivenName(source.getName().getGivenName());
}
if (StringUtils.isNotEmpty(source.getName().getFamilyName())) {
log.trace(" setting familyname ");
destination.setSurname(source.getName().getFamilyName());
}
if (StringUtils.isNotEmpty(source.getDisplayName())) {
log.trace(" setting displayname ");
destination.setDisplayName(source.getDisplayName());
}
setOrRemoveOptionalAttribute(destination, source.getName().getMiddleName(), OX_TRUST_MIDDLE_NAME);
setOrRemoveOptionalAttribute(destination, source.getName().getHonorificPrefix(), OX_TRUSTHONORIFIC_PREFIX);
setOrRemoveOptionalAttribute(destination, source.getName().getHonorificSuffix(), OX_TRUSTHONORIFIC_SUFFIX);
setOrRemoveOptionalAttribute(destination, source.getExternalId(), OX_TRUST_EXTERNAL_ID);
setOrRemoveOptionalAttribute(destination, source.getNickName(), OX_TRUST_NICK_NAME);
setOrRemoveOptionalAttribute(destination, source.getProfileUrl(), OX_TRUST_PROFILE_URL);
setOrRemoveOptionalAttributeList(destination, source.getEmails(), OX_TRUST_EMAIL);
setOrRemoveOptionalAttributeList(destination, source.getAddresses(), OX_TRUST_ADDRESSES);
setOrRemoveOptionalAttributeList(destination, source.getPhoneNumbers(), OX_TRUST_PHONE_VALUE);
setOrRemoveOptionalAttributeList(destination, source.getIms(), OX_TRUST_IMS_VALUE);
setOrRemoveOptionalAttributeList(destination, source.getPhotos(), OX_TRUST_PHOTOS);
setOrRemoveOptionalAttribute(destination, source.getUserType(), OX_TRUST_USER_TYPE);
setOrRemoveOptionalAttribute(destination, source.getTitle(), OX_TRUST_TITLE);
if (source.getPreferredLanguage() != null && source.getPreferredLanguage().length() > 0) {
destination.setPreferredLanguage(source.getPreferredLanguage());
}
setOrRemoveOptionalAttribute(destination, source.getLocale(), OX_TRUST_LOCALE);
if (source.getTimezone() != null && source.getTimezone().length() > 0) {
destination.setTimezone(source.getTimezone());
}
setOrRemoveOptionalAttribute(destination, source.getActive(), OX_TRUST_ACTIVE);
if (StringUtils.isNotEmpty(source.getPassword())) {
destination.setUserPassword(source.getPassword());
}
setGroups(source, destination);
setOrRemoveOptionalAttributeList(destination, source.getRoles(), OX_TRUST_ROLE);
setOrRemoveOptionalAttributeList(destination, source.getEntitlements(), OX_TRUST_ENTITLEMENTS);
setOrRemoveOptionalAttributeList(destination, source.getX509Certificates(), OX_TRUSTX509_CERTIFICATE);
setMetaData(source, destination);
// getting customAttributes
log.trace("getting custom attributes");
if (source.getCustomAttributes() != null) {
log.trace("source.getCustomAttributes() != null");
log.trace("getting a list of ScimCustomAttributes");
List<ScimCustomAttributes> customAttr = source.getCustomAttributes();
log.trace("checking every attribute in the request");
for (ScimCustomAttributes oneAttr : customAttr) {
if (oneAttr == null) {
continue;
}
int countValues = oneAttr.getValues().size();
if (countValues == 0) {
log.trace("setting a empty attribute");
destination.setAttribute(oneAttr.getName().replaceAll(" ", ""), oneAttr.getValues().toArray(new String[0]));
} else if (countValues == 1) {
log.trace("setting a single attribute");
destination.setAttribute(oneAttr.getName().replaceAll(" ", ""), oneAttr.getValues().get(0));
} else if (countValues > 1) {
log.trace("setting a multivalued attribute");
List<String> listOfAttr = oneAttr.getValues();
String[] AttrArray = new String[listOfAttr.size()];
int i = 0;
for (String oneValue : listOfAttr) {
if (oneValue != null && oneValue.length() > 0) {
log.trace("setting a value");
AttrArray[i] = oneValue;
i++;
}
}
log.trace("setting the list of multivalued attributes");
destination.setAttribute(oneAttr.getName().replaceAll(" ", ""), AttrArray);
}
}
}
} else {
try {
if (personService1.getPersonByUid(source.getUserName()) != null) {
return null;
}
personService1.addCustomObjectClass(destination);
log.trace(" setting userName ");
if (source.getUserName() != null && source.getUserName().length() > 0) {
destination.setUid(source.getUserName());
}
log.trace(" setting givenname ");
if (source.getName().getGivenName() != null && source.getName().getGivenName().length() > 0) {
destination.setGivenName(source.getName().getGivenName());
}
log.trace(" setting famillyname ");
if (source.getName().getFamilyName() != null && source.getName().getFamilyName().length() > 0) {
destination.setSurname(source.getName().getFamilyName());
}
log.trace(" setting displayname ");
if (source.getDisplayName() != null && source.getDisplayName().length() > 0) {
destination.setDisplayName(source.getDisplayName());
}
setOrRemoveOptionalAttribute(destination, source.getName().getMiddleName(), OX_TRUST_MIDDLE_NAME);
setOrRemoveOptionalAttribute(destination, source.getName().getHonorificPrefix(), OX_TRUSTHONORIFIC_PREFIX);
setOrRemoveOptionalAttribute(destination, source.getName().getHonorificSuffix(), OX_TRUSTHONORIFIC_SUFFIX);
setOrRemoveOptionalAttribute(destination, source.getExternalId(), OX_TRUST_EXTERNAL_ID);
setOrRemoveOptionalAttribute(destination, source.getNickName(), OX_TRUST_NICK_NAME);
setOrRemoveOptionalAttribute(destination, source.getProfileUrl(), OX_TRUST_PROFILE_URL);
setOrRemoveOptionalAttributeList(destination, source.getEmails(), OX_TRUST_EMAIL);
setOrRemoveOptionalAttributeList(destination, source.getAddresses(), OX_TRUST_ADDRESSES);
setOrRemoveOptionalAttributeList(destination, source.getPhoneNumbers(), OX_TRUST_PHONE_VALUE);
setOrRemoveOptionalAttributeList(destination, source.getIms(), OX_TRUST_IMS_VALUE);
setOrRemoveOptionalAttributeList(destination, source.getPhotos(), OX_TRUST_PHOTOS);
setOrRemoveOptionalAttribute(destination, source.getUserType(), OX_TRUST_USER_TYPE);
setOrRemoveOptionalAttribute(destination, source.getTitle(), OX_TRUST_TITLE);
if (source.getPreferredLanguage() != null && source.getPreferredLanguage().length() > 0) {
destination.setPreferredLanguage(source.getPreferredLanguage());
}
setOrRemoveOptionalAttribute(destination, source.getLocale(), OX_TRUST_LOCALE);
if (source.getTimezone() != null && source.getTimezone().length() > 0) {
destination.setTimezone(source.getTimezone());
}
setOrRemoveOptionalAttribute(destination, source.getActive(), OX_TRUST_ACTIVE);
if (source.getPassword() != null && source.getPassword().length() > 0) {
destination.setUserPassword(source.getPassword());
}
setGroups(source, destination);
setOrRemoveOptionalAttributeList(destination, source.getRoles(), OX_TRUST_ROLE);
setOrRemoveOptionalAttributeList(destination, source.getEntitlements(), OX_TRUST_ENTITLEMENTS);
setOrRemoveOptionalAttributeList(destination, source.getX509Certificates(), OX_TRUSTX509_CERTIFICATE);
setMetaData(source, destination);
// getting customAttributes
log.trace("getting custom attributes");
if (source.getCustomAttributes() != null && source.getCustomAttributes().size() > 0) {
log.trace("source.getCustomAttributes() != null");
log.trace("getting a list of ScimCustomAttributes");
List<ScimCustomAttributes> customAttr = source.getCustomAttributes();
log.trace("checking every attribute in the request");
for (ScimCustomAttributes oneAttr : customAttr) {
if (oneAttr != null && oneAttr.getValues().size() == 1) {
log.trace("setting a single attribute");
destination.setAttribute(oneAttr.getName().replaceAll(" ", ""), oneAttr.getValues().get(0));
} else if (oneAttr != null && oneAttr.getValues().size() > 1) {
log.trace("setting a multivalued attribute");
List<String> listOfAttr = oneAttr.getValues();
String[] AttrArray = new String[listOfAttr.size()];
int i = 0;
for (String oneValue : listOfAttr) {
if (oneValue != null && oneValue.length() > 0) {
log.trace("setting a value");
AttrArray[i] = oneValue;
i++;
}
}
log.trace("setting the list of multivalued attributes");
destination.setAttribute(oneAttr.getName().replaceAll(" ", ""), AttrArray);
}
}
}
} catch (Exception ex) {
return null;
}
}
setGluuStatus(source, destination);
return destination;
}
private static void setGroups(ScimPerson source, GluuCustomPerson destination) {
log.trace(" setting groups ");
if (source.getGroups() != null && source.getGroups().size() > 0) {
IGroupService groupService = GroupService.instance();
List<ScimPersonGroups> listGroups = source.getGroups();
List<String> members = new ArrayList<String>();
for (ScimPersonGroups group : listGroups) {
members.add(groupService.getDnForGroup(group.getValue()));
}
destination.setMemberOf(members);
}
}
private static void setMetaData(ScimPerson source, GluuCustomPerson destination) {
log.trace(" setting meta ");
if (source.getMeta().getCreated() != null && source.getMeta().getCreated().length() > 0) {
destination.setAttribute(OX_TRUST_META_CREATED, source.getMeta().getCreated());
}
if (source.getMeta().getLastModified() != null && source.getMeta().getLastModified().length() > 0) {
destination.setAttribute(OX_TRUST_META_LAST_MODIFIED, source.getMeta().getLastModified());
}
if (source.getMeta().getVersion() != null && source.getMeta().getVersion().length() > 0) {
destination.setAttribute(OX_TRUST_META_VERSION, source.getMeta().getVersion());
}
if (source.getMeta().getLocation() != null && source.getMeta().getLocation().length() > 0) {
destination.setAttribute(OX_TRUST_META_LOCATION, source.getMeta().getLocation());
}
}
private static void setOrRemoveOptionalAttributeList(GluuCustomPerson destination, List<?> items, String attributeName)
throws JsonGenerationException, JsonMappingException, IOException {
if (items == null) {
log.trace(" removing " + attributeName);
destination.removeAttribute(attributeName);
} else {
log.trace(" setting " + attributeName);
StringWriter listOfItems = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(listOfItems, items);
destination.setAttribute(attributeName, listOfItems.toString());
}
}
private static void setOrRemoveOptionalAttribute(GluuCustomPerson destination, String attributevalue, String attributeName) {
if (attributevalue == null) {
log.trace(" removing " + attributeName);
destination.removeAttribute(attributeName);
} else {
log.trace(" setting " + attributeName);
destination.setAttribute(attributeName, attributevalue);
}
}
/**
* Copy data from GluuCustomPerson object to ScimPerson object "Reda"
*
* @param source
* @param destination
* @return
* @throws Exception
*/
public static ScimPerson copy(GluuCustomPerson source, ScimPerson destination) throws Exception {
if (source == null) {
return null;
}
if (destination == null) {
log.trace(" creating a new GluuCustomPerson instant ");
destination = new ScimPerson();
}
destination.getSchemas().add("urn:scim2:schemas:core:1.0");
log.trace(" setting ID ");
if (source.getInum() != null) {
destination.setId(source.getInum());
}
log.trace(" setting userName ");
if (source.getUid() != null) {
destination.setUserName(source.getUid());
}
log.trace(" setting ExternalID ");
if (source.getAttribute(OX_TRUST_EXTERNAL_ID) != null) {
destination.setExternalId(source.getAttribute(OX_TRUST_EXTERNAL_ID));
}
log.trace(" setting givenname ");
if (source.getGivenName() != null) {
destination.getName().setGivenName(source.getGivenName());
}
log.trace(" getting family name ");
if (source.getSurname() != null) {
destination.getName().setFamilyName(source.getSurname());
}
log.trace(" getting middlename ");
if (source.getAttribute(OX_TRUST_MIDDLE_NAME) != null) {
destination.getName().setMiddleName(source.getAttribute(OX_TRUST_MIDDLE_NAME));
}
;
log.trace(" getting honorificPrefix ");
if (source.getAttribute(OX_TRUSTHONORIFIC_PREFIX) != null) {
destination.getName().setHonorificPrefix(source.getAttribute(OX_TRUSTHONORIFIC_PREFIX));
}
;
log.trace(" getting honorificSuffix ");
if (source.getAttribute(OX_TRUSTHONORIFIC_SUFFIX) != null) {
destination.getName().setHonorificSuffix(source.getAttribute(OX_TRUSTHONORIFIC_SUFFIX));
}
;
log.trace(" getting displayname ");
if (source.getDisplayName() != null) {
destination.setDisplayName(source.getDisplayName());
}
log.trace(" getting nickname ");
if (source.getAttribute(OX_TRUST_NICK_NAME) != null) {
destination.setNickName(source.getAttribute(OX_TRUST_NICK_NAME));
}
log.trace(" getting profileURL ");
if (source.getAttribute(OX_TRUST_PROFILE_URL) != null) {
destination.setProfileUrl(source.getAttribute(OX_TRUST_PROFILE_URL));
}
log.trace(" getting emails ");
// getting emails
if (source.getAttribute(OX_TRUST_EMAIL) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimPersonEmails> listOfEmails = mapper.readValue(source.getAttribute(OX_TRUST_EMAIL),
new TypeReference<List<ScimPersonEmails>>() {
});
/*
* List<ScimPersonEmails> emails = new
* ArrayList<ScimPersonEmails>(); String[] listEmails =
* source.getAttributes("oxTrustEmail"); String[] listEmailTyps =
* source.getAttributes("oxTrustEmailType"); String[]
* listEmailPrimary = source.getAttributes("oxTrustEmailPrimary");
* for(int i = 0 ; i<listEmails.length ; i++ ){ ScimPersonEmails
* oneEmail = new ScimPersonEmails();
* oneEmail.setValue(listEmails[i]);
* oneEmail.setType(listEmailTyps[i]);
* oneEmail.setPrimary(listEmailPrimary[i]); emails.add(oneEmail); }
*/
destination.setEmails(listOfEmails);
}
log.trace(" getting addresses ");
// getting addresses
if (source.getAttribute(OX_TRUST_ADDRESSES) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimPersonAddresses> listOfAddresses = mapper.readValue(source.getAttribute(OX_TRUST_ADDRESSES),
new TypeReference<List<ScimPersonAddresses>>() {
});
/*
* List<ScimPersonAddresses> addresses = new
* ArrayList<ScimPersonAddresses>(); String[] listStreets =
* source.getAttributes("oxTrustStreet"); String[] listAddressTypes
* = source.getAttributes("oxTrustAddressType"); String[]
* listLocalities = source.getAttributes("oxTrustLocality");
* String[] listRegions = source.getAttributes("oxTrustRegion");
* String[] listPostalCodes =
* source.getAttributes("oxTrustPostalCode"); String[] listCountries
* = source.getAttributes("oxTrustCountry"); String[]
* listAddressFormatted =
* source.getAttributes("oxTrustAddressFormatted"); String[]
* listAddressPrimary =
* source.getAttributes("oxTrustAddressPrimary");
* if(listStreets.length > 0){ for(int i = 0 ; i <
* listStreets.length ; i++ ){ ScimPersonAddresses address = new
* ScimPersonAddresses();
*
* if(!listAddressFormatted[i].equalsIgnoreCase("empty")){address.
* setFormatted
* (listAddressFormatted[i]);}else{address.setFormatted("");}
* if(!listStreets
* [i].equalsIgnoreCase("empty")){address.setStreetAddress
* (listStreets[i]);}else{address.setStreetAddress("");}
* if(!listAddressTypes
* [i].equalsIgnoreCase("empty")){address.setType
* (listAddressTypes[i]);}else{address.setType("");}
* if(!listLocalities
* [i].equalsIgnoreCase("empty")){address.setLocality
* (listLocalities[i]);}else{address.setLocality("");}
* if(!listRegions
* [i].equalsIgnoreCase("empty")){address.setRegion(listRegions
* [i]);}else{address.setRegion("");}
* if(!listPostalCodes[i].equalsIgnoreCase
* ("empty")){address.setPostalCode
* (listPostalCodes[i]);}else{address.setPostalCode("");}
* if(!listCountries
* [i].equalsIgnoreCase("empty")){address.setCountry
* (listCountries[i]);}else{address.setCountry("");}
* if(!listAddressPrimary
* [i].equalsIgnoreCase("empty")){address.setPrimary
* (listAddressPrimary[i]);}else{address.setPrimary("");}
* addresses.add(address);
*
* } }
*/
destination.setAddresses(listOfAddresses);
}
log.trace(" setting phoneNumber ");
// getting user's PhoneNumber
if (source.getAttribute(OX_TRUST_PHONE_VALUE) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimPersonPhones> listOfPhones = mapper.readValue(source.getAttribute(OX_TRUST_PHONE_VALUE),
new TypeReference<List<ScimPersonPhones>>() {
});
/*
* List<ScimPersonPhones> phones = new
* ArrayList<ScimPersonPhones>(); String[] listNumbers =
* source.getAttributes("oxTrustPhoneValue"); String[]
* listPhoneTypes = source.getAttributes("oxTrustPhoneType");
* if(listNumbers.length > 0){ for(int i = 0 ; i <
* listNumbers.length ; i++){ ScimPersonPhones phone = new
* ScimPersonPhones();
* if(!listNumbers[i].equalsIgnoreCase("empty")){
* phone.setValue(listNumbers[i]);}else{phone.setValue("");}
* if(!listPhoneTypes
* [i].equalsIgnoreCase("empty")){phone.setType(listPhoneTypes
* [i]);}else{phone.setType("");} phones.add(phone);
*
* } }
*/
destination.setPhoneNumbers(listOfPhones);
}
log.trace(" getting ims ");
// getting ims
if (source.getAttribute(OX_TRUST_IMS_VALUE) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimPersonIms> listOfIms = mapper.readValue(source.getAttribute(OX_TRUST_IMS_VALUE),
new TypeReference<List<ScimPersonIms>>() {
});
/*
* List<ScimPersonIms> ims = new ArrayList<ScimPersonIms>();
* String[] imValues = source.getAttributes("oxTrustImsValue");
* String[] imTypes = source.getAttributes("oxTrustImsType");
* if(imValues.length > 0){ for(int i = 0 ; i < imValues.length ;
* i++){ ScimPersonIms im = new ScimPersonIms(); if(imValues[i] !=
* null){im.setValue(imValues[i]);im.setType(imTypes[i]);}
* ims.add(im); } }
*/
destination.setIms(listOfIms);
}
log.trace(" setting photos ");
// getting photos
if (source.getAttribute(OX_TRUST_PHOTOS) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimPersonPhotos> listOfPhotos = mapper.readValue(source.getAttribute(OX_TRUST_PHOTOS),
new TypeReference<List<ScimPersonPhotos>>() {
});
/*
* List<ScimPersonPhotos> photos = new
* ArrayList<ScimPersonPhotos>(); String[] photoList =
* source.getAttributes("oxTrustPhotos"); String[] photoTypes =
* source.getAttributes("oxTrustPhotosType");
*
* if(photoList.length > 0){ for(int i = 0 ; i < photoList.length ;
* i++){
*
* ScimPersonPhotos photo = new ScimPersonPhotos(); if(photoList[i]
* !=
* null){photo.setValue(photoList[i]);photo.setType(photoTypes[i]);}
* photos.add(photo); } }
*/
destination.setPhotos(listOfPhotos);
}
log.trace(" setting userType ");
if (source.getAttribute(OX_TRUST_USER_TYPE) != null) {
destination.setUserType(source.getAttribute(OX_TRUST_USER_TYPE));
}
log.trace(" setting title ");
if (source.getAttribute(OX_TRUST_TITLE) != null) {
destination.setTitle(source.getAttribute(OX_TRUST_TITLE));
}
log.trace(" setting Locale ");
if (source.getAttribute(OX_TRUST_LOCALE) != null) {
destination.setLocale(source.getAttribute(OX_TRUST_LOCALE));
}
log.trace(" setting preferredLanguage ");
if (source.getPreferredLanguage() != null) {
destination.setPreferredLanguage(source.getPreferredLanguage());
}
log.trace(" setting timeZone ");
if (source.getTimezone() != null) {
destination.setTimezone(source.getTimezone());
}
log.trace(" setting active ");
if (source.getAttribute(OX_TRUST_ACTIVE) != null) {
destination.setActive(source.getAttribute(OX_TRUST_ACTIVE));
}
log.trace(" setting password ");
destination.setPassword("Hidden for Privacy Reasons");
// getting user groups
log.trace(" setting groups ");
if (source.getMemberOf() != null) {
IGroupService groupService = GroupService.instance();
List<String> listOfGroups = source.getMemberOf();
List<ScimPersonGroups> groupsList = new ArrayList<ScimPersonGroups>();
for (String groupDN : listOfGroups) {
ScimPersonGroups group = new ScimPersonGroups();
GluuGroup gluuGroup = groupService.getGroupByDn(groupDN);
group.setValue(gluuGroup.getInum());
group.setDisplay(gluuGroup.getDisplayName());
groupsList.add(group);
}
destination.setGroups(groupsList);
}
// getting roles
if (source.getAttribute(OX_TRUST_ROLE) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimRoles> listOfRoles = mapper.readValue(source.getAttribute(OX_TRUST_ROLE),
new TypeReference<List<ScimRoles>>() {
});
/*
* List<ScimRoles> roles = new ArrayList<ScimRoles>(); String[]
* listRoles = source.getAttributes("oxTrustRole");
* if(listRoles.length > 0){ for(int i = 0 ; i < listRoles.length
* ;i++){ ScimRoles role = new ScimRoles(); if(listRoles[i] !=
* null){role.setValue(listRoles[i]);} roles.add(role); } }
*/
destination.setRoles(listOfRoles);
}
log.trace(" getting entilements ");
// getting entitlements
if (source.getAttribute(OX_TRUST_ENTITLEMENTS) != null) {
ObjectMapper mapper = new ObjectMapper();
List<ScimEntitlements> listOfEnts = mapper.readValue(source.getAttribute(OX_TRUST_ENTITLEMENTS),
new TypeReference<List<ScimEntitlements>>() {
});
/*
* List<ScimEntitlements> entitlements = new
* ArrayList<ScimEntitlements>(); String[] listEntitlements =
* source.getAttributes("oxTrustEntitlements");
* if(listEntitlements.length > 0){ for(int i = 0 ; i <
* listEntitlements.length ; i++ ){ ScimEntitlements ent = new
* ScimEntitlements(); if(listEntitlements[i] !=
* null){ent.setValue(listEntitlements[i]);} entitlements.add(ent);
* } }
*/
destination.setEntitlements(listOfEnts);
}
// getting x509Certificates
log.trace(" setting certs ");
if (source.getAttribute(OX_TRUSTX509_CERTIFICATE) != null) {
ObjectMapper mapper = new ObjectMapper();
List<Scimx509Certificates> listOfCerts = mapper.readValue(source.getAttribute(OX_TRUSTX509_CERTIFICATE),
new TypeReference<List<Scimx509Certificates>>() {
});
/*
* List<Scimx509Certificates> certificates = new
* ArrayList<Scimx509Certificates>(); String[] listCertif =
* source.getAttributes("oxTrustx509Certificate");
* if(listCertif.length > 0){ for(int i = 0 ; i < listCertif.length
* ; i++){ Scimx509Certificates cert = new Scimx509Certificates();
* if(listCertif[i] != null){cert.setValue(listCertif[i]);}
* certificates.add(cert);
*
* } }
*/
destination.setX509Certificates(listOfCerts);
}
log.trace(" setting meta ");
// getting meta data
if (source.getAttribute(OX_TRUST_META_CREATED) != null) {
destination.getMeta().setCreated(source.getAttribute(OX_TRUST_META_CREATED));
}
if (source.getAttribute(OX_TRUST_META_LAST_MODIFIED) != null) {
destination.getMeta().setLastModified(source.getAttribute(OX_TRUST_META_LAST_MODIFIED));
}
if (source.getAttribute(OX_TRUST_META_VERSION) != null) {
destination.getMeta().setVersion(source.getAttribute(OX_TRUST_META_VERSION));
}
if (source.getAttribute(OX_TRUST_META_LOCATION) != null) {
destination.getMeta().setLocation(source.getAttribute(OX_TRUST_META_LOCATION));
}
log.trace(" getting custom Attributes ");
// getting custom Attributes
AttributeService attributeService = AttributeService.instance();
List<GluuAttribute> listOfAttr = attributeService.getSCIMRelatedAttributes();
if (listOfAttr != null && listOfAttr.size() > 0) {
List<ScimCustomAttributes> listOfCustomAttr = new ArrayList<ScimCustomAttributes>();
for (GluuAttribute attr : listOfAttr) {
boolean isEmpty = attr.getOxMultivaluedAttribute() == null;
if (!isEmpty && attr.getOxMultivaluedAttribute().getValue().equalsIgnoreCase("true")) {
boolean isAttrEmpty = source.getAttributes(attr.getName()) == null;
if (!isAttrEmpty) {
String[] arrayValues = source.getAttributes(attr.getName());
List<String> values = new ArrayList<String>(Arrays.asList(arrayValues));
ScimCustomAttributes scimAttr = new ScimCustomAttributes();
scimAttr.setName(attr.getName());
scimAttr.setValues(values);
listOfCustomAttr.add(scimAttr);
}
} else {
boolean isAttrEmpty = source.getAttributes(attr.getName()) == null;
if (!isAttrEmpty) {
List<String> values = new ArrayList<String>();
values.add(source.getAttribute(attr.getName()));
ScimCustomAttributes scimAttr = new ScimCustomAttributes();
scimAttr.setName(attr.getName());
scimAttr.setValues(values);
listOfCustomAttr.add(scimAttr);
}
}
}
if (listOfCustomAttr.size() > 0) {
destination.setCustomAttributes(listOfCustomAttr);
}
}
log.trace(" returning destination ");
return destination;
}
public static boolean isValidData(ScimPerson person, boolean isUpdate) {
if (isUpdate) {
// if (isEmpty(person.getFirstName()) ||
// isEmpty(person.getDisplayName())
// || isEmpty(person.getLastName())
// || isEmpty(person.getEmail())) {
// return false;
} else if (isEmpty(person.getUserName()) || isEmpty(person.getName().getGivenName()) || isEmpty(person.getDisplayName())
|| isEmpty(person.getName().getFamilyName())
// || (person.getEmails() == null || person.getEmails().size() <
|| isEmpty(person.getPassword())) {
return false;
}
return true;
}
public static boolean isEmpty(String value) {
if (value == null || value.trim().equals(""))
return true;
return false;
}
/**
* Copy data from GluuGroup object to ScimGroup object
*
* @param source
* @param destination
* @return
* @throws Exception
*/
public static ScimGroup copy(GluuGroup source, ScimGroup destination) throws Exception {
if (source == null) {
return null;
}
if (destination == null) {
destination = new ScimGroup();
}
IPersonService personService = PersonService.instance();
List<String> schemas = new ArrayList<String>();
schemas.add("urn:scim2:schemas:core:1.0");
destination.setSchemas(schemas);
destination.setDisplayName(source.getDisplayName());
destination.setId(source.getInum());
if (source.getMembers() != null) {
if (source.getMembers().size() != 0) {
List<ScimGroupMembers> members = new ArrayList<ScimGroupMembers>();
List<String> membersList = source.getMembers();
for (String oneMember : membersList) {
ScimGroupMembers member = new ScimGroupMembers();
GluuCustomPerson person = personService.getPersonByDn(oneMember);
member.setValue(person.getInum());
member.setDisplay(person.getDisplayName());
members.add(member);
}
destination.setMembers(members);
}
}
return destination;
}
public static GluuCustomPerson patch(ScimPersonPatch source, GluuCustomPerson destination, boolean isUpdate) throws Exception {
if (source == null || !isValidData(source, isUpdate)) {
return null;
}
if (destination == null) {
log.trace(" creating a new Scimperson instant ");
destination = new GluuCustomPerson();
}
log.trace(" setting userName ");
log.trace(" source.getUserName() :" + source.getUserName() + "h");
log.trace(" userName length : " + source.getUserName().length());
if (source.getUserName() != null && source.getUserName().length() > 0) {
destination.setUid(source.getUserName());
}
log.trace(" setting givenname ");
if (source.getName().getGivenName() != null && source.getName().getGivenName().length() > 0) {
destination.setGivenName(source.getName().getGivenName());
}
log.trace(" setting famillyname ");
if (source.getName().getFamilyName() != null && source.getName().getGivenName().length() > 0) {
destination.setSurname(source.getName().getFamilyName());
}
log.trace(" setting middlename ");
if (source.getName().getMiddleName() != null && source.getName().getMiddleName().length() > 0) {
destination.setAttribute(OX_TRUST_MIDDLE_NAME, source.getName().getMiddleName());
}
log.trace(" setting honor");
if (source.getName().getHonorificPrefix() != null && source.getName().getHonorificPrefix().length() > 0) {
destination.setAttribute(OX_TRUSTHONORIFIC_PREFIX, source.getName().getHonorificPrefix());
}
if (source.getName().getHonorificSuffix() != null && source.getName().getHonorificSuffix().length() > 0) {
destination.setAttribute(OX_TRUSTHONORIFIC_SUFFIX, source.getName().getHonorificSuffix());
}
log.trace(" setting displayname ");
if (source.getDisplayName() != null && source.getDisplayName().length() > 0) {
destination.setDisplayName(source.getDisplayName());
}
log.trace(" setting externalID ");
if (source.getExternalId() != null && source.getExternalId().length() > 0) {
destination.setAttribute(OX_TRUST_EXTERNAL_ID, source.getExternalId());
}
log.trace(" setting nickname ");
if (source.getNickName() != null && source.getNickName().length() > 0) {
destination.setAttribute(OX_TRUST_NICK_NAME, source.getNickName());
}
log.trace(" setting profileURL ");
if (source.getProfileUrl() != null && source.getProfileUrl().length() > 0) {
destination.setAttribute(OX_TRUST_PROFILE_URL, source.getProfileUrl());
}
// getting emails
log.trace(" setting emails ");
if (source.getEmails() != null && source.getEmails().size() > 0) {
List<ScimPersonEmailsPatch> emails = source.getEmails();
String[] emailsList = new String[source.getEmails().size()];
String[] emailsTypes = new String[source.getEmails().size()];
String[] emailsPrimary = new String[source.getEmails().size()];
int emailsSize = 0;
if (destination.getAttributes(OX_TRUST_EMAIL) != null && destination.getAttributes(OX_TRUST_EMAIL).length > 0) {
emailsList = destination.getAttributes(OX_TRUST_EMAIL);
emailsTypes = destination.getAttributes(OX_TRUST_EMAIL_TYPE);
emailsPrimary = destination.getAttributes(OX_TRUST_EMAIL_PRIMARY);
// emailsSize =
// destination.getAttributes("oxTrustEmail").length;
}
boolean emailIsFound = false;
while (emailIsFound != true) {
if (emails.get(0).getPrimary() == "true") {
for (String oneEmail : emailsList) {
if (oneEmail == emails.get(0).getValue()) {
if (emails.get(0).getPrimary() != null && emails.get(0).getPrimary().length() > 0) {
emailsPrimary[emailsSize] = emails.get(0).getPrimary();
}
emailIsFound = true;
}
emailsSize++;
}
emailsSize = 0;
for (String onePrimary : emailsPrimary) {
if (onePrimary == emails.get(0).getPrimary()) {
if (emails.get(0).getPrimary() != null && emails.get(0).getPrimary().length() > 0) {
emailsPrimary[emailsSize] = "false";
}
}
emailsSize++;
}
if (emails.get(0).getValue() != null && emails.get(0).getValue().length() > 0) {
emailsList[emailsSize] = emails.get(0).getValue();
}
if (emails.get(0).getType() != null && emails.get(0).getType().length() > 0) {
emailsTypes[emailsSize] = emails.get(0).getType();
}
if (emails.get(0).getPrimary() != null && emails.get(0).getPrimary().length() > 0) {
emailsPrimary[emailsSize] = emails.get(0).getPrimary();
}
emailIsFound = true;
}
if (emails.get(0).getPrimary() == "false") {
emailsSize = emailsList.length;
if (emails.get(0).getValue() != null && emails.get(0).getValue().length() > 0) {
emailsList[emailsSize] = emails.get(0).getValue();
}
if (emails.get(0).getType() != null && emails.get(0).getType().length() > 0) {
emailsTypes[emailsSize] = emails.get(0).getType();
}
if (emails.get(0).getPrimary() != null && emails.get(0).getPrimary().length() > 0) {
emailsPrimary[emailsSize] = emails.get(0).getPrimary();
}
emailIsFound = true;
}
}
destination.setAttribute(OX_TRUST_EMAIL, emailsList);
destination.setAttribute(OX_TRUST_EMAIL_TYPE, emailsTypes);
destination.setAttribute(OX_TRUST_EMAIL_PRIMARY, emailsPrimary);
}
// getting addresses
log.trace(" settting addresses ");
if (source.getAddresses() != null && source.getAddresses().size() == 2) {
List<ScimPersonAddressesPatch> addresses = source.getAddresses();
String[] street = new String[source.getAddresses().size()];
String[] formatted = new String[source.getAddresses().size()];
String[] locality = new String[source.getAddresses().size()];
String[] region = new String[source.getAddresses().size()];
String[] postalCode = new String[source.getAddresses().size()];
String[] country = new String[source.getAddresses().size()];
String[] addressType = new String[source.getAddresses().size()];
String[] addressPrimary = new String[source.getAddresses().size()];
int addressSize = 0;
if (destination.getAttributes(OX_TRUST_STREET) != null && destination.getAttributes(OX_TRUST_STREET).length > 0) {
street = destination.getAttributes(OX_TRUST_STREET);
formatted = destination.getAttributes(OX_TRUST_ADDRESS_FORMATTED);
locality = destination.getAttributes(OX_TRUST_LOCALITY);
region = destination.getAttributes(OX_TRUST_REGION);
postalCode = destination.getAttributes(OX_TRUST_POSTAL_CODE);
country = destination.getAttributes(OX_TRUST_COUNTRY);
addressType = destination.getAttributes(OX_TRUST_ADDRESS_TYPE);
addressPrimary = destination.getAttributes(OX_TRUST_ADDRESS_PRIMARY);
// addressSize =
// destination.getAttributes("oxTrustStreet").length;
}
for (String oneStreet : street) {
if (oneStreet == addresses.get(0).getStreetAddress()) {
if (addresses.get(1).getStreetAddress() != null && addresses.get(1).getStreetAddress().length() > 0) {
street[addressSize] = addresses.get(1).getStreetAddress();
}
if (addresses.get(1).getFormatted() != null && addresses.get(1).getFormatted().length() > 0) {
formatted[addressSize] = addresses.get(1).getFormatted();
}
if (addresses.get(1).getLocality() != null && addresses.get(1).getLocality().length() > 0) {
locality[addressSize] = addresses.get(1).getLocality();
}
if (addresses.get(1).getRegion() != null && addresses.get(1).getRegion().length() > 0) {
region[addressSize] = addresses.get(1).getRegion();
}
if (addresses.get(1).getPostalCode() != null && addresses.get(1).getPostalCode().length() > 0) {
postalCode[addressSize] = addresses.get(1).getPostalCode();
}
if (addresses.get(1).getCountry() != null && addresses.get(1).getCountry().length() > 0) {
country[addressSize] = addresses.get(1).getCountry();
}
if (addresses.get(1).getType() != null && addresses.get(1).getType().length() > 0) {
addressType[addressSize] = addresses.get(1).getType();
}
if (addresses.get(1).getPrimary() != null && addresses.get(1).getPrimary().length() > 0) {
addressPrimary[addressSize] = addresses.get(1).getPrimary();
}
}
addressSize++;
}
destination.setAttribute(OX_TRUST_STREET, street);
destination.setAttribute(OX_TRUST_LOCALITY, locality);
destination.setAttribute(OX_TRUST_REGION, region);
destination.setAttribute(OX_TRUST_POSTAL_CODE, postalCode);
destination.setAttribute(OX_TRUST_COUNTRY, country);
destination.setAttribute(OX_TRUST_ADDRESS_FORMATTED, formatted);
destination.setAttribute(OX_TRUST_ADDRESS_PRIMARY, addressPrimary);
destination.setAttribute(OX_TRUST_ADDRESS_TYPE, addressType);
}
// getting phone numbers;
log.trace(" setting phoneNumbers ");
if (source.getPhoneNumbers() != null && source.getPhoneNumbers().size() > 0) {
List<ScimPersonPhonesPatch> phones = source.getPhoneNumbers();
String[] phoneNumber = new String[source.getPhoneNumbers().size()];
String[] phoneType = new String[source.getPhoneNumbers().size()];
int phoneSize = 0;
if (destination.getAttributes(OX_TRUST_PHONE_VALUE) != null && destination.getAttributes(OX_TRUST_PHONE_VALUE).length > 0) {
phoneNumber = destination.getAttributes(OX_TRUST_PHONE_VALUE);
phoneType = destination.getAttributes(OX_TRUST_PHONE_TYPE);
// phoneSize =
// destination.getAttributes("oxTrustPhoneValue").length;
}
for (ScimPersonPhones phone : phones) {
if (phone.getValue() != null && phone.getValue().length() > 0) {
phoneNumber[phoneSize] = phone.getValue();
}
if (phone.getType() != null && phone.getType().length() > 0) {
phoneType[phoneSize] = phone.getType();
}
phoneSize++;
}
destination.setAttribute(OX_TRUST_PHONE_VALUE, phoneNumber);
destination.setAttribute(OX_TRUST_PHONE_TYPE, phoneType);
}
// getting ims
log.trace(" setting ims ");
if (source.getIms() != null && source.getIms().size() > 0) {
List<ScimPersonImsPatch> ims = source.getIms();
String[] imValue = new String[source.getIms().size()];
String[] imType = new String[source.getIms().size()];
int imSize = 0;
if (destination.getAttributes(OX_TRUST_IMS_VALUE) != null && destination.getAttributes(OX_TRUST_IMS_VALUE).length > 0) {
imValue = destination.getAttributes(OX_TRUST_IMS_VALUE);
imType = destination.getAttributes("oxTrustImsType");
imSize = destination.getAttributes(OX_TRUST_IMS_VALUE).length;
}
for (ScimPersonIms im : ims) {
if (im.getValue() != null && im.getValue().length() > 0) {
imValue[imSize] = im.getValue();
}
if (im.getType() != null && im.getType().length() > 0) {
imType[imSize] = im.getType();
}
imSize++;
}
destination.setAttribute(OX_TRUST_IMS_VALUE, imValue);
destination.setAttribute("oxTrustImsType", imType);
}
// getting Photos
log.trace(" setting photos ");
if (source.getPhotos() != null && source.getPhotos().size() > 0) {
List<ScimPersonPhotosPatch> photos = source.getPhotos();
String[] photoType = new String[source.getPhotos().size()];
String[] photoValue = new String[source.getPhotos().size()];
int photoSize = 0;
if (destination.getAttributes(OX_TRUST_PHOTOS) != null && destination.getAttributes(OX_TRUST_PHOTOS).length > 0) {
photoType = destination.getAttributes(OX_TRUST_PHOTOS_TYPE);
photoValue = destination.getAttributes(OX_TRUST_PHOTOS);
photoSize = destination.getAttributes(OX_TRUST_PHOTOS_TYPE).length;
}
for (ScimPersonPhotos photo : photos) {
if (photo.getType() != null && photo.getType().length() > 0) {
photoType[photoSize] = photo.getType();
}
if (photo.getValue() != null && photo.getValue().length() > 0) {
photoValue[photoSize] = photo.getValue();
}
photoSize++;
}
destination.setAttribute(OX_TRUST_PHOTOS_TYPE, photoType);
destination.setAttribute(OX_TRUST_PHOTOS, photoValue);
}
if (source.getUserType() != null && source.getUserType().length() > 0) {
destination.setAttribute(OX_TRUST_USER_TYPE, source.getUserType());
}
if (source.getTitle() != null && source.getTitle().length() > 0) {
destination.setAttribute(OX_TRUST_TITLE, source.getTitle());
}
if (source.getPreferredLanguage() != null && source.getPreferredLanguage().length() > 0) {
destination.setPreferredLanguage(source.getPreferredLanguage());
}
if (source.getLocale() != null && source.getLocale().length() > 0) {
destination.setAttribute(OX_TRUST_LOCALE, source.getLocale());
}
if (source.getTimezone() != null && source.getTimezone().length() > 0) {
destination.setTimezone(source.getTimezone());
}
if (source.getActive() != null && source.getActive().length() > 0) {
destination.setAttribute(OX_TRUST_ACTIVE, source.getActive());
}
if (source.getPassword() != null && source.getPassword().length() > 0) {
destination.setUserPassword(source.getPassword());
}
// getting user groups
log.trace(" setting groups ");
if (source.getGroups() != null && source.getGroups().size() > 0) {
IGroupService groupService = GroupService.instance();
List<ScimPersonGroupsPatch> listGroups = source.getGroups();
List<String> members = new ArrayList<String>();
for (ScimPersonGroups group : listGroups) {
members.add(groupService.getDnForGroup(group.getValue()));
}
destination.setMemberOf(members);
}
// getting roles
log.trace(" setting roles ");
if (source.getRoles() != null && source.getRoles().size() > 0) {
List<ScimRolesPatch> roles = source.getRoles();
String[] scimRole = new String[source.getRoles().size()];
int rolesSize = 0;
if (destination.getAttributes(OX_TRUST_ROLE) != null && destination.getAttributes(OX_TRUST_ROLE).length > 0) {
scimRole = destination.getAttributes(OX_TRUST_ROLE);
rolesSize = destination.getAttributes(OX_TRUST_ROLE).length;
}
for (ScimRoles role : roles) {
if (role.getValue() != null && role.getValue().length() > 0) {
scimRole[rolesSize] = role.getValue();
}
rolesSize++;
}
destination.setAttribute(OX_TRUST_ROLE, scimRole);
}
// getting entitlements
log.trace(" setting entilements ");
if (source.getEntitlements() != null && source.getEntitlements().size() > 0) {
List<ScimEntitlementsPatch> ents = source.getEntitlements();
String[] listEnts = new String[source.getEntitlements().size()];
int entsSize = 0;
if (destination.getAttributes(OX_TRUST_ENTITLEMENTS) != null
&& destination.getAttributes(OX_TRUST_ENTITLEMENTS).length > 0) {
listEnts = destination.getAttributes(OX_TRUST_ENTITLEMENTS);
entsSize = destination.getAttributes(OX_TRUST_ENTITLEMENTS).length;
}
for (ScimEntitlements ent : ents) {
if (ent.getValue() != null && ent.getValue().length() > 0) {
listEnts[entsSize] = ent.getValue();
}
entsSize++;
}
destination.setAttribute(OX_TRUST_ENTITLEMENTS, listEnts);
}
// getting x509Certificates
log.trace(" setting certs ");
if (source.getX509Certificates() != null && source.getX509Certificates().size() > 0) {
List<Scimx509CertificatesPatch> certs = source.getX509Certificates();
String[] listCerts = new String[source.getX509Certificates().size()];
int certsSize = 0;
if (destination.getAttributes(OX_TRUSTX509_CERTIFICATE) != null
&& destination.getAttributes(OX_TRUSTX509_CERTIFICATE).length > 0) {
listCerts = destination.getAttributes(OX_TRUSTX509_CERTIFICATE);
certsSize = destination.getAttributes(OX_TRUSTX509_CERTIFICATE).length;
}
for (Scimx509Certificates cert : certs) {
if (cert.getValue() != null && cert.getValue().length() > 0) {
listCerts[certsSize] = cert.getValue();
}
certsSize++;
}
destination.setAttribute(OX_TRUSTX509_CERTIFICATE, listCerts);
}
// getting meta
log.trace(" setting meta ");
if (source.getMeta().getCreated() != null && source.getMeta().getCreated().length() > 0) {
destination.setAttribute(OX_TRUST_META_CREATED, source.getMeta().getCreated());
}
if (source.getMeta().getLastModified() != null && source.getMeta().getLastModified().length() > 0) {
destination.setAttribute(OX_TRUST_META_LAST_MODIFIED, source.getMeta().getLastModified());
}
if (source.getMeta().getVersion() != null && source.getMeta().getVersion().length() > 0) {
destination.setAttribute(OX_TRUST_META_VERSION, source.getMeta().getVersion());
}
if (source.getMeta().getLocation() != null && source.getMeta().getLocation().length() > 0) {
destination.setAttribute(OX_TRUST_META_LOCATION, source.getMeta().getLocation());
}
setGluuStatus(source, destination);
return destination;
}
private static boolean isValidData(ScimPersonPatch person, boolean isUpdate) {
if (isUpdate) {
// if (isEmpty(person.getFirstName()) ||
// isEmpty(person.getDisplayName())
// || isEmpty(person.getLastName())
// || isEmpty(person.getEmail())) {
// return false;
} else if (isEmpty(person.getUserName()) || isEmpty(person.getName().getGivenName()) || isEmpty(person.getDisplayName())
|| isEmpty(person.getName().getFamilyName())
// || (person.getEmails() == null || person.getEmails().size() <
|| isEmpty(person.getPassword())) {
return false;
}
return true;
}
/**
* Copy data from ScimGroup object to GluuGroupn object
*
* @param source
* @param destination
* @param isUpdate
* @return
* @throws IOException
* @throws JsonMappingException
* @throws JsonGenerationException
* @throws Exception
*/
public static GluuGroup copy(ScimGroup source, GluuGroup destination, boolean isUpdate) throws Exception {
if (source == null || !isValidData(source, isUpdate)) {
return null;
}
if (destination == null) {
log.trace(" creating a new GluuGroup instant ");
destination = new GluuGroup();
}
if (isUpdate) {
if (source.getDisplayName() != null && source.getDisplayName().length() > 0) {
destination.setDisplayName(source.getDisplayName());
}
if (source.getMembers() != null && source.getMembers().size() > 0) {
IPersonService personService = PersonService.instance();
List<ScimGroupMembers> members = source.getMembers();
List<String> listMembers = new ArrayList<String>();
for (ScimGroupMembers member : members) {
listMembers.add(personService.getDnForPerson(member.getValue()));
}
destination.setMembers(listMembers);
}
} else {
log.trace(" creating a new GroupService instant ");
IGroupService groupService1 = GroupService.instance();
log.trace(" source.getDisplayName() : ", source.getDisplayName());
if (groupService1.getGroupByDisplayName(source.getDisplayName()) != null) {
log.trace(" groupService1.getGroupByDisplayName(source.getDisplayName() != null : ");
return null;
}
if (source.getDisplayName() != null && source.getDisplayName().length() > 0) {
destination.setDisplayName(source.getDisplayName());
}
log.trace(" source.getMembers() : ", source.getMembers());
log.trace(" source.getMembers().size() : ", source.getMembers().size());
if (source.getMembers() != null && source.getMembers().size() > 0) {
IPersonService personService = PersonService.instance();
List<ScimGroupMembers> members = source.getMembers();
List<String> listMembers = new ArrayList<String>();
for (ScimGroupMembers member : members) {
listMembers.add(personService.getDnForPerson(member.getValue()));
}
destination.setMembers(listMembers);
}
destination.setStatus(GluuStatus.ACTIVE);
OrganizationService orgService = OrganizationService.instance();
destination.setOrganization(orgService.getDnForOrganization());
}
return destination;
}
public static boolean isValidData(ScimGroup group, boolean isUpdate) {
if (isUpdate) {
} else if (isEmpty(group.getDisplayName())) {
return false;
}
return true;
}
/**
* Copy data from ScimData object to ScimGroup object
*
* @param source
* @param destination
* @return ScimGroup
* @throws Exception
*/
public static ScimGroup copy(ScimData source, ScimGroup destination) {
if (source == null) {
return null;
}
if (destination == null) {
destination = new ScimGroup();
}
if (source.getId() != null && source.getId().length() > 0) {
destination.setId(source.getId());
}
if (source.getDisplayName() != null && source.getDisplayName().length() > 0) {
destination.setDisplayName(source.getDisplayName());
}
if (source.getSchemas() != null && source.getSchemas().size() > 0) {
destination.setSchemas(source.getSchemas());
}
if (source.getMembers() != null && source.getMembers().size() > 0) {
destination.setMembers(source.getMembers());
}
return destination;
}
private static void setGluuStatus(ScimPerson source, GluuCustomPerson destination) {
String active = source.getActive();
setGluuStatus(destination, active);
}
private static void setGluuStatus(ScimPersonPatch source, GluuCustomPerson destination) {
String active = source.getActive();
setGluuStatus(destination, active);
}
private static void setGluuStatus(GluuCustomPerson destination, String active) {
if (StringHelper.isNotEmpty(active) && (destination.getAttribute(GLUU_STATUS) == null)) {
GluuBoolean gluuStatus = GluuBoolean.getByValue(org.xdi.util.StringHelper.toLowerCase(active));
if (gluuStatus != null) {
destination.setAttribute(GLUU_STATUS, gluuStatus.getValue());
}
}
}
}
|
package com.intellij.execution.console;
import com.intellij.AppTopics;
import com.intellij.CommonBundle;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.execution.console.ConsoleHistoryModel.Entry;
import com.intellij.ide.scratch.ScratchFileService;
import com.intellij.idea.ActionsBundle;
import com.intellij.lang.Language;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoConstants;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.actions.ContentChooser;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileDocumentManagerListener;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.SafeWriteRequestor;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.encoding.EncodingRegistry;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PathUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
/**
* @author gregsh
*/
public class ConsoleHistoryController implements Disposable {
private static final Logger LOG = Logger.getInstance("com.intellij.execution.console.ConsoleHistoryController");
private final static Map<LanguageConsoleView, ConsoleHistoryController> ourControllers =
ContainerUtil.createConcurrentWeakMap(ContainerUtil.identityStrategy());
private final LanguageConsoleView myConsole;
private final AnAction myHistoryNext = new MyAction(true, getKeystrokesUpDown(true));
private final AnAction myHistoryPrev = new MyAction(false, getKeystrokesUpDown(false));
private final AnAction myBrowseHistory = new MyBrowseAction();
private boolean myMultiline;
private ModelHelper myHelper;
private long myLastSaveStamp;
@Deprecated
public ConsoleHistoryController(@NotNull String type, @Nullable String persistenceId, @NotNull LanguageConsoleView console) {
this(new ConsoleRootType(type, null) { }, persistenceId, console);
}
public ConsoleHistoryController(@NotNull ConsoleRootType rootType, @Nullable String persistenceId, @NotNull LanguageConsoleView console) {
this(rootType, fixNullPersistenceId(persistenceId, console), console,
ConsoleHistoryModelProvider.findModelForConsole(fixNullPersistenceId(persistenceId, console), console));
}
private ConsoleHistoryController(@NotNull ConsoleRootType rootType, @NotNull String persistenceId,
@NotNull LanguageConsoleView console, @NotNull ConsoleHistoryModel model) {
myHelper = new ModelHelper(rootType, persistenceId, model);
myConsole = console;
}
@TestOnly
public void setModel(@NotNull ConsoleHistoryModel model){
myHelper = new ModelHelper(myHelper.myRootType, myHelper.myId, model);
}
@Override
public void dispose() {
}
//@Nullable
public static ConsoleHistoryController getController(@NotNull LanguageConsoleView console) {
return ourControllers.get(console);
}
public static void addToHistory(@NotNull LanguageConsoleView consoleView, @Nullable String command) {
ConsoleHistoryController controller = getController(consoleView);
if (controller != null) {
controller.addToHistory(command);
}
}
public void addToHistory(@Nullable String command) {
getModel().addToHistory(command);
}
public boolean hasHistory() {
return !getModel().isEmpty();
}
@NotNull
private static String fixNullPersistenceId(@Nullable String persistenceId, @NotNull LanguageConsoleView console) {
if (StringUtil.isNotEmpty(persistenceId)) return persistenceId;
String url = console.getProject().getPresentableUrl();
return StringUtil.isNotEmpty(url) ? url : "default";
}
public boolean isMultiline() {
return myMultiline;
}
public ConsoleHistoryController setMultiline(boolean multiline) {
myMultiline = multiline;
return this;
}
ConsoleHistoryModel getModel() {
return myHelper.getModel();
}
public void install() {
MessageBusConnection busConnection = myConsole.getProject().getMessageBus().connect(myConsole);
busConnection.subscribe(ProjectEx.ProjectSaved.TOPIC, new ProjectEx.ProjectSaved() {
@Override
public void duringSave(@NotNull Project project) {
ApplicationManager.getApplication().invokeAndWait(() -> saveHistory());
}
});
busConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerListener() {
@Override
public void beforeDocumentSaving(@NotNull Document document) {
if (document == myConsole.getEditorDocument()) {
saveHistory();
}
}
});
ConsoleHistoryController original = ourControllers.put(myConsole, this);
LOG.assertTrue(original == null,
"History controller already installed for: " + myConsole.getTitle());
Disposer.register(myConsole, this);
Disposer.register(this, new Disposable() {
@Override
public void dispose() {
ConsoleHistoryController controller = getController(myConsole);
if (controller == ConsoleHistoryController.this) {
ourControllers.remove(myConsole);
}
saveHistory();
}
});
if (myHelper.getModel().getHistorySize() == 0) {
loadHistory(myHelper.getId());
}
configureActions();
myLastSaveStamp = getCurrentTimeStamp();
}
private long getCurrentTimeStamp() {
return getModel().getModificationCount() + myConsole.getEditorDocument().getModificationStamp();
}
private void configureActions() {
EmptyAction.setupAction(myHistoryNext, "Console.History.Next", null);
EmptyAction.setupAction(myHistoryPrev, "Console.History.Previous", null);
EmptyAction.setupAction(myBrowseHistory, "Console.History.Browse", null);
if (!myMultiline) {
addShortcuts(myHistoryNext, getShortcutUpDown(true));
addShortcuts(myHistoryPrev, getShortcutUpDown(false));
}
myHistoryNext.registerCustomShortcutSet(myHistoryNext.getShortcutSet(), myConsole.getCurrentEditor().getComponent());
myHistoryPrev.registerCustomShortcutSet(myHistoryPrev.getShortcutSet(), myConsole.getCurrentEditor().getComponent());
myBrowseHistory.registerCustomShortcutSet(myBrowseHistory.getShortcutSet(), myConsole.getCurrentEditor().getComponent());
}
/**
* Use this method if you decided to change the id for your console but don't want your users to loose their current histories
* @param id previous id id
* @return true if some text has been loaded; otherwise false
*/
public boolean loadHistory(String id) {
CharSequence prev = myHelper.getContent();
boolean result = myHelper.loadHistory(id);
CharSequence userValue = myHelper.getContent();
if (prev != userValue && userValue != null) {
setConsoleText(new Entry(userValue, -1), false, false);
}
return result;
}
private void saveHistory() {
if (myLastSaveStamp == getCurrentTimeStamp()) {
return;
}
myHelper.setContent(myConsole.getEditorDocument().getText());
myHelper.saveHistory();
myLastSaveStamp = getCurrentTimeStamp();
}
public AnAction getHistoryNext() {
return myHistoryNext;
}
public AnAction getHistoryPrev() {
return myHistoryPrev;
}
public AnAction getBrowseHistory() {
return myBrowseHistory;
}
protected void setConsoleText(final Entry command, final boolean storeUserText, final boolean regularMode) {
if (regularMode && myMultiline && StringUtil.isEmptyOrSpaces(command.getText())) return;
final Editor editor = myConsole.getCurrentEditor();
final Document document = editor.getDocument();
WriteCommandAction.writeCommandAction(myConsole.getProject()).run(() -> {
if (storeUserText) {
String text = document.getText();
if (Comparing.equal(command.getText(), text) && myHelper.getContent() != null) return;
myHelper.setContent(text);
myHelper.getModel().setContent(text);
}
CharSequence text = ObjectUtils.chooseNotNull(command.getText(), "");
int offset;
if (regularMode) {
if (myMultiline) {
offset = insertTextMultiline(text, editor, document);
}
else {
document.setText(text);
offset = command.getOffset() == -1 ? document.getTextLength() : command.getOffset();
}
}
else {
offset = 0;
try {
document.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
document.setText(text);
}
finally {
document.putUserData(UndoConstants.DONT_RECORD_UNDO, null);
}
}
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
});
}
protected int insertTextMultiline(CharSequence text, Editor editor, Document document) {
TextRange selection = EditorUtil.getSelectionInAnyMode(editor);
int start = document.getLineStartOffset(document.getLineNumber(selection.getStartOffset()));
int end = document.getLineEndOffset(document.getLineNumber(selection.getEndOffset()));
document.replaceString(start, end, text);
editor.getSelectionModel().setSelection(start, start + text.length());
return start;
}
private class MyAction extends DumbAwareAction {
private final boolean myNext;
@NotNull
private final Collection<KeyStroke> myUpDownKeystrokes;
MyAction(final boolean next, @NotNull Collection<KeyStroke> upDownKeystrokes) {
myNext = next;
myUpDownKeystrokes = upDownKeystrokes;
getTemplatePresentation().setVisible(false);
}
@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
boolean hasHistory = getModel().hasHistory(); // need to check before next line's side effect
Entry command = myNext ? getModel().getHistoryNext() : getModel().getHistoryPrev();
if (!myMultiline && command == null || !hasHistory && !myNext) return;
setConsoleText(command, !hasHistory, true);
}
@Override
public void update(@NotNull final AnActionEvent e) {
super.update(e);
boolean enabled = myMultiline || !isUpDownKey(e) || canMoveInEditor(myNext);
//enabled &= getModel().hasHistory(myNext);
e.getPresentation().setEnabled(enabled);
}
private boolean isUpDownKey(@NotNull AnActionEvent e) {
final InputEvent event = e.getInputEvent();
if (!(event instanceof KeyEvent)) {
return false;
}
final KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent((KeyEvent)event);
return myUpDownKeystrokes.contains(keyStroke);
}
}
private boolean canMoveInEditor(final boolean next) {
final Editor consoleEditor = myConsole.getCurrentEditor();
final Document document = consoleEditor.getDocument();
final CaretModel caretModel = consoleEditor.getCaretModel();
if (LookupManager.getActiveLookup(consoleEditor) != null) return false;
if (next) {
return document.getLineNumber(caretModel.getOffset()) == 0;
}
else {
final int lineCount = document.getLineCount();
return (lineCount == 0 || document.getLineNumber(caretModel.getOffset()) == lineCount - 1) &&
(StringUtil.isEmptyOrSpaces(document.getText().substring(caretModel.getOffset())) || myHelper.getModel().prevOnLastLine());
}
}
private class MyBrowseAction extends DumbAwareAction {
@Override
public void update(@NotNull AnActionEvent e) {
boolean enabled = hasHistory();
e.getPresentation().setEnabled(enabled);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
String title = myConsole.getTitle() + " History";
final ContentChooser<String> chooser = new ContentChooser<String>(myConsole.getProject(), title, true, true) {
{
setOKButtonText(ActionsBundle.actionText(IdeActions.ACTION_EDITOR_PASTE));
setOKButtonMnemonic('P');
setCancelButtonText(CommonBundle.getCloseButtonText());
setUseNumbering(false);
}
@Override
protected void removeContentAt(String content) {
getModel().removeFromHistory(content);
}
@Override
protected String getStringRepresentationFor(String content) {
return content;
}
@NotNull
@Override
protected List<String> getContents() {
return getModel().getEntries();
}
@Override
protected Editor createIdeaEditor(String text) {
PsiFile consoleFile = myConsole.getFile();
Language language = consoleFile.getLanguage();
Project project = consoleFile.getProject();
PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(
"a." + consoleFile.getFileType().getDefaultExtension(),
language,
StringUtil.convertLineSeparators(text), false, true);
VirtualFile virtualFile = psiFile.getViewProvider().getVirtualFile();
if (virtualFile instanceof LightVirtualFile) ((LightVirtualFile)virtualFile).setWritable(false);
Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
EditorFactory editorFactory = EditorFactory.getInstance();
EditorEx editor = (EditorEx)editorFactory.createViewer(document, project);
editor.getSettings().setFoldingOutlineShown(false);
editor.getSettings().setLineMarkerAreaShown(false);
editor.getSettings().setIndentGuidesShown(false);
SyntaxHighlighter highlighter =
SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, psiFile.getViewProvider().getVirtualFile());
editor.setHighlighter(new LexerEditorHighlighter(highlighter, editor.getColorsScheme()));
return editor;
}
};
chooser.setContentIcon(null);
chooser.setSplitterOrientation(false);
chooser.setSelectedIndex(Math.max(0, getModel().getHistorySize() - 1));
if (chooser.showAndGet() && myConsole.getCurrentEditor().getComponent().isShowing()) {
setConsoleText(new Entry(chooser.getSelectedText(), -1), false, true);
}
}
}
public static final class ModelHelper implements SafeWriteRequestor {
private final ConsoleRootType myRootType;
private final String myId;
private final ConsoleHistoryModel myModel;
private CharSequence myContent;
public ModelHelper(ConsoleRootType rootType, String id, ConsoleHistoryModel model) {
myRootType = rootType;
myId = id;
myModel = model;
}
public ConsoleHistoryModel getModel() {
return myModel;
}
public void setContent(String userValue) {
myContent = userValue;
}
public String getId() {
return myId;
}
public CharSequence getContent() {
return myContent;
}
@Nullable
File getFile(String id) {
if (myRootType.isHidden()) return null;
String rootPath = ScratchFileService.getInstance().getRootPath(HistoryRootType.getInstance());
return new File(FileUtil.toSystemDependentName(rootPath + "/" + getHistoryName(myRootType, id)));
}
@NotNull
Charset getCharset() {
return EncodingRegistry.getInstance().getDefaultCharset();
}
public boolean loadHistory(String id) {
try {
File file = getFile(id);
if (file == null || !file.exists()) {
return false;
}
String[] split = FileUtil.loadFile(file, getCharset()).split(myRootType.getEntrySeparator());
getModel().resetEntries(Arrays.asList(split));
return true;
}
catch (Exception ignored) {
return false;
}
}
private void saveHistory() {
if (getModel().isEmpty()) return;
File file = getFile(myId);
if (file == null) return;
File dir = file.getParentFile();
if (dir == null || !dir.mkdirs()) {
LOG.error("Unable to create " + file.getPath());
return;
}
try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), getCharset()))) {
boolean first = true;
for (String entry : getModel().getEntries()) {
if (first) first = false;
else out.write(myRootType.getEntrySeparator());
out.write(entry);
}
out.flush();
}
catch (Exception ex) {
LOG.error(ex);
}
}
}
@NotNull
private static String getHistoryName(@NotNull ConsoleRootType rootType, @NotNull String id) {
return rootType.getConsoleTypeId() + "/" +
PathUtil.makeFileName(rootType.getHistoryPathName(id), rootType.getDefaultFileExtension());
}
@Nullable
public static VirtualFile getContentFile(@NotNull final ConsoleRootType rootType, @NotNull String id, ScratchFileService.Option option) {
final String pathName = PathUtil.makeFileName(rootType.getContentPathName(id), rootType.getDefaultFileExtension());
try {
return rootType.findFile(null, pathName, option);
}
catch (final IOException e) {
LOG.warn(e);
ApplicationManager.getApplication().invokeLater(() -> {
String message = String.format("Unable to open '%s/%s'\nReason: %s", rootType.getId(), pathName, e.getLocalizedMessage());
Messages.showErrorDialog(message, "Unable to Open File");
});
return null;
}
}
private static ShortcutSet getShortcutUpDown(boolean isUp) {
AnAction action = ActionManager.getInstance().getActionOrStub(isUp ?
IdeActions.ACTION_EDITOR_MOVE_CARET_UP :
IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN);
if (action != null) {
return action.getShortcutSet();
}
return new CustomShortcutSet(KeyStroke.getKeyStroke(isUp ? KeyEvent.VK_UP : KeyEvent.VK_DOWN, 0));
}
private static void addShortcuts(@NotNull AnAction action, @NotNull ShortcutSet newShortcuts) {
if (action.getShortcutSet().getShortcuts().length == 0) {
action.registerCustomShortcutSet(newShortcuts, null);
}
else {
action.registerCustomShortcutSet(new CompositeShortcutSet(action.getShortcutSet(), newShortcuts), null);
}
}
private static Collection<KeyStroke> getKeystrokesUpDown(boolean isUp) {
Collection<KeyStroke> result = new ArrayList<>();
final ShortcutSet shortcutSet = getShortcutUpDown(isUp);
for (Shortcut shortcut : shortcutSet.getShortcuts()) {
if (shortcut.isKeyboard() && ((KeyboardShortcut)shortcut).getSecondKeyStroke() == null) {
result.add(((KeyboardShortcut)shortcut).getFirstKeyStroke());
}
}
return result;
}
}
|
package com.intellij.refactoring.safeDelete;
import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter;
import com.intellij.lang.LanguageRefactoringSupport;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.lang.refactoring.RefactoringSupportProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.listeners.RefactoringEventData;
import com.intellij.refactoring.listeners.RefactoringEventListener;
import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteCustomUsageInfo;
import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceSimpleDeleteUsageInfo;
import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceUsageInfo;
import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteUsageInfo;
import com.intellij.refactoring.util.NonCodeSearchDescriptionLocation;
import com.intellij.refactoring.util.RefactoringUIUtil;
import com.intellij.refactoring.util.TextOccurrencesUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageInfoFactory;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.usages.*;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author dsl
*/
public class SafeDeleteProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.safeDelete.SafeDeleteProcessor");
private final PsiElement[] myElements;
private boolean mySearchInCommentsAndStrings;
private boolean mySearchNonJava;
private boolean myPreviewNonCodeUsages = true;
private Runnable myAfterRefactoringCallback;
private SafeDeleteProcessor(Project project, @Nullable Runnable prepareSuccessfulCallback,
PsiElement[] elementsToDelete, boolean isSearchInComments, boolean isSearchNonJava) {
super(project, prepareSuccessfulCallback);
myElements = elementsToDelete;
mySearchInCommentsAndStrings = isSearchInComments;
mySearchNonJava = isSearchNonJava;
}
@Override
@NotNull
protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) {
return new SafeDeleteUsageViewDescriptor(myElements);
}
private static boolean isInside(PsiElement place, PsiElement[] ancestors) {
return isInside(place, Arrays.asList(ancestors));
}
private static boolean isInside(PsiElement place, Collection<? extends PsiElement> ancestors) {
for (PsiElement element : ancestors) {
if (isInside(place, element)) return true;
}
return false;
}
public static boolean isInside (PsiElement place, PsiElement ancestor) {
if (ancestor instanceof PsiDirectoryContainer) {
final PsiDirectory[] directories = ((PsiDirectoryContainer)ancestor).getDirectories(place.getResolveScope());
for (PsiDirectory directory : directories) {
if (isInside(place, directory)) return true;
}
}
if (ancestor instanceof PsiFile) {
for (PsiFile file : ((PsiFile)ancestor).getViewProvider().getAllFiles()) {
if (PsiTreeUtil.isAncestor(file, place, false)) return true;
}
}
boolean isAncestor = PsiTreeUtil.isAncestor(ancestor, place, false);
if (!isAncestor && ancestor instanceof PsiNameIdentifierOwner) {
final PsiElement nameIdentifier = ((PsiNameIdentifierOwner)ancestor).getNameIdentifier();
if (nameIdentifier != null && !PsiTreeUtil.isAncestor(ancestor, nameIdentifier, true)) {
isAncestor = PsiTreeUtil.isAncestor(nameIdentifier.getParent(), place, false);
}
}
if (!isAncestor) {
final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(place.getProject());
PsiLanguageInjectionHost host = injectedLanguageManager.getInjectionHost(place);
while (host != null) {
if (PsiTreeUtil.isAncestor(ancestor, host, false)) {
isAncestor = true;
break;
}
host = injectedLanguageManager.getInjectionHost(host);
}
}
return isAncestor;
}
@Override
@NotNull
protected UsageInfo[] findUsages() {
List<UsageInfo> usages = Collections.synchronizedList(new ArrayList<UsageInfo>());
for (PsiElement element : myElements) {
boolean handled = false;
for(SafeDeleteProcessorDelegate delegate: Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
if (delegate.handlesElement(element)) {
final NonCodeUsageSearchInfo filter = delegate.findUsages(element, myElements, usages);
if (filter != null) {
for(PsiElement nonCodeUsageElement: filter.getElementsToSearch()) {
addNonCodeUsages(nonCodeUsageElement, usages, filter.getInsideDeletedCondition(), mySearchNonJava,
mySearchInCommentsAndStrings);
}
}
handled = true;
break;
}
}
if (!handled && element instanceof PsiNamedElement) {
findGenericElementUsages(element, usages, myElements);
addNonCodeUsages(element, usages, getDefaultInsideDeletedCondition(myElements), mySearchNonJava, mySearchInCommentsAndStrings);
}
}
UsageInfo[] result = usages.toArray(new UsageInfo[usages.size()]);
result = UsageViewUtil.removeDuplicatedUsages(result);
Arrays.sort(result, (o1, o2) -> PsiUtilCore.compareElementsByPosition(o2.getElement(), o1.getElement()));
return result;
}
public static Condition<PsiElement> getDefaultInsideDeletedCondition(final PsiElement[] elements) {
return usage -> !(usage instanceof PsiFile) && isInside(usage, elements);
}
public static void findGenericElementUsages(@NotNull PsiElement element, List<UsageInfo> usages, PsiElement[] allElementsToDelete, SearchScope scope) {
ReferencesSearch.search(element, scope).forEach(reference -> {
final PsiElement refElement = reference.getElement();
if (!isInside(refElement, allElementsToDelete)) {
usages.add(new SafeDeleteReferenceSimpleDeleteUsageInfo(refElement, element, false));
}
return true;
});
}
public static void findGenericElementUsages(final PsiElement element, final List<UsageInfo> usages, final PsiElement[] allElementsToDelete) {
findGenericElementUsages(element, usages, allElementsToDelete, element.getUseScope());
}
@Override
protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
UsageInfo[] usages = refUsages.get();
ArrayList<String> conflicts = new ArrayList<>();
for (PsiElement element : myElements) {
for(SafeDeleteProcessorDelegate delegate: Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
if (delegate.handlesElement(element)) {
Collection<String> foundConflicts = delegate instanceof SafeDeleteProcessorDelegateBase
? ((SafeDeleteProcessorDelegateBase)delegate).findConflicts(element, myElements, usages)
: delegate.findConflicts(element, myElements);
if (foundConflicts != null) {
conflicts.addAll(foundConflicts);
}
break;
}
}
}
if (checkConflicts(usages, conflicts)) return false;
UsageInfo[] preprocessedUsages = usages;
for(SafeDeleteProcessorDelegate delegate: Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages);
if (preprocessedUsages == null) return false;
}
HashSet<UsageInfo> diff = ContainerUtilRt.newHashSet(preprocessedUsages);
diff.removeAll(Arrays.asList(usages));
if (checkConflicts(diff.toArray(UsageInfo.EMPTY_ARRAY), new ArrayList<>())) return false;
final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages);
prepareSuccessful(); // dialog is always dismissed
if(filteredUsages == null) {
return false;
}
refUsages.set(filteredUsages);
return true;
}
private boolean checkConflicts(UsageInfo[] usages, ArrayList<String> conflicts) {
final HashMap<PsiElement,UsageHolder> elementsToUsageHolders = sortUsages(usages);
final Collection<UsageHolder> usageHolders = elementsToUsageHolders.values();
for (UsageHolder usageHolder : usageHolders) {
if (usageHolder.hasUnsafeUsagesInCode()) {
conflicts.add(usageHolder.getDescription());
}
}
if (!conflicts.isEmpty()) {
final RefactoringEventData conflictData = new RefactoringEventData();
conflictData.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts);
myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).conflictsDetected("refactoring.safeDelete", conflictData);
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (!ConflictsInTestsException.isTestIgnore()) throw new ConflictsInTestsException(conflicts);
}
else {
UnsafeUsagesDialog dialog = new UnsafeUsagesDialog(ArrayUtil.toStringArray(conflicts), myProject);
if (!dialog.showAndGet()) {
final int exitCode = dialog.getExitCode();
prepareSuccessful(); // dialog is always dismissed;
if (exitCode == UnsafeUsagesDialog.VIEW_USAGES_EXIT_CODE) {
showUsages(Arrays.stream(usages)
.filter(usage -> usage instanceof SafeDeleteReferenceUsageInfo &&
!((SafeDeleteReferenceUsageInfo)usage).isSafeDelete()).toArray(UsageInfo[]::new),
usages);
}
return true;
}
else {
myPreviewNonCodeUsages = false;
}
}
}
return false;
}
private void showUsages(final UsageInfo[] conflictUsages, final UsageInfo[] usages) {
UsageViewPresentation presentation = new UsageViewPresentation();
presentation.setTabText("Safe Delete Conflicts");
presentation.setTargetsNodeText(RefactoringBundle.message("attempting.to.delete.targets.node.text"));
presentation.setShowReadOnlyStatusAsRed(true);
presentation.setShowCancelButton(true);
presentation.setCodeUsagesString(RefactoringBundle.message("safe.delete.conflict.title"));
presentation.setUsagesInGeneratedCodeString(RefactoringBundle.message("references.found.in.generated.code"));
presentation.setNonCodeUsagesString(RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files"));
presentation.setUsagesString(RefactoringBundle.message("usageView.usagesText"));
UsageViewManager manager = UsageViewManager.getInstance(myProject);
final UsageView usageView = showUsages(conflictUsages, presentation, manager);
usageView.addPerformOperationAction(new RerunSafeDelete(myProject, myElements, usageView),
RefactoringBundle.message("retry.command"), null, RefactoringBundle.message("rerun.safe.delete"));
usageView.addPerformOperationAction(() -> {
UsageInfo[] preprocessedUsages = usages;
for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages);
if (preprocessedUsages == null) return;
}
final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages);
execute(filteredUsages);
}, "Delete Anyway", RefactoringBundle.message("usageView.need.reRun"), RefactoringBundle.message("usageView.doAction"));
}
private UsageView showUsages(UsageInfo[] usages, UsageViewPresentation presentation, UsageViewManager manager) {
for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
if (delegate instanceof SafeDeleteProcessorDelegateBase) {
final UsageView view = ((SafeDeleteProcessorDelegateBase)delegate).showUsages(usages, presentation, manager, myElements);
if (view != null) return view;
}
}
UsageTarget[] targets = new UsageTarget[myElements.length];
for (int i = 0; i < targets.length; i++) {
targets[i] = new PsiElement2UsageTargetAdapter(myElements[i]);
}
return manager.showUsages(targets,
UsageInfoToUsageConverter.convert(myElements, usages),
presentation
);
}
public PsiElement[] getElements() {
return myElements;
}
private static class RerunSafeDelete implements Runnable {
final SmartPsiElementPointer[] myPointers;
private final Project myProject;
private final UsageView myUsageView;
RerunSafeDelete(Project project, PsiElement[] elements, UsageView usageView) {
myProject = project;
myUsageView = usageView;
myPointers = new SmartPsiElementPointer[elements.length];
for (int i = 0; i < elements.length; i++) {
PsiElement element = elements[i];
myPointers[i] = SmartPointerManager.getInstance(myProject).createSmartPsiElementPointer(element);
}
}
@Override
public void run() {
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
myUsageView.close();
ArrayList<PsiElement> elements = new ArrayList<>();
for (SmartPsiElementPointer pointer : myPointers) {
final PsiElement element = pointer.getElement();
if (element != null) {
elements.add(element);
}
}
if(!elements.isEmpty()) {
SafeDeleteHandler.invoke(myProject, PsiUtilCore.toPsiElementArray(elements), true);
}
}
}
/**
* @param usages
* @return Map from elements to UsageHolders
*/
private static HashMap<PsiElement,UsageHolder> sortUsages(@NotNull UsageInfo[] usages) {
HashMap<PsiElement,UsageHolder> result = new HashMap<>();
for (final UsageInfo usage : usages) {
if (usage instanceof SafeDeleteUsageInfo) {
final PsiElement referencedElement = ((SafeDeleteUsageInfo)usage).getReferencedElement();
if (!result.containsKey(referencedElement)) {
result.put(referencedElement, new UsageHolder(referencedElement, usages));
}
}
}
return result;
}
@Override
protected void refreshElements(@NotNull PsiElement[] elements) {
LOG.assertTrue(elements.length == myElements.length);
System.arraycopy(elements, 0, myElements, 0, elements.length);
}
@Override
protected boolean isPreviewUsages(@NotNull UsageInfo[] usages) {
if(myPreviewNonCodeUsages && UsageViewUtil.reportNonRegularUsages(usages, myProject)) {
return true;
}
return super.isPreviewUsages(filterToBeDeleted(usages));
}
private static UsageInfo[] filterToBeDeleted(UsageInfo[] infos) {
ArrayList<UsageInfo> list = new ArrayList<>();
for (UsageInfo info : infos) {
if (!(info instanceof SafeDeleteReferenceUsageInfo) || ((SafeDeleteReferenceUsageInfo) info).isSafeDelete()) {
list.add(info);
}
}
return list.toArray(new UsageInfo[list.size()]);
}
@Nullable
@Override
protected RefactoringEventData getBeforeData() {
final RefactoringEventData beforeData = new RefactoringEventData();
beforeData.addElements(myElements);
return beforeData;
}
@Nullable
@Override
protected String getRefactoringId() {
return "refactoring.safeDelete";
}
@Override
protected void performRefactoring(@NotNull UsageInfo[] usages) {
try {
for (UsageInfo usage : usages) {
if (usage instanceof SafeDeleteCustomUsageInfo) {
((SafeDeleteCustomUsageInfo) usage).performRefactoring();
}
}
SmartPointerManager pointerManager = SmartPointerManager.getInstance(myProject);
List<SmartPsiElementPointer<PsiElement>> pointers = ContainerUtil.map(myElements, pointerManager::createSmartPsiElementPointer);
for (PsiElement element : myElements) {
for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
if (delegate.handlesElement(element)) {
delegate.prepareForDeletion(element);
}
}
}
for (SmartPsiElementPointer<PsiElement> pointer : pointers) {
PsiElement element = pointer.getElement();
if (element != null) {
element.delete();
}
}
if (myAfterRefactoringCallback != null) myAfterRefactoringCallback.run();
} catch (IncorrectOperationException e) {
RefactoringUIUtil.processIncorrectOperation(myProject, e);
}
}
private String calcCommandName() {
return RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(myElements));
}
private String myCachedCommandName = null;
@Override
protected String getCommandName() {
if (myCachedCommandName == null) {
myCachedCommandName = calcCommandName();
}
return myCachedCommandName;
}
public static void addNonCodeUsages(final PsiElement element,
List<UsageInfo> usages,
@Nullable final Condition<PsiElement> insideElements,
boolean searchNonJava,
boolean searchInCommentsAndStrings) {
UsageInfoFactory nonCodeUsageFactory = new UsageInfoFactory() {
@Override
public UsageInfo createUsageInfo(@NotNull PsiElement usage, int startOffset, int endOffset) {
if (insideElements != null && insideElements.value(usage)) {
return null;
}
return new SafeDeleteReferenceSimpleDeleteUsageInfo(usage, element, startOffset, endOffset, true, false);
}
};
if (searchInCommentsAndStrings) {
String stringToSearch = ElementDescriptionUtil.getElementDescription(element, NonCodeSearchDescriptionLocation.STRINGS_AND_COMMENTS);
TextOccurrencesUtil.addUsagesInStringsAndComments(element, stringToSearch, usages, nonCodeUsageFactory);
}
if (searchNonJava) {
String stringToSearch = ElementDescriptionUtil.getElementDescription(element, NonCodeSearchDescriptionLocation.NON_JAVA);
TextOccurrencesUtil.addTextOccurences(element, stringToSearch, GlobalSearchScope.projectScope(element.getProject()), usages, nonCodeUsageFactory);
}
}
@Override
protected boolean isToBeChanged(@NotNull UsageInfo usageInfo) {
if (usageInfo instanceof SafeDeleteReferenceUsageInfo) {
return ((SafeDeleteReferenceUsageInfo)usageInfo).isSafeDelete() && super.isToBeChanged(usageInfo);
}
return super.isToBeChanged(usageInfo);
}
public static boolean validElement(@NotNull PsiElement element) {
if (element instanceof PsiFile) return true;
if (!element.isPhysical()) return false;
final RefactoringSupportProvider provider = LanguageRefactoringSupport.INSTANCE.forLanguage(element.getLanguage());
return provider.isSafeDeleteAvailable(element);
}
public static SafeDeleteProcessor createInstance(Project project, @Nullable Runnable prepareSuccessfulCallback,
PsiElement[] elementsToDelete, boolean isSearchInComments, boolean isSearchNonJava) {
return new SafeDeleteProcessor(project, prepareSuccessfulCallback, elementsToDelete, isSearchInComments, isSearchNonJava);
}
public static SafeDeleteProcessor createInstance(Project project, @Nullable Runnable prepareSuccessfulCallBack,
PsiElement[] elementsToDelete, boolean isSearchInComments, boolean isSearchNonJava,
boolean askForAccessors) {
ArrayList<PsiElement> elements = new ArrayList<>(Arrays.asList(elementsToDelete));
HashSet<PsiElement> elementsToDeleteSet = new HashSet<>(Arrays.asList(elementsToDelete));
for (PsiElement psiElement : elementsToDelete) {
for(SafeDeleteProcessorDelegate delegate: Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
if (delegate.handlesElement(psiElement)) {
Collection<PsiElement> addedElements = delegate.getAdditionalElementsToDelete(psiElement, elementsToDeleteSet, askForAccessors);
if (addedElements != null) {
elements.addAll(addedElements);
}
break;
}
}
}
return new SafeDeleteProcessor(project, prepareSuccessfulCallBack,
PsiUtilCore.toPsiElementArray(elements),
isSearchInComments, isSearchNonJava);
}
public boolean isSearchInCommentsAndStrings() {
return mySearchInCommentsAndStrings;
}
public void setSearchInCommentsAndStrings(boolean searchInCommentsAndStrings) {
mySearchInCommentsAndStrings = searchInCommentsAndStrings;
}
public boolean isSearchNonJava() {
return mySearchNonJava;
}
public void setSearchNonJava(boolean searchNonJava) {
mySearchNonJava = searchNonJava;
}
@Override
protected boolean skipNonCodeUsages() {
return true;
}
public void setAfterRefactoringCallback(Runnable afterRefactoringCallback) {
myAfterRefactoringCallback = afterRefactoringCallback;
}
}
|
package edu.umd.cs.daveho.ba;
import java.io.*;
/**
* Cached data for a source file.
* Contains a map of line numbers to byte offsets, for quick
* searching of source lines.
* @see SourceFinder
* @author David Hovemeyer
*/
public class SourceFile {
private static int intValueOf(byte b) {
// Why isn't there an API method to do this?
if ((b & 0x80) == 0)
return b;
else
return 0x80 | ((int)b & 0x7F);
}
/**
* Helper object to build map of line number to byte offset
* for a source file.
*/
private static class LineNumberMapBuilder {
private SourceFile sourceFile;
private int offset;
private int lastSeen;
public LineNumberMapBuilder(SourceFile sourceFile) {
this.sourceFile = sourceFile;
this.offset = 0;
this.lastSeen = -1;
}
public void addData(byte[] data, int len) {
for (int i = 0; i < len; ++i) {
int ch = intValueOf(data[i]);
add(ch);
}
}
public void eof() {
add(-1);
}
private void add(int ch) {
switch (ch) {
case '\n':
sourceFile.addLineOffset(offset + 1);
break;
case '\r':
// Need to see next character to know if it's a
// line terminator.
break;
default:
if (lastSeen == '\r') {
// We consider a bare CR to be an end of line
// if it is not followed by a new line.
// Mac OS has historically used a bare CR as
// its line terminator.
sourceFile.addLineOffset(offset);
}
}
lastSeen = ch;
++offset;
}
}
private static final int DEFAULT_SIZE = 100;
private String fullFileName;
private byte[] data;
private int[] lineNumberMap;
private int numLines;
/**
* Constructor.
* Creates an empty SourceFile object.
*/
public SourceFile(String fullFileName) {
this.fullFileName = fullFileName;
this.lineNumberMap = new int[DEFAULT_SIZE];
this.numLines = 0;
}
/**
* Get the full path name of the source file (with directory).
*/
public String getFullFileName() {
return fullFileName;
}
/**
* Get an InputStream on data.
* @return an InputStream on the data in the source file,
* starting from given offset
*/
public InputStream getInputStream() throws IOException {
loadFileData();
return new ByteArrayInputStream(data);
}
/**
* Get an InputStream on data starting at given offset.
* @param offset the start offset
* @return an InputStream on the data in the source file,
* starting at the given offset
*/
public InputStream getInputStreamFromOffset(int offset) throws IOException {
loadFileData();
return new ByteArrayInputStream(data, offset, data.length - offset);
}
/**
* Add a source line byte offset.
* This method should be called for each line in the source file,
* in order.
* @param offset the byte offset of the next source line
*/
public void addLineOffset(int offset) {
if (numLines >= lineNumberMap.length) {
// Grow the line number map.
int capacity = lineNumberMap.length * 2;
int[] newLineNumberMap = new int[capacity];
System.arraycopy(lineNumberMap, 0, newLineNumberMap, 0, lineNumberMap.length);
lineNumberMap = newLineNumberMap;
}
lineNumberMap[numLines++] = offset;
}
/**
* Get the byte offset in the data for a source line.
* Note that lines are considered to be zero-index, so the first
* line in the file is numbered zero.
* @param line the line number
* @return the byte offset in the file's data for the line,
* or -1 if the line is not valid
*/
public int getLineOffset(int line) {
if (line < 0 || line >= numLines)
return -1;
return lineNumberMap[line];
}
private void loadFileData() throws IOException {
if (data != null)
return;
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(fullFileName));
ByteArrayOutputStream out = new ByteArrayOutputStream();
addLineOffset(0); // Line 0 starts at offset 0
LineNumberMapBuilder mapBuilder = new LineNumberMapBuilder(this);
// Copy all of the data from the file into the byte array output stream
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
mapBuilder.addData(buf, n);
out.write(buf, 0, n);
}
mapBuilder.eof();
setData(out.toByteArray());
} finally {
if (in != null)
in.close();
}
}
/**
* Set the source file data.
* @param data the data
*/
private void setData(byte[] data) {
this.data = data;
}
}
// vim:ts=4
|
package org.opencms.configuration;
import org.opencms.test.OpenCmsTestCase;
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;
import org.apache.commons.collections.ExtendedProperties;
/**
* Test cases for the parameter configuration.<p>
*/
public class TestParameterConfiguration extends OpenCmsTestCase {
/**
* Tests escaping and unescaping values in the parameter configuration.<p>
*
* @throws Exception in case the test fails
*/
public void testEscapeUnescapeParameterConfiguration() throws Exception {
CmsParameterConfiguration config = new CmsParameterConfiguration();
config.add("test1", "test, eins");
assertEquals("test, eins", config.get("test1"));
config.add("test2", "test \\\\ zwei");
assertEquals("test \\\\ zwei", config.get("test2"));
config.add("test3", "test \\= drei");
assertEquals("test \\= drei", config.get("test3"));
}
/**
* Test merging the parameter configuration.<p>
*
* @throws Exception in case the test fails
*/
public void testMergeParameterConfiguration() throws Exception {
CmsParameterConfiguration config1 = new CmsParameterConfiguration();
String p = "testParam";
config1.add(p, "1");
config1.add(p, "2");
config1.add(p, "3");
config1.add("x", "y");
CmsParameterConfiguration config2 = new CmsParameterConfiguration();
config2.add(p, "a");
config2.add(p, "b");
config2.add(p, "c");
config2.add("v", "w");
config1.putAll(config2);
assertEquals("1,2,3,a,b,c", config1.get(p));
assertEquals(6, config1.getList(p).size());
assertEquals("y", config1.get("x"));
assertEquals("w", config1.get("v"));
}
/**
* Test reading the parameter configuration.<p>
*
* @throws Exception in case the test fails
*/
public void testReadParameterConfiguration() throws Exception {
String testPropPath = "org/opencms/configuration/opencms-test.properties";
URL url = this.getClass().getClassLoader().getResource(testPropPath);
String decodedPath = URLDecoder.decode(url.getPath(), "UTF-8");
File file = new File(decodedPath);
System.out.println("URL: '" + url + "'");
System.out.println("URL path decoded: '" + decodedPath + "'");
System.out.println("File: '" + file + "'");
// make sure the test properties file is found
assertTrue("Test property file '" + file.getAbsolutePath() + "' not found", file.exists());
CmsParameterConfiguration cmsProp = new CmsParameterConfiguration(file.getAbsolutePath());
assertEquals("C:\\dev\\workspace\\opencms-core\\test\\data", cmsProp.get("test.path.one"));
// test some of the more advanced features
assertEquals(4, cmsProp.getList("test.list").size());
assertEquals(3, cmsProp.getList("test.otherlist").size());
assertEquals("comma, escaped with \\ backslash", cmsProp.get("test.escaping"));
assertEquals("this is a long long long long long long line!", cmsProp.get("test.multiline"));
// test compatibility with Collection Extended Properties
ExtendedProperties extProp = new ExtendedProperties(file.getAbsolutePath());
assertEquals(extProp.size(), cmsProp.size());
for (String key : cmsProp.keySet()) {
Object value = cmsProp.getObject(key);
assertTrue("Key '" + key + "' not found in CmsConfiguration", extProp.containsKey(key));
assertTrue("Objects for '" + key + "' not equal", value.equals(extProp.getProperty(key)));
}
}
/**
* Tests the extraction of properties.
*
* @throws Exception
*/
public void testExtractionOfPrefixedConfiguration() throws Exception {
CmsParameterConfiguration config = new CmsParameterConfiguration();
config.add("a", "value_a");
config.add("a.b1", "value_a.b1");
config.add("a.b2", "value_a.b2");
config.add("a.b1.c1", "value_a.b1.c1"); // These three will be retrieved
config.add("a.b1.c2", "value_a.b1.c2"); // These three will be retrieved
config.add("a.b1.c3", "value_a.b1.c3"); // These three will be retrieved
config.add("a.b2.c1", "value_a.b2.c1");
config.add("a.b2.c2", "value_a.b2.c2");
config.add("a.b2.c3", "value_a.b2.c3");
Properties result = config.getPrefixedProperties("a.b1");
assertNull("Key 'a' found in Properties", result.getProperty("a"));
assertNull("Key 'a.b1' found in Properties", result.getProperty("a.b1"));
assertNull("Key 'b1' found in Properties", result.getProperty("b1"));
assertNull("Empty key '' found in Properties", result.getProperty(""));
assertEquals("Incorrect value of key c1 (a.b1.c1)", "value_a.b1.c1", result.getProperty("c1"));
assertEquals("Incorrect value of key c2 (a.b1.c2)", "value_a.b1.c2", result.getProperty("c2"));
assertEquals("Incorrect value of key c2 (a.b1.c3)", "value_a.b1.c3", result.getProperty("c3"));
assertEquals("Incorrect number of properties", 3, result.size());
}
}
|
package com.intellij.openapi.editor.impl.view;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorFontType;
import com.intellij.openapi.editor.colors.FontPreferences;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.HighlighterIterator;
import com.intellij.openapi.editor.impl.*;
import com.intellij.openapi.editor.impl.softwrap.SoftWrapDrawingType;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.editor.markup.TextAttributesEffectsBuilder.EffectDescriptor;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.impl.IdeBackgroundUtil;
import com.intellij.ui.CachingPainter;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.ui.paint.EffectPainter;
import com.intellij.ui.paint.LinePainter2D;
import com.intellij.ui.paint.PaintUtil;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.DocumentUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.containers.PeekableIterator;
import com.intellij.util.containers.PeekableIteratorWrapper;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.ui.UIUtil;
import gnu.trove.TFloatArrayList;
import gnu.trove.TIntObjectHashMap;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.List;
import java.util.*;
import java.util.function.Consumer;
import static com.intellij.openapi.editor.markup.TextAttributesEffectsBuilder.EffectSlot.FRAME_SLOT;
/**
* Renders editor contents.
*/
public class EditorPainter implements TextDrawingCallback {
private static final Color CARET_LIGHT = Gray._255;
private static final Color CARET_DARK = Gray._0;
private static final Stroke IME_COMPOSED_TEXT_UNDERLINE_STROKE = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0,
new float[]{0, 2, 0, 2}, 0);
private static final int CARET_DIRECTION_MARK_SIZE = 5;
private static final char IDEOGRAPHIC_SPACE = '\u3000';
private static final String WHITESPACE_CHARS = " \t" + IDEOGRAPHIC_SPACE;
private static final Object ourCachedDot = ObjectUtils.sentinel("space symbol");
private final EditorView myView;
EditorPainter(EditorView view) {
myView = view;
}
void paint(Graphics2D g) {
new Session(myView, g).paint();
}
void repaintCarets() {
EditorImpl editor = myView.getEditor();
EditorImpl.CaretRectangle[] locations = editor.getCaretLocations(false);
if (locations == null) return;
int nominalLineHeight = myView.getNominalLineHeight();
int topOverhang = myView.getTopOverhang();
for (EditorImpl.CaretRectangle location : locations) {
float x = (float)location.myPoint.getX();
int y = (int)location.myPoint.getY() - topOverhang;
float width = Math.max(location.myWidth, CARET_DIRECTION_MARK_SIZE);
int xStart = (int)Math.floor(x - width);
int xEnd = (int)Math.ceil(x + width);
editor.getContentComponent().repaint(xStart, y, xEnd - xStart, nominalLineHeight);
}
}
@Override
public void drawChars(@NotNull Graphics g, char @NotNull [] data, int start, int end, int x, int y, Color color, FontInfo fontInfo) {
g.setFont(fontInfo.getFont());
g.setColor(color);
g.drawChars(data, start, end - start, x, y);
}
public static boolean isMarginShown(@NotNull Editor editor) {
return editor.getSettings().isRightMarginShown() &&
editor.getColorsScheme().getColor(EditorColors.RIGHT_MARGIN_COLOR) != null &&
(Registry.is("editor.show.right.margin.in.read.only.files") || editor.getDocument().isWritable());
}
private static class Session {
private final EditorView myView;
private final EditorImpl myEditor;
private final Document myDocument;
private final CharSequence myText;
private final MarkupModelEx myDocMarkup;
private final MarkupModelEx myEditorMarkup;
private final XCorrector myCorrector;
private final Graphics2D myGraphics;
private final Rectangle myClip;
private final int myYShift;
private final int myStartVisualLine;
private final int myEndVisualLine;
private final int myStartOffset;
private final int myEndOffset;
private final int mySeparatorHighlightersStartOffset;
private final int mySeparatorHighlightersEndOffset;
private final ClipDetector myClipDetector;
private final IterationState.CaretData myCaretData;
private final Map<Integer, Couple<Integer>> myVirtualSelectionMap;
private final TIntObjectHashMap<List<LineExtensionData>> myExtensionData = new TIntObjectHashMap<>(); // key is visual line
private final TIntObjectHashMap<TextAttributes> myBetweenLinesAttributes = new TIntObjectHashMap<>(); // key is bottom visual line
private final int myLineHeight;
private final int myAscent;
private final int myDescent;
private final Color myDefaultBackgroundColor;
private final Color myBackgroundColor;
private final int myMarginColumns;
private final List<Consumer<Graphics2D>> myTextDrawingTasks = new ArrayList<>();
private final List<RangeHighlighter> myForegroundCustomHighlighters = new SmartList<>();
private MarginPositions myMarginPositions;
private Session(EditorView view, Graphics2D g) {
myView = view;
myEditor = myView.getEditor();
myDocument = myEditor.getDocument();
myText = myDocument.getImmutableCharSequence();
myDocMarkup = myEditor.getFilteredDocumentMarkupModel();
myEditorMarkup = myEditor.getMarkupModel();
myCorrector = XCorrector.create(myView);
myGraphics = g;
myClip = myGraphics.getClipBounds();
myYShift = -myClip.y;
myStartVisualLine = myView.yToVisualLine(myClip.y);
myEndVisualLine = myView.yToVisualLine(myClip.y + myClip.height - 1);
myStartOffset = myView.visualLineToOffset(myStartVisualLine);
myEndOffset = myView.visualLineToOffset(myEndVisualLine + 1);
mySeparatorHighlightersStartOffset = DocumentUtil.getLineStartOffset(myView.visualLineToOffset(myStartVisualLine - 1), myDocument);
mySeparatorHighlightersEndOffset = DocumentUtil.getLineEndOffset(myView.visualLineToOffset(myEndVisualLine + 2), myDocument);
myClipDetector = new ClipDetector(myEditor, myClip);
myCaretData = myEditor.isPaintSelection() ? IterationState.createCaretData(myEditor) : null;
myVirtualSelectionMap = createVirtualSelectionMap(myEditor, myStartVisualLine, myEndVisualLine);
myLineHeight = myView.getLineHeight();
myAscent = myView.getAscent();
myDescent = myView.getDescent();
myDefaultBackgroundColor = myEditor.getColorsScheme().getDefaultBackground();
myBackgroundColor = myEditor.getBackgroundColor();
myMarginColumns = myEditor.getSettings().getRightMargin(myEditor.getProject());
}
private void paint() {
if (myEditor.getContentComponent().isOpaque()) {
myGraphics.setColor(myBackgroundColor);
myGraphics.fillRect(myClip.x, myClip.y, myClip.width, myClip.height);
}
myGraphics.translate(0, -myYShift);
if (paintPlaceholderText()) {
paintCaret();
return;
}
paintBackground();
paintRightMargin();
paintCustomRenderers();
paintLineMarkersSeparators(myDocMarkup);
paintLineMarkersSeparators(myEditorMarkup);
paintTextWithEffects();
paintHighlightersAfterEndOfLine(myDocMarkup);
paintHighlightersAfterEndOfLine(myEditorMarkup);
paintBorderEffect(myEditor.getHighlighter());
paintBorderEffect(myDocMarkup);
paintBorderEffect(myEditorMarkup);
paintForegroundCustomRenderers();
paintBlockInlays();
paintCaret();
paintComposedTextDecoration();
myGraphics.translate(0, myYShift);
}
private boolean paintPlaceholderText() {
CharSequence hintText = myEditor.getPlaceholder();
EditorComponentImpl editorComponent = myEditor.getContentComponent();
if (myDocument.getTextLength() > 0 || hintText == null || hintText.length() == 0 ||
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == editorComponent &&
!myEditor.getShowPlaceholderWhenFocused()) {
return false;
}
hintText = SwingUtilities.layoutCompoundLabel(myGraphics.getFontMetrics(), hintText.toString(), null, 0, 0, 0, 0,
SwingUtilities.calculateInnerArea(editorComponent, null), // account for insets
new Rectangle(), new Rectangle(), 0);
EditorFontType fontType = EditorFontType.PLAIN;
Color color = JBColor.namedColor("Component.infoForeground", myEditor.getColorsScheme().getDefaultForeground());
TextAttributes attributes = myEditor.getPlaceholderAttributes();
if (attributes != null) {
int type = attributes.getFontType();
if (type == Font.ITALIC) fontType = EditorFontType.ITALIC;
else if (type == Font.BOLD) fontType = EditorFontType.BOLD;
else if (type == (Font.ITALIC | Font.BOLD)) fontType = EditorFontType.BOLD_ITALIC;
Color attColor = attributes.getForegroundColor();
if (attColor != null) color = attColor;
}
myGraphics.setColor(color);
myGraphics.setFont(myEditor.getColorsScheme().getFont(fontType));
myGraphics.drawString(hintText.toString(), myView.getInsets().left, myView.getInsets().top + myAscent + myYShift);
return true;
}
private void paintRightMargin() {
if (!isMarginShown()) return;
Color visualGuidesColor = myEditor.getColorsScheme().getColor(EditorColors.VISUAL_INDENT_GUIDE_COLOR);
if (visualGuidesColor != null) {
myGraphics.setColor(visualGuidesColor);
for (Integer marginX : myCorrector.softMarginsX()) {
LinePainter2D.paint(myGraphics, marginX, 0, marginX, myClip.height);
}
}
myGraphics.setColor(myEditor.getColorsScheme().getColor(EditorColors.RIGHT_MARGIN_COLOR));
float baseMarginWidth = getBaseMarginWidth(myView);
int baseMarginX = myCorrector.marginX(baseMarginWidth);
if (myMarginPositions == null) {
LinePainter2D.paint(myGraphics, baseMarginX, 0, baseMarginX, myClip.height);
}
else {
int displayedLinesCount = myMarginPositions.x.length - 1;
for (int i = 0; i <= displayedLinesCount; i++) {
float width = myMarginPositions.x[i];
int x = width == 0 ? baseMarginX : (int)width;
int y = myMarginPositions.y[i];
if (i == 0 && y > myYShift) {
myGraphics.fillRect(baseMarginX, myYShift, 1, y - myYShift);
if (x != baseMarginX) {
myGraphics.fillRect(Math.min(x, baseMarginX), y - 1, Math.abs(x - baseMarginX) + 1, 1);
}
}
if (i < displayedLinesCount) {
myGraphics.fillRect(x, y, 1, myLineHeight);
float nextWidth = myMarginPositions.x[i + 1];
int nextX = nextWidth == 0 ? baseMarginX : (int)nextWidth;
int nextY = myMarginPositions.y[i + 1];
if (nextY > y + myLineHeight) {
if (x != baseMarginX) {
myGraphics.fillRect(Math.min(x, baseMarginX), y + myLineHeight - 1, Math.abs(x - baseMarginX) + 1, 1);
}
myGraphics.fillRect(baseMarginX, y + myLineHeight, 1, nextY - y - myLineHeight);
if (baseMarginX != nextX) {
myGraphics.fillRect(Math.min(nextX, baseMarginX), nextY - 1, Math.abs(nextX - baseMarginX) + 1, 1);
}
}
else {
if (x != nextX) {
myGraphics.fillRect(Math.min(x, nextX), y + myLineHeight - 1, Math.abs(x - nextX) + 1, 1);
}
}
}
else {
myGraphics.fillRect(x, y, 1, myClip.y + myClip.height + myYShift - y);
}
}
}
}
private static float getBaseMarginWidth(EditorView view) {
Editor editor = view.getEditor();
return editor.getSettings().getRightMargin(editor.getProject()) * view.getPlainSpaceWidth();
}
private boolean isMarginShown() {
return EditorPainter.isMarginShown(myEditor);
}
private void paintBackground() {
int lineCount = myEditor.getVisibleLineCount();
boolean calculateMarginWidths = Registry.is("editor.adjust.right.margin") && isMarginShown() && myStartVisualLine < lineCount;
myMarginPositions = calculateMarginWidths ? new MarginPositions(Math.min(myEndVisualLine, lineCount - 1) - myStartVisualLine + 2)
: null;
final LineWhitespacePaintingStrategy whitespacePaintingStrategy = new LineWhitespacePaintingStrategy(myEditor.getSettings());
boolean paintAllSoftWraps = myEditor.getSettings().isAllSoftWrapsShown();
float whiteSpaceScale = ((float)myEditor.getColorsScheme().getEditorFontSize()) / FontPreferences.DEFAULT_FONT_SIZE;
final BasicStroke whiteSpaceStroke = new BasicStroke(calcFeatureSize(1, whiteSpaceScale));
PeekableIterator<Caret> caretIterator = null;
if (myEditor.getInlayModel().hasBlockElements()) {
Iterator<Caret> carets = myEditor.getCaretModel().getAllCarets()
.stream()
.filter(Caret::hasSelection)
.sorted(Comparator.comparingInt(Caret::getSelectionStart))
.iterator();
caretIterator = new PeekableIteratorWrapper<>(carets);
}
final VisualPosition primarySelectionStart = myEditor.getSelectionModel().getSelectionStartPosition();
final VisualPosition primarySelectionEnd = myEditor.getSelectionModel().getSelectionEndPosition();
LineLayout prefixLayout = myView.getPrefixLayout();
if (myStartVisualLine == 0 && prefixLayout != null) {
float width = prefixLayout.getWidth();
TextAttributes attributes = myView.getPrefixAttributes();
paintBackground(attributes, myCorrector.startX(myStartVisualLine), myYShift + myView.visualLineToY(0), width);
myTextDrawingTasks.add(g -> {
g.setColor(attributes.getForegroundColor());
paintLineLayoutWithEffect(prefixLayout,
myCorrector.startX(myStartVisualLine), myAscent + myYShift + myView.visualLineToY(0),
attributes.getEffectColor(), attributes.getEffectType());
});
}
int startX = myView.getInsets().left;
int endX = myClip.x + myClip.width;
int prevY = Math.max(myView.getInsets().top, myClip.y) + myYShift;
VisualLinesIterator visLinesIterator = new VisualLinesIterator(myEditor, myStartVisualLine);
while (!visLinesIterator.atEnd()) {
int visualLine = visLinesIterator.getVisualLine();
if (visualLine > myEndVisualLine + 1) break;
int y = visLinesIterator.getY() + myYShift;
if (calculateMarginWidths) myMarginPositions.y[visualLine - myStartVisualLine] = y;
if (y > prevY) {
TextAttributes attributes = getBetweenLinesAttributes(visualLine, visLinesIterator.getVisualLineStartOffset(),
Objects.requireNonNull(caretIterator));
myBetweenLinesAttributes.put(visualLine, attributes);
paintBackground(attributes.getBackgroundColor(), startX, prevY, endX - startX, y - prevY);
}
boolean dryRun = visualLine > myEndVisualLine;
if (dryRun && !calculateMarginWidths) break;
boolean paintSoftWraps = paintAllSoftWraps ||
myEditor.getCaretModel().getLogicalPosition().line == visLinesIterator.getStartLogicalLine();
int[] currentLogicalLine = new int[]{-1};
paintLineFragments(visLinesIterator, y, new LineFragmentPainter() {
@Override
public void paintBeforeLineStart(TextAttributes attributes, boolean hasSoftWrap, int columnEnd, float xEnd, int y) {
if (dryRun) return;
paintBackground(attributes, startX, y, xEnd);
if (!hasSoftWrap) return;
paintSelectionOnSecondSoftWrapLineIfNecessary(visualLine, columnEnd, xEnd, y, primarySelectionStart, primarySelectionEnd);
if (paintSoftWraps) {
myTextDrawingTasks.add(g -> {
SoftWrapModelImpl softWrapModel = myEditor.getSoftWrapModel();
int symbolWidth = softWrapModel.getMinDrawingWidthInPixels(SoftWrapDrawingType.AFTER_SOFT_WRAP);
softWrapModel.doPaint(g, SoftWrapDrawingType.AFTER_SOFT_WRAP, (int)xEnd - symbolWidth, y, myLineHeight);
});
}
}
@Override
public void paint(VisualLineFragmentsIterator.Fragment fragment, int start, int end,
TextAttributes attributes, float xStart, float xEnd, int y) {
if (dryRun) return;
FoldRegion foldRegion = fragment.getCurrentFoldRegion();
TextAttributes foldRegionInnerAttributes =
foldRegion == null || !Registry.is("editor.highlight.foldings") ? null : getInnerHighlighterAttributes(foldRegion);
if (foldRegionInnerAttributes == null ||
!paintFoldingBackground(foldRegionInnerAttributes, xStart, y, xEnd - xStart, foldRegion)) {
paintBackground(attributes, xStart, y, xEnd - xStart);
}
Inlay inlay = fragment.getCurrentInlay();
if (inlay != null) {
TextAttributes attrs = attributes.clone();
myTextDrawingTasks.add(g -> {
inlay.getRenderer().paint(inlay, g, new Rectangle((int)xStart, y, inlay.getWidthInPixels(), myLineHeight), attrs);
});
}
else {
if (foldRegionInnerAttributes != null) {
attributes = TextAttributes.merge(attributes, foldRegionInnerAttributes);
}
if (attributes != null) {
attributes.forEachEffect((type, color) -> myTextDrawingTasks.add(
g -> paintTextEffect(xStart, xEnd, y + myAscent, color, type, foldRegion != null)
));
}
if (attributes != null) {
Color color = attributes.getForegroundColor();
if (color != null) {
myTextDrawingTasks.add(g -> g.setColor(color));
myTextDrawingTasks.add(fragment.draw(xStart, y + myAscent, start, end));
}
}
}
if (foldRegion == null) {
int logicalLine = fragment.getStartLogicalLine();
if (logicalLine != currentLogicalLine[0]) {
whitespacePaintingStrategy.update(myText,
myDocument.getLineStartOffset(logicalLine), myDocument.getLineEndOffset(logicalLine));
currentLogicalLine[0] = logicalLine;
}
paintWhitespace(xStart, y + myAscent, start, end, whitespacePaintingStrategy, fragment, whiteSpaceStroke,
whiteSpaceScale);
}
}
@Override
public void paintAfterLineEnd(IterationState it, int columnStart, float x, int y) {
if (dryRun) return;
TextAttributes backgroundAttributes = it.getPastLineEndBackgroundAttributes().clone();
paintBackground(backgroundAttributes, x, y, endX - x);
int offset = it.getEndOffset();
SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset);
if (softWrap == null) {
collectExtensions(visualLine, offset);
paintLineExtensionsBackground(visualLine, x, y);
paintVirtualSelectionIfNecessary(visualLine, columnStart, x, y);
myTextDrawingTasks.add(g -> {
int logicalLine = myDocument.getLineNumber(offset);
List<Inlay> inlays = myEditor.getInlayModel().getAfterLineEndElementsForLogicalLine(logicalLine);
if (!inlays.isEmpty()) {
float curX = x + myView.getPlainSpaceWidth();
for (Inlay inlay : inlays) {
int width = inlay.getWidthInPixels();
inlay.getRenderer().paint(inlay, g, new Rectangle((int)curX, y, width, myLineHeight), backgroundAttributes);
curX += width;
}
}
paintLineExtensions(visualLine, logicalLine, x, y + myAscent);
});
}
else {
paintSelectionOnFirstSoftWrapLineIfNecessary(visualLine, columnStart, x, y, primarySelectionStart, primarySelectionEnd);
if (paintSoftWraps) {
myTextDrawingTasks.add(g -> {
myEditor.getSoftWrapModel().doPaint(g, SoftWrapDrawingType.BEFORE_SOFT_WRAP_LINE_FEED, (int)x, y, myLineHeight);
});
}
}
}
}, calculateMarginWidths && !visLinesIterator.endsWithSoftWrap() && !visLinesIterator.startsWithSoftWrap()
? width -> myMarginPositions.x[visualLine - myStartVisualLine] = width : null);
prevY = y + myLineHeight;
visLinesIterator.advance();
}
if (calculateMarginWidths && myEndVisualLine >= lineCount - 1) {
myMarginPositions.y[myMarginPositions.y.length - 1] = myMarginPositions.y[myMarginPositions.y.length - 2] + myLineHeight;
}
}
private boolean paintFoldingBackground(TextAttributes innerAttributes, float x, int y, float width, @NotNull FoldRegion foldRegion) {
if (innerAttributes.getBackgroundColor() != null && !isSelected(foldRegion)) {
paintBackground(innerAttributes, x, y, width);
Color borderColor = myEditor.getColorsScheme().getColor(EditorColors.FOLDED_TEXT_BORDER_COLOR);
if (borderColor != null) {
Shape border = getBorderShape(x, y, width, myLineHeight, 2, false);
if (border != null) {
myGraphics.setColor(borderColor);
myGraphics.fill(border);
}
}
return true;
}
else {
return false;
}
}
private static Map<Integer, Couple<Integer>> createVirtualSelectionMap(Editor editor, int startVisualLine, int endVisualLine) {
HashMap<Integer, Couple<Integer>> map = new HashMap<>();
for (Caret caret : editor.getCaretModel().getAllCarets()) {
if (caret.hasSelection()) {
VisualPosition selectionStart = caret.getSelectionStartPosition();
VisualPosition selectionEnd = caret.getSelectionEndPosition();
if (selectionStart.line == selectionEnd.line) {
int line = selectionStart.line;
if (line >= startVisualLine && line <= endVisualLine) {
map.put(line, Couple.of(selectionStart.column, selectionEnd.column));
}
}
}
}
return map;
}
private void paintVirtualSelectionIfNecessary(int visualLine, int columnStart, float xStart, int y) {
Couple<Integer> selectionRange = myVirtualSelectionMap.get(visualLine);
if (selectionRange == null || selectionRange.second <= columnStart) return;
float startX = selectionRange.first <= columnStart
? xStart
: (float)myView.visualPositionToXY(new VisualPosition(visualLine, selectionRange.first)).getX();
float endX = (float)Math.min(myClip.x + myClip.width,
myView.visualPositionToXY(new VisualPosition(visualLine, selectionRange.second)).getX());
paintBackground(myEditor.getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), startX, y, endX - startX);
}
private void paintSelectionOnSecondSoftWrapLineIfNecessary(int visualLine, int columnEnd, float xEnd, int y,
VisualPosition selectionStartPosition, VisualPosition selectionEndPosition) {
if (selectionStartPosition.equals(selectionEndPosition) ||
visualLine < selectionStartPosition.line ||
visualLine > selectionEndPosition.line ||
visualLine == selectionStartPosition.line && selectionStartPosition.column >= columnEnd) {
return;
}
float startX = (selectionStartPosition.line == visualLine && selectionStartPosition.column > 0) ?
(float)myView.visualPositionToXY(selectionStartPosition).getX() : myCorrector.startX(visualLine);
float endX = (selectionEndPosition.line == visualLine && selectionEndPosition.column < columnEnd) ?
(float)myView.visualPositionToXY(selectionEndPosition).getX() : xEnd;
paintBackground(myEditor.getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), startX, y, endX - startX);
}
private void paintSelectionOnFirstSoftWrapLineIfNecessary(int visualLine,
int columnStart,
float xStart,
int y,
VisualPosition selectionStartPosition,
VisualPosition selectionEndPosition) {
if (selectionStartPosition.equals(selectionEndPosition) ||
visualLine < selectionStartPosition.line ||
visualLine > selectionEndPosition.line ||
visualLine == selectionEndPosition.line && selectionEndPosition.column <= columnStart) {
return;
}
float startX = selectionStartPosition.line == visualLine && selectionStartPosition.column > columnStart ?
(float)myView.visualPositionToXY(selectionStartPosition).getX() : xStart;
float endX = selectionEndPosition.line == visualLine ?
(float)myView.visualPositionToXY(selectionEndPosition).getX() : myClip.x + myClip.width;
paintBackground(myEditor.getColorsScheme().getColor(EditorColors.SELECTION_BACKGROUND_COLOR), startX, y, endX - startX);
}
private void paintBackground(TextAttributes attributes, float x, int y, float width) {
if (attributes == null) return;
paintBackground(attributes.getBackgroundColor(), x, y, width);
}
private void paintBackground(Color color, float x, int y, float width) {
paintBackground(color, x, y, width, myLineHeight);
}
private void paintBackground(Color color, float x, int y, float width, int height) {
if (width <= 0 || color == null || color.equals(myDefaultBackgroundColor) || color.equals(myBackgroundColor)) return;
myGraphics.setColor(color);
myGraphics.fill(new Rectangle2D.Float(x, y, width, height));
}
private void paintCustomRenderers() {
myGraphics.translate(0, myYShift);
myEditorMarkup.processRangeHighlightersOverlappingWith(myStartOffset, myEndOffset, highlighter -> {
CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer();
if (customRenderer != null) {
int highlighterStart = highlighter.getStartOffset();
int highlighterEnd = highlighter.getEndOffset();
if (highlighterStart <= myEndOffset && highlighterEnd >= myStartOffset &&
myClipDetector.rangeCanBeVisible(highlighterStart, highlighterEnd)) {
if (customRenderer.isForeground()) {
myForegroundCustomHighlighters.add(highlighter);
}
else {
customRenderer.paint(myEditor, highlighter, myGraphics);
}
}
}
return true;
});
myGraphics.translate(0, -myYShift);
}
private void paintForegroundCustomRenderers() {
if (!myForegroundCustomHighlighters.isEmpty()) {
myGraphics.translate(0, myYShift);
for (RangeHighlighter highlighter : myForegroundCustomHighlighters) {
CustomHighlighterRenderer customRenderer = highlighter.getCustomRenderer();
if (customRenderer != null) {
customRenderer.paint(myEditor, highlighter, myGraphics);
}
}
myGraphics.translate(0, -myYShift);
}
}
private void paintLineMarkersSeparators(MarkupModelEx markupModel) {
markupModel.processRangeHighlightersOverlappingWith(mySeparatorHighlightersStartOffset, mySeparatorHighlightersEndOffset,
highlighter -> {
paintLineMarkerSeparator(highlighter);
return true;
});
}
private void paintLineMarkerSeparator(RangeHighlighter marker) {
Color separatorColor = marker.getLineSeparatorColor();
LineSeparatorRenderer lineSeparatorRenderer = marker.getLineSeparatorRenderer();
if (separatorColor == null && lineSeparatorRenderer == null) {
return;
}
boolean isTop = marker.getLineSeparatorPlacement() == SeparatorPlacement.TOP;
int edgeOffset = isTop ? myDocument.getLineStartOffset(myDocument.getLineNumber(marker.getStartOffset()))
: myDocument.getLineEndOffset(myDocument.getLineNumber(marker.getEndOffset()));
int visualLine = myView.offsetToVisualLine(edgeOffset, !isTop);
int y = (isTop ? EditorUtil.getVisualLineAreaStartY(myEditor, visualLine)
: EditorUtil.getVisualLineAreaEndY(myEditor, visualLine))
- 1 + myYShift;
int startX = myCorrector.lineSeparatorStart(myClip.x);
int endX = myCorrector.lineSeparatorEnd(myClip.x + myClip.width);
myGraphics.setColor(separatorColor);
if (lineSeparatorRenderer != null) {
lineSeparatorRenderer.drawLine(myGraphics, startX, endX, y);
}
else {
LinePainter2D.paint(myGraphics, startX, y, endX, y);
}
}
private void paintTextWithEffects() {
myTextDrawingTasks.forEach(t -> t.accept(myGraphics));
ComplexTextFragment.flushDrawingCache(myGraphics);
}
@Nullable
private TextAttributes getInnerHighlighterAttributes(@NotNull FoldRegion region) {
if (region.areInnerHighlightersMuted()) return null;
List<RangeHighlighterEx> innerHighlighters = new ArrayList<>();
collectVisibleInnerHighlighters(region, myEditorMarkup, innerHighlighters);
collectVisibleInnerHighlighters(region, myDocMarkup, innerHighlighters);
if (innerHighlighters.isEmpty()) return null;
innerHighlighters.sort(IterationState.BY_LAYER_THEN_ATTRIBUTES);
Color fgColor = null;
Color bgColor = null;
Color effectColor = null;
EffectType effectType = null;
for (RangeHighlighter h : innerHighlighters) {
TextAttributes attrs = h.getTextAttributes();
if (attrs == null) continue;
if (fgColor == null && attrs.getForegroundColor() != null) fgColor = attrs.getForegroundColor();
if (bgColor == null && attrs.getBackgroundColor() != null) bgColor = attrs.getBackgroundColor();
if (effectColor == null && attrs.getEffectColor() != null) {
EffectType type = attrs.getEffectType();
if (type != null && type != EffectType.BOXED && type != EffectType.ROUNDED_BOX && type != EffectType.STRIKEOUT) {
effectColor = attrs.getEffectColor();
effectType = type;
}
}
}
return new TextAttributes(fgColor, bgColor, effectColor, effectType, Font.PLAIN);
}
private static void collectVisibleInnerHighlighters(@NotNull FoldRegion region, @NotNull MarkupModelEx markupModel,
@NotNull List<? super RangeHighlighterEx> highlighters) {
int startOffset = region.getStartOffset();
int endOffset = region.getEndOffset();
markupModel.processRangeHighlightersOverlappingWith(startOffset, endOffset, h -> {
if (h.isVisibleIfFolded() && h.getAffectedAreaStartOffset() >= startOffset && h.getAffectedAreaEndOffset() <= endOffset) {
highlighters.add(h);
}
return true;
});
}
private float paintLineLayoutWithEffect(LineLayout layout, float x, float y,
@Nullable Color effectColor, @Nullable EffectType effectType) {
paintTextEffect(x, x + layout.getWidth(), (int)y, effectColor, effectType, false);
for (LineLayout.VisualFragment fragment : layout.getFragmentsInVisualOrder(x)) {
fragment.draw(myGraphics, fragment.getStartX(), y);
x = fragment.getEndX();
}
return x;
}
private void paintTextEffect(float xFrom,
float xTo,
int y,
@Nullable Color effectColor,
@Nullable EffectType effectType,
boolean allowBorder) {
if (effectColor == null) {
return;
}
myGraphics.setColor(effectColor);
int xStart = (int)xFrom;
int xEnd = (int)xTo;
if (effectType == EffectType.LINE_UNDERSCORE) {
EffectPainter.LINE_UNDERSCORE.paint(myGraphics, xStart, y, xEnd - xStart, myDescent,
myEditor.getColorsScheme().getFont(EditorFontType.PLAIN));
}
else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) {
EffectPainter.BOLD_LINE_UNDERSCORE.paint(myGraphics, xStart, y, xEnd - xStart, myDescent,
myEditor.getColorsScheme().getFont(EditorFontType.PLAIN));
}
else if (effectType == EffectType.STRIKEOUT) {
EffectPainter.STRIKE_THROUGH.paint(myGraphics, xStart, y, xEnd - xStart, myView.getCharHeight(),
myEditor.getColorsScheme().getFont(EditorFontType.PLAIN));
}
else if (effectType == EffectType.WAVE_UNDERSCORE) {
EffectPainter.WAVE_UNDERSCORE.paint(myGraphics, xStart, y, xEnd - xStart, myDescent,
myEditor.getColorsScheme().getFont(EditorFontType.PLAIN));
}
else if (effectType == EffectType.BOLD_DOTTED_LINE) {
EffectPainter.BOLD_DOTTED_UNDERSCORE.paint(myGraphics, xStart, y, xEnd - xStart, myDescent,
myEditor.getColorsScheme().getFont(EditorFontType.PLAIN));
}
else if (allowBorder && (effectType == EffectType.BOXED || effectType == EffectType.ROUNDED_BOX)) {
drawSimpleBorder(xFrom, xTo, y - myAscent, effectType == EffectType.ROUNDED_BOX);
}
}
private static int calcFeatureSize(int unscaledSize, float scale) {
return Math.max(1, Math.round(scale * unscaledSize));
}
private static float roundToPixelCenter(double value, Graphics2D g) {
return (float)(PaintUtil.alignToInt(value, g, PaintUtil.RoundingMode.FLOOR) + PaintUtil.devPixel(g) / 2);
}
private void paintWhitespace(float x, int y, int start, int end,
LineWhitespacePaintingStrategy whitespacePaintingStrategy,
VisualLineFragmentsIterator.Fragment fragment, BasicStroke stroke, float scale) {
if (!whitespacePaintingStrategy.showAnyWhitespace()) return;
boolean restoreStroke = false;
Stroke defaultStroke = myGraphics.getStroke();
Color color = myEditor.getColorsScheme().getColor(EditorColors.WHITESPACES_COLOR);
boolean isRtl = fragment.isRtl();
int baseStartOffset = fragment.getStartOffset();
int startOffset = isRtl ? baseStartOffset - start : baseStartOffset + start;
int yToUse = y - 1;
for (int i = start; i < end; i++) {
int charOffset = isRtl ? baseStartOffset - i - 1 : baseStartOffset + i;
char c = myText.charAt(charOffset);
if (" \t\u3000".indexOf(c) >= 0 && whitespacePaintingStrategy.showWhitespaceAtOffset(charOffset)) {
int startX = (int)fragment.offsetToX(x, startOffset, isRtl ? baseStartOffset - i : baseStartOffset + i);
int endX = (int)fragment.offsetToX(x, startOffset, isRtl ? baseStartOffset - i - 1 : baseStartOffset + i + 1);
if (c == ' ') {
// making center point lie at the center of device pixel
float dotX = roundToPixelCenter((startX + endX) / 2., myGraphics) - scale / 2;
float dotY = roundToPixelCenter(yToUse + 1 - myAscent + myLineHeight / 2., myGraphics) - scale / 2;
myTextDrawingTasks.add(g -> {
CachingPainter.paint(g, dotX, dotY, scale, scale,
_g -> {
_g.setColor(color);
_g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
_g.fill(new Ellipse2D.Float(0, 0, scale, scale));
}, ourCachedDot, color);
});
}
else if (c == '\t') {
double strokeWidth = Math.max(scale, PaintUtil.devPixel(myGraphics));
if (Registry.is("editor.old.tab.painting")) {
int tabEndX = endX - (int)(myView.getPlainSpaceWidth() / 4);
int height = myView.getCharHeight();
Color tabColor = color == null ? null : ColorUtil.mix(myBackgroundColor, color, 0.7);
myTextDrawingTasks.add(g -> {
int halfHeight = height / 2;
int yMid = yToUse - halfHeight;
int yTop = yToUse - height;
g.setColor(tabColor);
LinePainter2D.paint(g, startX, yMid, tabEndX, yMid, LinePainter2D.StrokeType.INSIDE, strokeWidth);
LinePainter2D.paint(g, tabEndX, yToUse, tabEndX, yTop, LinePainter2D.StrokeType.INSIDE, strokeWidth);
g.fillPolygon(new int[]{tabEndX - halfHeight, tabEndX - halfHeight, tabEndX}, new int[]{yToUse, yTop, yMid}, 3);
});
}
else {
int yMid = yToUse - myView.getCharHeight() / 2;
int tabEndX = Math.max(startX + 1, endX - calcFeatureSize(5, scale));
myTextDrawingTasks.add(g -> {
g.setColor(color);
LinePainter2D.paint(g, startX, yMid, tabEndX, yMid, LinePainter2D.StrokeType.INSIDE, strokeWidth);
});
}
}
else if (c == '\u3000') { // ideographic space
int charHeight = myView.getCharHeight();
int strokeWidth = Math.round(stroke.getLineWidth());
myTextDrawingTasks.add(g -> {
g.setColor(color);
g.setStroke(stroke);
g.drawRect(startX + JBUIScale.scale(2) + strokeWidth / 2, yToUse - charHeight + strokeWidth / 2,
endX - startX - JBUIScale.scale(4) - (strokeWidth - 1), charHeight - (strokeWidth - 1));
});
restoreStroke = true;
}
}
}
if (restoreStroke) {
myTextDrawingTasks.add((g) -> {
g.setStroke(defaultStroke);
});
}
}
private void collectExtensions(int visualLine, int offset) {
myEditor.processLineExtensions(myDocument.getLineNumber(offset), (info) -> {
List<LineExtensionData> list = myExtensionData.get(visualLine);
if (list == null) myExtensionData.put(visualLine, list = new ArrayList<>());
list.add(new LineExtensionData(info, LineLayout.create(myView, info.getText(), info.getFontType())));
return true;
});
}
private void paintLineExtensionsBackground(int visualLine, float x, int y) {
List<LineExtensionData> data = myExtensionData.get(visualLine);
if (data == null) return;
for (LineExtensionData datum : data) {
float width = datum.layout.getWidth();
paintBackground(datum.info.getBgColor(), x, y, width);
x += width;
}
}
private void paintLineExtensions(int visualLine, int logicalLine, float x, int y) {
List<LineExtensionData> data = myExtensionData.get(visualLine);
if (data == null) return;
for (LineExtensionData datum : data) {
myGraphics.setColor(datum.info.getColor());
x = paintLineLayoutWithEffect(datum.layout, x, y, datum.info.getEffectColor(), datum.info.getEffectType());
}
int currentLineWidth = myCorrector.lineWidth(visualLine, x);
EditorSizeManager sizeManager = myView.getSizeManager();
if (currentLineWidth > sizeManager.getMaxLineWithExtensionWidth()) {
sizeManager.setMaxLineWithExtensionWidth(logicalLine, currentLineWidth);
myEditor.getContentComponent().revalidate();
}
}
private void paintHighlightersAfterEndOfLine(MarkupModelEx markupModel) {
markupModel.processRangeHighlightersOverlappingWith(myStartOffset, myEndOffset, highlighter -> {
if (highlighter.getStartOffset() >= myStartOffset) {
paintHighlighterAfterEndOfLine(highlighter);
}
return true;
});
}
private void paintHighlighterAfterEndOfLine(RangeHighlighterEx highlighter) {
if (!highlighter.isAfterEndOfLine()) {
return;
}
int startOffset = highlighter.getStartOffset();
int lineEndOffset = myDocument.getLineEndOffset(myDocument.getLineNumber(startOffset));
if (myEditor.getFoldingModel().isOffsetCollapsed(lineEndOffset)) return;
Point2D lineEnd = myView.offsetToXY(lineEndOffset, true, false);
float x = (float)lineEnd.getX();
int y = (int)lineEnd.getY() + myYShift;
TextAttributes attributes = highlighter.getTextAttributes();
paintBackground(attributes, x, y, myView.getPlainSpaceWidth());
if (attributes != null) {
attributes.forEachEffect(
(type, color) -> paintTextEffect(x, x + myView.getPlainSpaceWidth() - 1, y + myAscent, color, type, false));
}
}
private void paintBorderEffect(EditorHighlighter highlighter) {
HighlighterIterator it = highlighter.createIterator(myStartOffset);
while (!it.atEnd() && it.getStart() < myEndOffset) {
TextAttributes attributes = it.getTextAttributes();
EffectDescriptor borderDescriptor = getBorderDescriptor(attributes);
if (borderDescriptor != null) {
paintBorderEffect(it.getStart(), it.getEnd(), borderDescriptor);
}
it.advance();
}
}
private void paintBorderEffect(MarkupModelEx markupModel) {
markupModel.processRangeHighlightersOverlappingWith(myStartOffset, myEndOffset, rangeHighlighter -> {
TextAttributes attributes = rangeHighlighter.getTextAttributes();
EffectDescriptor borderDescriptor = getBorderDescriptor(attributes);
if (borderDescriptor != null) {
paintBorderEffect(rangeHighlighter.getAffectedAreaStartOffset(), rangeHighlighter.getAffectedAreaEndOffset(), borderDescriptor);
}
return true;
});
}
/**
* @return {@link EffectDescriptor descriptor} of border effect if attributes contains a border effect with not null color and
* null otherwise
*/
@Contract("null -> null")
@Nullable
private static EffectDescriptor getBorderDescriptor(@Nullable TextAttributes attributes) {
return attributes == null || !attributes.hasEffects()
? null
: TextAttributesEffectsBuilder.create(attributes).getEffectDescriptor(FRAME_SLOT);
}
private void paintBorderEffect(int startOffset, int endOffset, EffectDescriptor borderDescriptor) {
startOffset = DocumentUtil.alignToCodePointBoundary(myDocument, startOffset);
endOffset = DocumentUtil.alignToCodePointBoundary(myDocument, endOffset);
if (!myClipDetector.rangeCanBeVisible(startOffset, endOffset)) return;
int startLine = myDocument.getLineNumber(startOffset);
int endLine = myDocument.getLineNumber(endOffset);
if (startLine + 1 == endLine &&
startOffset == myDocument.getLineStartOffset(startLine) &&
endOffset == myDocument.getLineStartOffset(endLine)) {
// special case of line highlighters
endLine
endOffset = myDocument.getLineEndOffset(endLine);
}
boolean rounded = borderDescriptor.effectType == EffectType.ROUNDED_BOX;
myGraphics.setColor(borderDescriptor.effectColor);
VisualPosition startPosition = myView.offsetToVisualPosition(startOffset, true, false);
VisualPosition endPosition = myView.offsetToVisualPosition(endOffset, false, true);
if (startPosition.line == endPosition.line) {
int y = myView.visualLineToY(startPosition.line) + myYShift;
TFloatArrayList ranges = adjustedLogicalRangeToVisualRanges(startOffset, endOffset);
for (int i = 0; i < ranges.size() - 1; i += 2) {
float startX = myCorrector.singleLineBorderStart(ranges.get(i));
float endX = myCorrector.singleLineBorderEnd(ranges.get(i + 1));
drawSimpleBorder(startX, endX, y, rounded);
}
}
else {
TFloatArrayList leadingRanges = adjustedLogicalRangeToVisualRanges(
startOffset, myView.visualPositionToOffset(new VisualPosition(startPosition.line, Integer.MAX_VALUE, true)));
TFloatArrayList trailingRanges = adjustedLogicalRangeToVisualRanges(
myView.visualPositionToOffset(new VisualPosition(endPosition.line, 0)), endOffset);
if (!leadingRanges.isEmpty() && !trailingRanges.isEmpty()) {
int minX = Math.min(myCorrector.minX(startPosition.line, endPosition.line), (int)leadingRanges.get(0));
int maxX = Math.max(myCorrector.maxX(startPosition.line, endPosition.line), (int)trailingRanges.get(trailingRanges.size() - 1));
boolean containsInnerLines = endPosition.line > startPosition.line + 1;
int lineHeight = myLineHeight - 1;
int leadingTopY = myView.visualLineToY(startPosition.line) + myYShift;
int leadingBottomY = leadingTopY + lineHeight;
int trailingTopY = myView.visualLineToY(endPosition.line) + myYShift;
int trailingBottomY = trailingTopY + lineHeight;
float start = 0;
float end = 0;
float leftGap = leadingRanges.get(0) - (containsInnerLines ? minX : trailingRanges.get(0));
int adjustY = leftGap == 0 ? 2 : leftGap > 0 ? 1 : 0; // avoiding 1-pixel gap between aligned lines
for (int i = 0; i < leadingRanges.size() - 1; i += 2) {
start = leadingRanges.get(i);
end = leadingRanges.get(i + 1);
if (i > 0) {
drawLine(leadingRanges.get(i - 1), leadingBottomY, start, leadingBottomY, rounded);
}
drawLine(start, leadingBottomY + (i == 0 ? adjustY : 0), start, leadingTopY, rounded);
if ((i + 2) < leadingRanges.size()) {
drawLine(start, leadingTopY, end, leadingTopY, rounded);
drawLine(end, leadingTopY, end, leadingBottomY, rounded);
}
}
end = Math.max(end, maxX);
drawLine(start, leadingTopY, end, leadingTopY, rounded);
drawLine(end, leadingTopY, end, trailingTopY - 1, rounded);
float targetX = trailingRanges.get(trailingRanges.size() - 1);
drawLine(end, trailingTopY - 1, targetX, trailingTopY - 1, rounded);
adjustY = end == targetX ? -2 : -1; // for lastX == targetX we need to avoid a gap when rounding is used
for (int i = trailingRanges.size() - 2; i >= 0; i -= 2) {
start = trailingRanges.get(i);
end = trailingRanges.get(i + 1);
drawLine(end, trailingTopY + (i == 0 ? adjustY : 0), end, trailingBottomY, rounded);
drawLine(end, trailingBottomY, start, trailingBottomY, rounded);
drawLine(start, trailingBottomY, start, trailingTopY, rounded);
if (i > 0) {
drawLine(start, trailingTopY, trailingRanges.get(i - 1), trailingTopY, rounded);
}
}
float lastX = start;
if (containsInnerLines) {
if (start != minX) {
drawLine(start, trailingTopY, start, trailingTopY - 1, rounded);
drawLine(start, trailingTopY - 1, minX, trailingTopY - 1, rounded);
drawLine(minX, trailingTopY - 1, minX, leadingBottomY + 1, rounded);
}
else {
drawLine(minX, trailingTopY, minX, leadingBottomY + 1, rounded);
}
lastX = minX;
}
targetX = leadingRanges.get(0);
if (lastX < targetX) {
drawLine(lastX, leadingBottomY + 1, targetX, leadingBottomY + 1, rounded);
}
else {
drawLine(lastX, leadingBottomY + 1, lastX, leadingBottomY, rounded);
drawLine(lastX, leadingBottomY, targetX, leadingBottomY, rounded);
}
}
}
}
private void drawSimpleBorder(float xStart, float xEnd, float y, boolean rounded) {
Shape border = getBorderShape(xStart, y, xEnd - xStart, myLineHeight, 1, rounded);
if (border != null) {
Object old = myGraphics.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
myGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
myGraphics.fill(border);
myGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, old);
}
}
private static Shape getBorderShape(float x, float y, float width, int height, int thickness, boolean rounded) {
if (width <= 0 || height <= 0) return null;
Shape outer = rounded
? new RoundRectangle2D.Float(x, y, width, height, 2, 2)
: new Rectangle2D.Float(x, y, width, height);
int doubleThickness = 2 * thickness;
if (width <= doubleThickness || height <= doubleThickness) return outer;
Shape inner = new Rectangle2D.Float(x + thickness, y + thickness, width - doubleThickness, height - doubleThickness);
Path2D path = new Path2D.Float(Path2D.WIND_EVEN_ODD);
path.append(outer, false);
path.append(inner, false);
return path;
}
private void drawLine(float x1, int y1, float x2, int y2, boolean rounded) {
if (rounded) {
UIUtil.drawLinePickedOut(myGraphics, (int)x1, y1, (int)x2, y2);
}
else {
LinePainter2D.paint(myGraphics, (int)x1, y1, (int)x2, y2);
}
}
/**
* Returns ranges obtained from {@link #logicalRangeToVisualRanges(int, int)}, adjusted for painting range border - lines should
* line inside target ranges (except for empty range). Target offsets are supposed to be located on the same visual line.
*/
private TFloatArrayList adjustedLogicalRangeToVisualRanges(int startOffset, int endOffset) {
TFloatArrayList ranges = logicalRangeToVisualRanges(startOffset, endOffset);
for (int i = 0; i < ranges.size() - 1; i += 2) {
float startX = ranges.get(i);
float endX = ranges.get(i + 1);
if (startX == endX) {
if (startX > 0) {
startX
}
else {
endX++;
}
}
else {
endX
}
ranges.set(i, startX);
ranges.set(i + 1, endX);
}
return ranges;
}
/**
* Returns a list of pairs of x coordinates for visual ranges representing given logical range. If
* {@code startOffset == endOffset}, a pair of equal numbers is returned, corresponding to target position. Target offsets are
* supposed to be located on the same visual line.
*/
private TFloatArrayList logicalRangeToVisualRanges(int startOffset, int endOffset) {
assert startOffset <= endOffset;
TFloatArrayList result = new TFloatArrayList();
if (myDocument.getTextLength() == 0) {
int minX = myCorrector.emptyTextX();
result.add(minX);
result.add(minX);
}
else {
float lastX = -1;
for (VisualLineFragmentsIterator.Fragment fragment : VisualLineFragmentsIterator.create(myView, startOffset, false, true)) {
int minOffset = fragment.getMinOffset();
int maxOffset = fragment.getMaxOffset();
if (startOffset == endOffset) {
lastX = fragment.getEndX();
Inlay inlay = fragment.getCurrentInlay();
if (inlay != null && !inlay.isRelatedToPrecedingText()) continue;
if (startOffset >= minOffset && startOffset < maxOffset) {
float x = fragment.offsetToX(startOffset);
result.add(x);
result.add(x);
break;
}
}
else if (startOffset < maxOffset && endOffset > minOffset) {
float x1 = minOffset == maxOffset ? fragment.getStartX() : fragment.offsetToX(Math.max(minOffset, startOffset));
float x2 = minOffset == maxOffset ? fragment.getEndX() : fragment.offsetToX(Math.min(maxOffset, endOffset));
if (x1 > x2) {
float tmp = x1;
x1 = x2;
x2 = tmp;
}
if (result.isEmpty() || x1 > result.get(result.size() - 1)) {
result.add(x1);
result.add(x2);
}
else {
result.set(result.size() - 1, x2);
}
}
}
if (startOffset == endOffset && result.isEmpty() && lastX >= 0) {
result.add(lastX);
result.add(lastX);
}
}
return result;
}
private void paintComposedTextDecoration() {
TextRange composedTextRange = myEditor.getComposedTextRange();
if (composedTextRange != null) {
Point2D p1 = myView.offsetToXY(Math.min(composedTextRange.getStartOffset(), myDocument.getTextLength()), true, false);
Point2D p2 = myView.offsetToXY(Math.min(composedTextRange.getEndOffset(), myDocument.getTextLength()), false, true);
int y = (int)p1.getY() + myAscent + 1 + myYShift;
myGraphics.setStroke(IME_COMPOSED_TEXT_UNDERLINE_STROKE);
myGraphics.setColor(myEditor.getColorsScheme().getDefaultForeground());
LinePainter2D.paint(myGraphics, (int)p1.getX(), y, (int)p2.getX(), y);
}
}
private void paintBlockInlays() {
if (!myEditor.getInlayModel().hasBlockElements()) return;
int startX = myView.getInsets().left;
int lineCount = myEditor.getVisibleLineCount();
VisualLinesIterator visLinesIterator = new VisualLinesIterator(myEditor, myStartVisualLine);
while (!visLinesIterator.atEnd()) {
int visualLine = visLinesIterator.getVisualLine();
if (visualLine > myEndVisualLine || visualLine >= lineCount) break;
int y = visLinesIterator.getY() + myYShift;
int curY = y;
List<Inlay> inlaysAbove = visLinesIterator.getBlockInlaysAbove();
if (!inlaysAbove.isEmpty()) {
TextAttributes attributes = getInlayAttributes(visualLine);
for (Inlay inlay : inlaysAbove) {
if (curY <= myClip.y + myYShift) break;
int height = inlay.getHeightInPixels();
if (height > 0) {
int newY = curY - height;
inlay.getRenderer().paint(inlay, myGraphics, new Rectangle(startX, newY, inlay.getWidthInPixels(), height), attributes);
curY = newY;
}
}
}
curY = y + myLineHeight;
List<Inlay> inlaysBelow = visLinesIterator.getBlockInlaysBelow();
if (!inlaysBelow.isEmpty()) {
TextAttributes attributes = getInlayAttributes(visualLine + 1);
for (Inlay inlay : inlaysBelow) {
if (curY >= myClip.y + myClip.height + myYShift) break;
int height = inlay.getHeightInPixels();
if (height > 0) {
inlay.getRenderer().paint(inlay, myGraphics, new Rectangle(startX, curY, inlay.getWidthInPixels(), height), attributes);
curY += height;
}
}
}
visLinesIterator.advance();
}
}
private TextAttributes getInlayAttributes(int visualLine) {
TextAttributes attributes = myBetweenLinesAttributes.get(visualLine);
if (attributes != null) return attributes;
// inlay shown below last document line
return new TextAttributes();
}
@NotNull
private TextAttributes getBetweenLinesAttributes(int bottomVisualLine,
int bottomVisualLineStartOffset,
PeekableIterator<Caret> caretIterator) {
boolean selection = false;
while (caretIterator.hasNext() && caretIterator.peek().getSelectionEnd() < bottomVisualLineStartOffset) caretIterator.next();
if (caretIterator.hasNext()) {
Caret caret = caretIterator.peek();
selection = caret.getSelectionStart() <= bottomVisualLineStartOffset &&
caret.getSelectionStartPosition().line < bottomVisualLine && bottomVisualLine <= caret.getSelectionEndPosition().line;
}
class MyProcessor implements Processor<RangeHighlighterEx> {
private int layer;
private Color backgroundColor;
private MyProcessor(boolean selection) {
backgroundColor = selection ? myEditor.getSelectionModel().getTextAttributes().getBackgroundColor() : null;
layer = backgroundColor == null ? Integer.MIN_VALUE : HighlighterLayer.SELECTION;
}
@Override
public boolean process(RangeHighlighterEx highlighterEx) {
int layer = highlighterEx.getLayer();
if (layer > this.layer &&
highlighterEx.getAffectedAreaStartOffset() < bottomVisualLineStartOffset &&
highlighterEx.getAffectedAreaEndOffset() > bottomVisualLineStartOffset) {
TextAttributes attributes = highlighterEx.getTextAttributes();
Color backgroundColor = attributes == null ? null : attributes.getBackgroundColor();
if (backgroundColor != null) {
this.layer = layer;
this.backgroundColor = backgroundColor;
}
}
return true;
}
}
MyProcessor processor = new MyProcessor(selection);
myDocMarkup.processRangeHighlightersOverlappingWith(bottomVisualLineStartOffset, bottomVisualLineStartOffset, processor);
myEditorMarkup.processRangeHighlightersOverlappingWith(bottomVisualLineStartOffset, bottomVisualLineStartOffset, processor);
TextAttributes attributes = new TextAttributes();
attributes.setBackgroundColor(processor.backgroundColor);
return attributes;
}
private void paintCaret() {
if (myEditor.isPurePaintingMode()) return;
EditorImpl.CaretRectangle[] locations = myEditor.getCaretLocations(true);
if (locations == null) return;
Graphics2D g = IdeBackgroundUtil.getOriginalGraphics(myGraphics);
int nominalLineHeight = myView.getNominalLineHeight();
int topOverhang = myView.getTopOverhang();
EditorSettings settings = myEditor.getSettings();
Color caretColor = myEditor.getColorsScheme().getColor(EditorColors.CARET_COLOR);
if (caretColor == null) caretColor = new JBColor(CARET_DARK, CARET_LIGHT);
int minX = myView.getInsets().left;
for (EditorImpl.CaretRectangle location : locations) {
float x = (float)location.myPoint.getX();
int y = (int)location.myPoint.getY() - topOverhang + myYShift;
Caret caret = location.myCaret;
CaretVisualAttributes attr = caret == null ? CaretVisualAttributes.DEFAULT : caret.getVisualAttributes();
g.setColor(attr.getColor() != null ? attr.getColor() : caretColor);
boolean isRtl = location.myIsRtl;
if (myEditor.isInsertMode() != settings.isBlockCursor()) {
int lineWidth = JBUIScale.scale(attr.getWidth(settings.getLineCursorWidth()));
// fully cover extra character's pixel which can appear due to antialiasing
// see IDEA-148843 for more details
if (x > minX && lineWidth > 1) x -= 1 / JBUIScale.sysScale(g);
g.fill(new Rectangle2D.Float(x, y, lineWidth, nominalLineHeight));
if (myDocument.getTextLength() > 0 && caret != null &&
!myView.getTextLayoutCache().getLineLayout(caret.getLogicalPosition().line).isLtr()) {
GeneralPath triangle = new GeneralPath(Path2D.WIND_NON_ZERO, 3);
triangle.moveTo(isRtl ? x + lineWidth : x, y);
triangle.lineTo(isRtl ? x + lineWidth - CARET_DIRECTION_MARK_SIZE : x + CARET_DIRECTION_MARK_SIZE, y);
triangle.lineTo(isRtl ? x + lineWidth : x, y + CARET_DIRECTION_MARK_SIZE);
triangle.closePath();
g.fill(triangle);
}
}
else {
float width = location.myWidth;
float startX = Math.max(minX, isRtl ? x - width : x);
g.fill(new Rectangle2D.Float(startX, y, width, nominalLineHeight));
if (myDocument.getTextLength() > 0 && caret != null) {
int targetVisualColumn = caret.getVisualPosition().column - (isRtl ? 1 : 0);
for (VisualLineFragmentsIterator.Fragment fragment : VisualLineFragmentsIterator.create(myView,
caret.getVisualLineStart(),
false)) {
if (fragment.getCurrentInlay() != null) continue;
int startVisualColumn = fragment.getStartVisualColumn();
int endVisualColumn = fragment.getEndVisualColumn();
if (startVisualColumn <= targetVisualColumn && targetVisualColumn < endVisualColumn) {
g.setColor(ColorUtil.isDark(caretColor) ? CARET_LIGHT : CARET_DARK);
fragment.draw(startX, y + topOverhang + myAscent,
fragment.visualColumnToOffset(targetVisualColumn - startVisualColumn),
fragment.visualColumnToOffset(targetVisualColumn + 1 - startVisualColumn)).accept(g);
break;
}
}
ComplexTextFragment.flushDrawingCache(g);
}
}
}
}
private interface MarginWidthConsumer {
void process(float width);
}
private void paintLineFragments(VisualLinesIterator visLineIterator,
int y,
LineFragmentPainter painter,
MarginWidthConsumer marginWidthConsumer) {
int visualLine = visLineIterator.getVisualLine();
float x = myCorrector.startX(visualLine) + (visualLine == 0 ? myView.getPrefixTextWidthInPixels() : 0);
int offset = visLineIterator.getVisualLineStartOffset();
int visualLineEndOffset = visLineIterator.getVisualLineEndOffset();
IterationState it = null;
int prevEndOffset = -1;
boolean firstFragment = true;
int maxColumn = 0;
int endLogicalLine = visLineIterator.getEndLogicalLine();
boolean marginReached = false;
for (VisualLineFragmentsIterator.Fragment fragment : VisualLineFragmentsIterator.create(myView, visLineIterator, null, true)) {
int fragmentStartOffset = fragment.getStartOffset();
int start = fragmentStartOffset;
int end = fragment.getEndOffset();
x = fragment.getStartX();
if (firstFragment) {
firstFragment = false;
SoftWrap softWrap = myEditor.getSoftWrapModel().getSoftWrap(offset);
boolean hasSoftWrap = softWrap != null;
if (hasSoftWrap || myEditor.isRightAligned()) {
prevEndOffset = offset;
it = new IterationState(myEditor, offset == 0 ? 0 : DocumentUtil.getPreviousCodePointOffset(myDocument, offset),
visualLineEndOffset,
myCaretData, false, false, false, false);
if (it.getEndOffset() <= offset) {
it.advance();
}
if (x >= myClip.getMinX()) {
TextAttributes attributes = it.getStartOffset() == offset ? it.getBeforeLineStartBackgroundAttributes() :
it.getMergedAttributes();
painter.paintBeforeLineStart(attributes, hasSoftWrap, fragment.getStartVisualColumn(), x, y);
}
}
}
FoldRegion foldRegion = fragment.getCurrentFoldRegion();
if (foldRegion == null) {
if (start != prevEndOffset) {
it = new IterationState(myEditor, start, fragment.isRtl() ? offset : visualLineEndOffset,
myCaretData, false, false, false, fragment.isRtl());
}
prevEndOffset = end;
assert it != null;
if (start == end) { // special case of inlays
if (start == it.getEndOffset() && !it.atEnd()) {
it.advance();
}
TextAttributes attributes = it.getStartOffset() == start ? it.getBreakAttributes() : it.getMergedAttributes();
float xNew = fragment.getEndX();
if (xNew >= myClip.getMinX()) {
painter.paint(fragment, 0, 0, attributes, x, xNew, y);
}
x = xNew;
}
else {
while (fragment.isRtl() ? start > end : start < end) {
if (fragment.isRtl() ? it.getEndOffset() >= start : it.getEndOffset() <= start) {
assert !it.atEnd();
it.advance();
}
TextAttributes attributes = it.getMergedAttributes();
int curEnd = fragment.isRtl() ? Math.max(it.getEndOffset(), end) : Math.min(it.getEndOffset(), end);
float xNew = fragment.offsetToX(x, start, curEnd);
if (xNew >= myClip.getMinX()) {
painter.paint(fragment,
fragment.isRtl() ? fragmentStartOffset - start : start - fragmentStartOffset,
fragment.isRtl() ? fragmentStartOffset - curEnd : curEnd - fragmentStartOffset,
attributes, x, xNew, y);
}
x = xNew;
start = curEnd;
}
if (marginWidthConsumer != null && fragment.getEndLogicalLine() == endLogicalLine &&
fragment.getStartLogicalColumn() <= myMarginColumns && fragment.getEndLogicalColumn() > myMarginColumns) {
marginWidthConsumer.process(fragment.visualColumnToX(fragment.logicalToVisualColumn(myMarginColumns)));
marginReached = true;
}
}
}
else {
float xNew = fragment.getEndX();
if (xNew >= myClip.getMinX()) {
painter.paint(fragment, 0, fragment.getVisualLength(), getFoldRegionAttributes(foldRegion), x, xNew, y);
}
x = xNew;
prevEndOffset = -1;
it = null;
}
if (x > myClip.getMaxX()) return;
maxColumn = fragment.getEndVisualColumn();
}
if (firstFragment && myEditor.isRightAligned()) {
it = new IterationState(myEditor, offset, visualLineEndOffset, myCaretData, false, false, false, false);
if (it.getEndOffset() <= offset) {
it.advance();
}
painter.paintBeforeLineStart(it.getBeforeLineStartBackgroundAttributes(), false, maxColumn, x, y);
}
if (it == null || it.getEndOffset() != visualLineEndOffset) {
it = new IterationState(myEditor, visualLineEndOffset == offset
? visualLineEndOffset : DocumentUtil.getPreviousCodePointOffset(myDocument, visualLineEndOffset),
visualLineEndOffset, myCaretData, false, false, false, false);
}
if (!it.atEnd()) {
it.advance();
}
assert it.atEnd();
painter.paintAfterLineEnd(it, maxColumn, x, y);
if (marginWidthConsumer != null && !marginReached &&
(visualLine == myEditor.getCaretModel().getVisualPosition().line || x > myMarginColumns * myView.getPlainSpaceWidth())) {
int endLogicalColumn = myView.offsetToLogicalPosition(visualLineEndOffset).column;
if (endLogicalColumn <= myMarginColumns) {
marginWidthConsumer.process(x + (myMarginColumns - endLogicalColumn) * myView.getPlainSpaceWidth());
}
}
}
private TextAttributes getFoldRegionAttributes(FoldRegion foldRegion) {
TextAttributes selectionAttributes = isSelected(foldRegion) ? myEditor.getSelectionModel().getTextAttributes() : null;
TextAttributes defaultAttributes = getDefaultAttributes();
if (myEditor.isInFocusMode(foldRegion)) {
return ObjectUtils.notNull(myEditor.getUserData(FocusModeModel.FOCUS_MODE_ATTRIBUTES), getDefaultAttributes());
}
TextAttributes foldAttributes = myEditor.getFoldingModel().getPlaceholderAttributes();
return mergeAttributes(mergeAttributes(selectionAttributes, foldAttributes), defaultAttributes);
}
@SuppressWarnings("UseJBColor")
private TextAttributes getDefaultAttributes() {
TextAttributes attributes = myEditor.getColorsScheme().getAttributes(HighlighterColors.TEXT);
if (attributes.getForegroundColor() == null) attributes.setForegroundColor(Color.black);
if (attributes.getBackgroundColor() == null) attributes.setBackgroundColor(Color.white);
return attributes;
}
private static boolean isSelected(FoldRegion foldRegion) {
int regionStart = foldRegion.getStartOffset();
int regionEnd = foldRegion.getEndOffset();
int[] selectionStarts = foldRegion.getEditor().getSelectionModel().getBlockSelectionStarts();
int[] selectionEnds = foldRegion.getEditor().getSelectionModel().getBlockSelectionEnds();
for (int i = 0; i < selectionStarts.length; i++) {
int start = selectionStarts[i];
int end = selectionEnds[i];
if (regionStart >= start && regionEnd <= end) return true;
}
return false;
}
private static TextAttributes mergeAttributes(TextAttributes primary, TextAttributes secondary) {
if (primary == null) return secondary;
if (secondary == null) return primary;
TextAttributes result =
new TextAttributes(primary.getForegroundColor() == null ? secondary.getForegroundColor() : primary.getForegroundColor(),
primary.getBackgroundColor() == null ? secondary.getBackgroundColor() : primary.getBackgroundColor(),
null, null,
primary.getFontType() == Font.PLAIN ? secondary.getFontType() : primary.getFontType());
return TextAttributesEffectsBuilder.create(secondary).coverWith(primary).applyTo(result);
}
}
interface LineFragmentPainter {
void paintBeforeLineStart(TextAttributes attributes, boolean hasSoftWrap, int columnEnd, float xEnd, int y);
void paint(VisualLineFragmentsIterator.Fragment fragment, int start, int end, TextAttributes attributes,
float xStart, float xEnd, int y);
void paintAfterLineEnd(IterationState iterationState, int columnStart, float x, int y);
}
private static class LineWhitespacePaintingStrategy {
private final boolean myWhitespaceShown;
private final boolean myLeadingWhitespaceShown;
private final boolean myInnerWhitespaceShown;
private final boolean myTrailingWhitespaceShown;
// Offsets on current line where leading whitespace ends and trailing whitespace starts correspondingly.
private int currentLeadingEdge;
private int currentTrailingEdge;
LineWhitespacePaintingStrategy(EditorSettings settings) {
myWhitespaceShown = settings.isWhitespacesShown();
myLeadingWhitespaceShown = settings.isLeadingWhitespaceShown();
myInnerWhitespaceShown = settings.isInnerWhitespaceShown();
myTrailingWhitespaceShown = settings.isTrailingWhitespaceShown();
}
private boolean showAnyWhitespace() {
return myWhitespaceShown && (myLeadingWhitespaceShown || myInnerWhitespaceShown || myTrailingWhitespaceShown);
}
private void update(CharSequence chars, int lineStart, int lineEnd) {
if (showAnyWhitespace() && !(myLeadingWhitespaceShown && myInnerWhitespaceShown && myTrailingWhitespaceShown)) {
currentTrailingEdge = CharArrayUtil.shiftBackward(chars, lineStart, lineEnd - 1, WHITESPACE_CHARS) + 1;
currentLeadingEdge = CharArrayUtil.shiftForward(chars, lineStart, currentTrailingEdge, WHITESPACE_CHARS);
}
}
private boolean showWhitespaceAtOffset(int offset) {
return myWhitespaceShown
&& (offset < currentLeadingEdge ? myLeadingWhitespaceShown :
offset >= currentTrailingEdge ? myTrailingWhitespaceShown :
myInnerWhitespaceShown);
}
}
private interface XCorrector {
float startX(int line);
int lineWidth(int line, float x);
int emptyTextX();
int minX(int startLine, int endLine);
int maxX(int startLine, int endLine);
int lineSeparatorStart(int minX);
int lineSeparatorEnd(int maxX);
float singleLineBorderStart(float x);
float singleLineBorderEnd(float x);
int marginX(float marginWidth);
List<Integer> softMarginsX();
@NotNull
static XCorrector create(@NotNull EditorView view) {
return view.getEditor().isRightAligned() ? new RightAligned(view) : new LeftAligned(view);
}
class LeftAligned implements XCorrector {
private final EditorView myView;
private final int myLeftInset;
private LeftAligned(@NotNull EditorView view) {
myView = view;
myLeftInset = myView.getInsets().left;
}
@Override
public float startX(int line) {
return myLeftInset;
}
@Override
public int emptyTextX() {
return myLeftInset;
}
@Override
public int minX(int startLine, int endLine) {
return myLeftInset;
}
@Override
public int maxX(int startLine, int endLine) {
return minX(startLine, endLine) + myView.getMaxTextWidthInLineRange(startLine, endLine - 1) - 1;
}
@Override
public float singleLineBorderStart(float x) {
return x;
}
@Override
public float singleLineBorderEnd(float x) {
return x + 1;
}
@Override
public int lineWidth(int line, float x) {
return (int)x - myLeftInset;
}
@Override
public int lineSeparatorStart(int maxX) {
return myLeftInset;
}
@Override
public int lineSeparatorEnd(int maxX) {
return isMarginShown(myView.getEditor()) ? Math.min(marginX(Session.getBaseMarginWidth(myView)), maxX) : maxX;
}
@Override
public int marginX(float marginWidth) {
return (int)(myLeftInset + marginWidth);
}
@Override
public List<Integer> softMarginsX() {
List<Integer> margins = myView.getEditor().getSettings().getSoftMargins();
List<Integer> result = new ArrayList<>(margins.size());
for (Integer margin : margins) {
result.add((int)(myLeftInset + margin * myView.getPlainSpaceWidth()));
}
return result;
}
}
class RightAligned implements XCorrector {
private final EditorView myView;
private RightAligned(@NotNull EditorView view) {
myView = view;
}
@Override
public float startX(int line) {
return myView.getRightAlignmentLineStartX(line);
}
@Override
public int lineWidth(int line, float x) {
return (int)(x - myView.getRightAlignmentLineStartX(line));
}
@Override
public int emptyTextX() {
return myView.getRightAlignmentMarginX();
}
@Override
public int minX(int startLine, int endLine) {
return myView.getRightAlignmentMarginX() - myView.getMaxTextWidthInLineRange(startLine, endLine - 1) - 1;
}
@Override
public int maxX(int startLine, int endLine) {
return myView.getRightAlignmentMarginX() - 1;
}
@Override
public float singleLineBorderStart(float x) {
return x - 1;
}
@Override
public float singleLineBorderEnd(float x) {
return x;
}
@Override
public int lineSeparatorStart(int minX) {
return isMarginShown(myView.getEditor()) ? Math.max(marginX(Session.getBaseMarginWidth(myView)), minX) : minX;
}
@Override
public int lineSeparatorEnd(int maxX) {
return maxX;
}
@Override
public int marginX(float marginWidth) {
return (int)(myView.getRightAlignmentMarginX() - marginWidth);
}
@Override
public List<Integer> softMarginsX() {
List<Integer> margins = myView.getEditor().getSettings().getSoftMargins();
List<Integer> result = new ArrayList<>(margins.size());
for (Integer margin : margins) {
result.add((int)(myView.getRightAlignmentMarginX() - margin * myView.getPlainSpaceWidth()));
}
return result;
}
}
}
private static class LineExtensionData {
private final LineExtensionInfo info;
private final LineLayout layout;
private LineExtensionData(LineExtensionInfo info, LineLayout layout) {
this.info = info;
this.layout = layout;
}
}
private static class MarginPositions {
private final float[] x;
private final int[] y;
private MarginPositions(int size) {
x = new float[size];
y = new int[size];
}
}
}
|
package org.redisson;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import org.junit.Assert;
import org.junit.Test;
import org.redisson.api.RFuture;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
public class RedissonMapTest extends BaseTest {
public static class SimpleKey implements Serializable {
private String key;
public SimpleKey() {
}
public SimpleKey(String field) {
this.key = field;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String toString() {
return "key: " + key;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleKey other = (SimpleKey) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
public static class SimpleValue implements Serializable {
private String value;
public SimpleValue() {
}
public SimpleValue(String field) {
this.value = field;
}
public void setValue(String field) {
this.value = field;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "value: " + value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleValue other = (SimpleValue) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
@Test
public void testAddAndGet() throws InterruptedException {
RMap<Integer, Integer> map = redisson.getMap("getAll");
map.put(1, 100);
Integer res = map.addAndGet(1, 12);
assertThat(res).isEqualTo(112);
res = map.get(1);
assertThat(res).isEqualTo(112);
RMap<Integer, Double> map2 = redisson.getMap("getAll2");
map2.put(1, new Double(100.2));
Double res2 = map2.addAndGet(1, new Double(12.1));
assertThat(res2).isEqualTo(112.3);
res2 = map2.get(1);
assertThat(res2).isEqualTo(112.3);
RMap<String, Integer> mapStr = redisson.getMap("mapStr");
assertThat(mapStr.put("1", 100)).isNull();
assertThat(mapStr.addAndGet("1", 12)).isEqualTo(112);
assertThat(mapStr.get("1")).isEqualTo(112);
}
@Test
public void testGetAll() {
RMap<Integer, Integer> map = redisson.getMap("getAll");
map.put(1, 100);
map.put(2, 200);
map.put(3, 300);
map.put(4, 400);
Map<Integer, Integer> filtered = map.getAll(new HashSet<Integer>(Arrays.asList(2, 3, 5)));
Map<Integer, Integer> expectedMap = new HashMap<Integer, Integer>();
expectedMap.put(2, 200);
expectedMap.put(3, 300);
assertThat(filtered).isEqualTo(expectedMap);
}
@Test
public void testGetAllWithStringKeys() {
RMap<String, Integer> map = redisson.getMap("getAllStrings");
map.put("A", 100);
map.put("B", 200);
map.put("C", 300);
map.put("D", 400);
Map<String, Integer> filtered = map.getAll(new HashSet<String>(Arrays.asList("B", "C", "E")));
Map<String, Integer> expectedMap = new HashMap<String, Integer>();
expectedMap.put("B", 200);
expectedMap.put("C", 300);
assertThat(filtered).isEqualTo(expectedMap);
}
@Test
public void testStringCodec() {
Config config = createConfig();
config.setCodec(StringCodec.INSTANCE);
RedissonClient redisson = Redisson.create(config);
RMap<String, String> rmap = redisson.getMap("TestRMap01");
rmap.put("A", "1");
rmap.put("B", "2");
Iterator<Map.Entry<String, String>> iterator = rmap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
assertThat(next).isIn(new AbstractMap.SimpleEntry("A", "1"), new AbstractMap.SimpleEntry("B", "2"));
}
redisson.shutdown();
}
@Test
public void testInteger() {
Map<Integer, Integer> map = redisson.getMap("test_int");
map.put(1, 2);
map.put(3, 4);
assertThat(map.size()).isEqualTo(2);
Integer val = map.get(1);
assertThat(val).isEqualTo(2);
Integer val2 = map.get(3);
assertThat(val2).isEqualTo(4);
}
@Test
public void testLong() {
Map<Long, Long> map = redisson.getMap("test_long");
map.put(1L, 2L);
map.put(3L, 4L);
assertThat(map.size()).isEqualTo(2);
Long val = map.get(1L);
assertThat(val).isEqualTo(2);
Long val2 = map.get(3L);
assertThat(val2).isEqualTo(4);
}
@Test
public void testIteratorRemoveHighVolume() throws InterruptedException {
RMap<Integer, Integer> map = redisson.getMap("simpleMap");
for (int i = 0; i < 10000; i++) {
map.put(i, i*10);
}
int cnt = 0;
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
iterator.remove();
cnt++;
}
Assert.assertEquals(10000, cnt);
assertThat(map).isEmpty();
Assert.assertEquals(0, map.size());
}
@Test
public void testIterator() {
RMap<Integer, Integer> rMap = redisson.getMap("123");
int size = 1000;
for (int i = 0; i < size; i++) {
rMap.put(i,i);
}
assertThat(rMap.size()).isEqualTo(1000);
int counter = 0;
for (Integer key : rMap.keySet()) {
counter++;
}
assertThat(counter).isEqualTo(size);
counter = 0;
for (Integer value : rMap.values()) {
counter++;
}
assertThat(counter).isEqualTo(size);
counter = 0;
for (Entry<Integer, Integer> entry : rMap.entrySet()) {
counter++;
}
assertThat(counter).isEqualTo(size);
}
@Test
public void testNull() {
Map<Integer, String> map = redisson.getMap("simple12");
map.put(1, null);
map.put(2, null);
map.put(3, "43");
assertThat(map.size()).isEqualTo(3);
String val = map.get(2);
assertThat(val).isNull();
String val2 = map.get(1);
assertThat(val2).isNull();
String val3 = map.get(3);
assertThat(val3).isEqualTo("43");
}
@Test
public void testEntrySet() {
Map<Integer, String> map = redisson.getMap("simple12");
map.put(1, "12");
map.put(2, "33");
map.put(3, "43");
assertThat(map.entrySet().size()).isEqualTo(3);
Map<Integer, String> testMap = new HashMap<Integer, String>(map);
assertThat(map.entrySet()).containsOnlyElementsOf(testMap.entrySet());
}
@Test
public void testReadAllEntrySet() {
RMap<Integer, String> map = redisson.getMap("simple12");
map.put(1, "12");
map.put(2, "33");
map.put(3, "43");
assertThat(map.readAllEntrySet().size()).isEqualTo(3);
Map<Integer, String> testMap = new HashMap<Integer, String>(map);
assertThat(map.readAllEntrySet()).containsOnlyElementsOf(testMap.entrySet());
}
@Test
public void testSimpleTypes() {
Map<Integer, String> map = redisson.getMap("simple12");
map.put(1, "12");
map.put(2, "33");
map.put(3, "43");
String val = map.get(2);
assertThat(val).isEqualTo("33");
}
@Test
public void testRemove() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
map.remove(new SimpleKey("33"));
map.remove(new SimpleKey("5"));
assertThat(map.size()).isEqualTo(1);
}
@Test
public void testOrdering() {
Map<String, String> map = new LinkedHashMap<String, String>();
// General player data
map.put("name", "123");
map.put("ip", "4124");
map.put("rank", "none");
map.put("tokens", "0");
map.put("coins", "0");
// Arsenal player statistics
map.put("ar_score", "0");
map.put("ar_gameswon", "0");
map.put("ar_gameslost", "0");
map.put("ar_kills", "0");
map.put("ar_deaths", "0");
RMap<String, String> rmap = redisson.getMap("123");
rmap.putAll(map);
assertThat(rmap.keySet()).containsExactlyElementsOf(map.keySet());
assertThat(rmap.readAllKeySet()).containsExactlyElementsOf(map.keySet());
assertThat(rmap.values()).containsExactlyElementsOf(map.values());
assertThat(rmap.readAllValues()).containsExactlyElementsOf(map.values());
assertThat(rmap.entrySet()).containsExactlyElementsOf(map.entrySet());
assertThat(rmap.readAllEntrySet()).containsExactlyElementsOf(map.entrySet());
}
@Test
public void testPutAll() {
Map<Integer, String> map = redisson.getMap("simple");
map.put(1, "1");
map.put(2, "2");
map.put(3, "3");
Map<Integer, String> joinMap = new HashMap<Integer, String>();
joinMap.put(4, "4");
joinMap.put(5, "5");
joinMap.put(6, "6");
map.putAll(joinMap);
assertThat(map.keySet()).containsOnly(1, 2, 3, 4, 5, 6);
}
@Test
public void testKeySet() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
Assert.assertTrue(map.keySet().contains(new SimpleKey("33")));
Assert.assertFalse(map.keySet().contains(new SimpleKey("44")));
}
@Test
public void testReadAllKeySet() {
RMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.readAllKeySet().size()).isEqualTo(3);
Map<SimpleKey, SimpleValue> testMap = new HashMap<>(map);
assertThat(map.readAllKeySet()).containsOnlyElementsOf(testMap.keySet());
}
@Test
public void testReadAllKeySetHighAmount() {
RMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
for (int i = 0; i < 1000; i++) {
map.put(new SimpleKey("" + i), new SimpleValue("" + i));
}
assertThat(map.readAllKeySet().size()).isEqualTo(1000);
Map<SimpleKey, SimpleValue> testMap = new HashMap<>(map);
assertThat(map.readAllKeySet()).containsOnlyElementsOf(testMap.keySet());
}
@Test
public void testReadAllValues() {
RMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.readAllValues().size()).isEqualTo(3);
Map<SimpleKey, SimpleValue> testMap = new HashMap<>(map);
assertThat(map.readAllValues()).containsOnlyElementsOf(testMap.values());
}
@Test
public void testContainsValue() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
Assert.assertTrue(map.containsValue(new SimpleValue("2")));
Assert.assertFalse(map.containsValue(new SimpleValue("441")));
Assert.assertFalse(map.containsValue(new SimpleKey("5")));
}
@Test
public void testContainsKey() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
Assert.assertTrue(map.containsKey(new SimpleKey("33")));
Assert.assertFalse(map.containsKey(new SimpleKey("34")));
}
@Test
public void testRemoveValue() {
ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.remove(new SimpleKey("1"), new SimpleValue("2"));
Assert.assertTrue(res);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertNull(val1);
Assert.assertEquals(0, map.size());
}
@Test
public void testRemoveValueFail() {
ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.remove(new SimpleKey("2"), new SimpleValue("1"));
Assert.assertFalse(res);
boolean res1 = map.remove(new SimpleKey("1"), new SimpleValue("3"));
Assert.assertFalse(res1);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("2", val1.getValue());
}
@Test
public void testReplaceOldValueFail() {
ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.replace(new SimpleKey("1"), new SimpleValue("43"), new SimpleValue("31"));
Assert.assertFalse(res);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("2", val1.getValue());
}
@Test
public void testReplaceOldValueSuccess() {
ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
Assert.assertTrue(res);
boolean res1 = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
Assert.assertFalse(res1);
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("3", val1.getValue());
}
@Test
public void testReplaceValue() {
ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
SimpleValue res = map.replace(new SimpleKey("1"), new SimpleValue("3"));
Assert.assertEquals("2", res.getValue());
SimpleValue val1 = map.get(new SimpleKey("1"));
Assert.assertEquals("3", val1.getValue());
}
@Test
public void testReplace() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
SimpleValue val1 = map.get(new SimpleKey("33"));
Assert.assertEquals("44", val1.getValue());
map.put(new SimpleKey("33"), new SimpleValue("abc"));
SimpleValue val2 = map.get(new SimpleKey("33"));
Assert.assertEquals("abc", val2.getValue());
}
@Test
public void testPutGet() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
SimpleValue val1 = map.get(new SimpleKey("33"));
Assert.assertEquals("44", val1.getValue());
SimpleValue val2 = map.get(new SimpleKey("5"));
Assert.assertEquals("6", val2.getValue());
}
@Test
public void testPutIfAbsent() throws Exception {
ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
SimpleKey key = new SimpleKey("1");
SimpleValue value = new SimpleValue("2");
map.put(key, value);
Assert.assertEquals(value, map.putIfAbsent(key, new SimpleValue("3")));
Assert.assertEquals(value, map.get(key));
SimpleKey key1 = new SimpleKey("2");
SimpleValue value1 = new SimpleValue("4");
Assert.assertNull(map.putIfAbsent(key1, value1));
Assert.assertEquals(value1, map.get(key1));
}
@Test
public void testFastPutIfAbsent() throws Exception {
RMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
SimpleKey key = new SimpleKey("1");
SimpleValue value = new SimpleValue("2");
map.put(key, value);
assertThat(map.fastPutIfAbsent(key, new SimpleValue("3"))).isFalse();
assertThat(map.get(key)).isEqualTo(value);
SimpleKey key1 = new SimpleKey("2");
SimpleValue value1 = new SimpleValue("4");
assertThat(map.fastPutIfAbsent(key1, value1)).isTrue();
assertThat(map.get(key1)).isEqualTo(value1);
}
@Test
public void testSize() {
Map<SimpleKey, SimpleValue> map = redisson.getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("3"), new SimpleValue("4"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
Assert.assertEquals(3, map.size());
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("3"), new SimpleValue("4"));
Assert.assertEquals(3, map.size());
map.put(new SimpleKey("1"), new SimpleValue("21"));
map.put(new SimpleKey("3"), new SimpleValue("41"));
Assert.assertEquals(3, map.size());
map.put(new SimpleKey("51"), new SimpleValue("6"));
Assert.assertEquals(4, map.size());
map.remove(new SimpleKey("3"));
Assert.assertEquals(3, map.size());
}
@Test
public void testEmptyRemove() {
RMap<Integer, Integer> map = redisson.getMap("simple");
Assert.assertFalse(map.remove(1, 3));
map.put(4, 5);
Assert.assertTrue(map.remove(4, 5));
}
@Test
public void testPutAsync() throws InterruptedException, ExecutionException {
RMap<Integer, Integer> map = redisson.getMap("simple");
RFuture<Integer> future = map.putAsync(2, 3);
Assert.assertNull(future.get());
Assert.assertEquals((Integer) 3, map.get(2));
RFuture<Integer> future1 = map.putAsync(2, 4);
Assert.assertEquals((Integer) 3, future1.get());
Assert.assertEquals((Integer) 4, map.get(2));
}
@Test
public void testRemoveAsync() throws InterruptedException, ExecutionException {
RMap<Integer, Integer> map = redisson.getMap("simple");
map.put(1, 3);
map.put(3, 5);
map.put(7, 8);
assertThat(map.removeAsync(1).get()).isEqualTo(3);
assertThat(map.removeAsync(3).get()).isEqualTo(5);
assertThat(map.removeAsync(10).get()).isNull();
assertThat(map.removeAsync(7).get()).isEqualTo(8);
}
@Test
public void testFastRemoveAsync() throws InterruptedException, ExecutionException {
RMap<Integer, Integer> map = redisson.getMap("simple");
map.put(1, 3);
map.put(3, 5);
map.put(4, 6);
map.put(7, 8);
assertThat(map.fastRemoveAsync(1, 3, 7).get()).isEqualTo(3);
Thread.sleep(1);
assertThat(map.size()).isEqualTo(1);
}
@Test
public void testKeyIterator() {
RMap<Integer, Integer> map = redisson.getMap("simple");
map.put(1, 0);
map.put(3, 5);
map.put(4, 6);
map.put(7, 8);
Collection<Integer> keys = map.keySet();
assertThat(keys).containsOnly(1, 3, 4, 7);
for (Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext();) {
Integer value = iterator.next();
if (!keys.remove(value)) {
Assert.fail();
}
}
assertThat(keys.size()).isEqualTo(0);
}
@Test
public void testValueIterator() {
RMap<Integer, Integer> map = redisson.getMap("simple");
map.put(1, 0);
map.put(3, 5);
map.put(4, 6);
map.put(7, 8);
Collection<Integer> values = map.values();
assertThat(values).containsOnly(0, 5, 6, 8);
for (Iterator<Integer> iterator = map.values().iterator(); iterator.hasNext();) {
Integer value = iterator.next();
if (!values.remove(value)) {
Assert.fail();
}
}
assertThat(values.size()).isEqualTo(0);
}
@Test
public void testFastPut() throws Exception {
RMap<Integer, Integer> map = redisson.getMap("simple");
Assert.assertTrue(map.fastPut(1, 2));
Assert.assertFalse(map.fastPut(1, 3));
Assert.assertEquals(1, map.size());
}
@Test
public void testEquals() {
RMap<String, String> map = redisson.getMap("simple");
map.put("1", "7");
map.put("2", "4");
map.put("3", "5");
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("1", "7");
testMap.put("2", "4");
testMap.put("3", "5");
assertThat(map).isEqualTo(testMap);
assertThat(testMap.hashCode()).isEqualTo(map.hashCode());
}
@Test
public void testFastRemoveEmpty() throws Exception {
RMap<Integer, Integer> map = redisson.getMap("simple");
map.put(1, 3);
assertThat(map.fastRemove()).isZero();
assertThat(map.size()).isEqualTo(1);
}
@Test(timeout = 5000)
public void testDeserializationErrorReturnsErrorImmediately() throws Exception {
redisson.getConfig().setCodec(new JsonJacksonCodec());
RMap<String, SimpleObjectWithoutDefaultConstructor> map = redisson.getMap("deserializationFailure");
SimpleObjectWithoutDefaultConstructor object = new SimpleObjectWithoutDefaultConstructor("test-val");
Assert.assertEquals("test-val", object.getTestField());
map.put("test-key", object);
try {
map.get("test-key");
Assert.fail("Expected exception from map.get() call");
} catch (Exception e) {
e.printStackTrace();
}
}
public static class SimpleObjectWithoutDefaultConstructor {
private String testField;
SimpleObjectWithoutDefaultConstructor(String testField) {
this.testField = testField;
}
public String getTestField() {
return testField;
}
public void setTestField(String testField) {
this.testField = testField;
}
}
}
|
package edu.umd.cs.findbugs.charsets;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import javax.annotation.WillCloseWhenClosed;
/**
* @author pugh
*/
public class UTF8 {
public static final Charset charset;
static {
charset = Charset.forName("UTF-8");
}
public static Writer writer(OutputStream out) throws IOException {
return new OutputStreamWriter(out, charset);
}
public static Writer fileWriter(File fileName) throws IOException {
return new OutputStreamWriter(new FileOutputStream(fileName), charset);
}
public static BufferedWriter bufferedWriter(File fileName) throws IOException {
return new BufferedWriter(fileWriter(fileName));
}
public static PrintWriter printWriter(File fileName) throws IOException {
return new PrintWriter(bufferedWriter(fileName));
}
public static Writer fileWriter(String fileName) throws IOException {
return new OutputStreamWriter(new FileOutputStream(fileName), charset);
}
public static BufferedWriter bufferedWriter(String fileName) throws IOException {
return new BufferedWriter(fileWriter(fileName));
}
public static PrintWriter printWriter(String fileName) throws IOException {
return new PrintWriter(bufferedWriter(fileName));
}
public static Reader reader(@WillCloseWhenClosed InputStream in) {
return new InputStreamReader(in, charset);
}
public static BufferedReader bufferedReader(@WillCloseWhenClosed InputStream in) {
return new BufferedReader(reader(in));
}
public static byte[] getBytes(String s) {
return charset.encode(s).array();
}
}
|
package com.intellij.openapi.options.ex;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.extensions.ExtensionsArea;
import com.intellij.openapi.options.*;
import com.intellij.openapi.project.Project;
import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.*;
/**
* @author Dmitry Avdeev
*/
public class ConfigurableWrapper implements SearchableConfigurable, Weighted {
static final Logger LOG = Logger.getInstance(ConfigurableWrapper.class);
@Nullable
public static <T extends UnnamedConfigurable> T wrapConfigurable(@NotNull ConfigurableEP<T> ep) {
return wrapConfigurable(ep, false);
}
@Nullable
public static <T extends UnnamedConfigurable> T wrapConfigurable(@NotNull ConfigurableEP<T> ep, boolean settings) {
if (!ep.canCreateConfigurable()) {
return null;
}
if (settings || ep.displayName != null || ep.key != null || ep.parentId != null || ep.groupId != null) {
//noinspection unchecked
return (T)(!ep.dynamic && ep.children == null && ep.childrenEPName == null ? new ConfigurableWrapper(ep) : new CompositeWrapper(ep));
}
return createConfigurable(ep, LOG.isDebugEnabled());
}
@Nullable
private static <T extends UnnamedConfigurable> T createConfigurable(@NotNull ConfigurableEP<T> ep, boolean log) {
long time = System.currentTimeMillis();
T configurable = ep.createConfigurable();
if (configurable instanceof Configurable) {
ConfigurableCardPanel.warn((Configurable)configurable, "init", time);
if (log) {
LOG.debug("cannot create configurable wrapper for " + configurable.getClass());
}
}
return configurable;
}
public static <T extends UnnamedConfigurable> List<T> createConfigurables(@NotNull ExtensionPointName<? extends ConfigurableEP<T>> name) {
Collection<? extends ConfigurableEP<T>> collection = name.getExtensionList();
if (collection.isEmpty()) {
return Collections.emptyList();
}
List<T> result = new ArrayList<>(collection.size());
for (ConfigurableEP<T> item : collection) {
T o = wrapConfigurable(item, false);
if (o != null) {
result.add(o);
}
}
return result.isEmpty() ? Collections.emptyList() : result;
}
public static boolean hasOwnContent(UnnamedConfigurable configurable) {
SearchableConfigurable.Parent parent = cast(SearchableConfigurable.Parent.class, configurable);
return parent != null && parent.hasOwnContent();
}
public static boolean isNonDefaultProject(Configurable configurable) {
//noinspection deprecation
return configurable instanceof NonDefaultProjectConfigurable ||
(configurable instanceof ConfigurableWrapper && ((ConfigurableWrapper)configurable).myEp.nonDefaultProject);
}
@Nullable
public static <T> T cast(@NotNull Class<T> type, UnnamedConfigurable configurable) {
if (configurable instanceof ConfigurableWrapper) {
ConfigurableWrapper wrapper = (ConfigurableWrapper)configurable;
if (wrapper.myConfigurable == null) {
Class<?> configurableType = wrapper.getExtensionPoint().getConfigurableType();
if (configurableType != null) {
if (!type.isAssignableFrom(configurableType)) {
return null; // do not create configurable that cannot be cast to the specified type
}
}
}
configurable = wrapper.getConfigurable();
}
return type.isInstance(configurable)
? type.cast(configurable)
: null;
}
private final ConfigurableEP<?> myEp;
int myWeight; // see ConfigurableExtensionPointUtil.getConfigurableToReplace
private ConfigurableWrapper(@NotNull ConfigurableEP<?> ep) {
myEp = ep;
myWeight = ep.groupWeight;
}
@Nullable
private UnnamedConfigurable myConfigurable;
@Nullable
public UnnamedConfigurable getRawConfigurable() {
return myConfigurable;
}
public UnnamedConfigurable getConfigurable() {
if (myConfigurable == null) {
myConfigurable = createConfigurable(myEp, false);
if (myConfigurable == null) {
LOG.error("Can't instantiate configurable for " + myEp);
}
else if (LOG.isDebugEnabled()) {
LOG.debug("created configurable for " + myConfigurable.getClass());
}
}
return myConfigurable;
}
@Override
public int getWeight() {
return myWeight;
}
@Nls
@Override
public String getDisplayName() {
if (myEp.displayName == null && myEp.key == null) {
boolean loaded = myConfigurable != null;
Configurable configurable = cast(Configurable.class, this);
if (configurable != null) {
String name = configurable.getDisplayName();
if (!loaded && LOG.isDebugEnabled()) {
LOG.debug("XML does not provide displayName for " + configurable.getClass());
}
return name;
}
}
return myEp.getDisplayName();
}
public String getProviderClass() {
return myEp.providerClass;
}
@Nullable
public Project getProject() {
return myEp.getProject();
}
@Nullable
@Override
public String getHelpTopic() {
UnnamedConfigurable configurable = getConfigurable();
return configurable instanceof Configurable ? ((Configurable)configurable).getHelpTopic() : null;
}
@Nullable
@Override
public JComponent createComponent() {
UnnamedConfigurable configurable = getConfigurable();
return configurable == null ? null : configurable.createComponent();
}
@Override
public boolean isModified() {
return getConfigurable().isModified();
}
@Override
public void apply() throws ConfigurationException {
getConfigurable().apply();
}
@Override
public void reset() {
getConfigurable().reset();
}
@Override
public void disposeUIResources() {
UnnamedConfigurable configurable = myConfigurable;
if (configurable != null) {
configurable.disposeUIResources();
myConfigurable = null;
}
}
@Override
public void cancel() {
UnnamedConfigurable configurable = myConfigurable;
if (configurable != null) {
configurable.cancel();
}
}
@NotNull
@Override
public String getId() {
if (myEp.id != null) {
return myEp.id;
}
boolean loaded = myConfigurable != null;
SearchableConfigurable configurable = cast(SearchableConfigurable.class, this);
if (configurable != null) {
String id = configurable.getId();
if (!loaded) {
LOG.debug("XML does not provide id for " + configurable.getClass());
}
return id;
}
// order from #ConfigurableEP(PicoContainer, Project)
return myEp.providerClass != null
? myEp.providerClass
: myEp.instanceClass != null
? myEp.instanceClass
: myEp.implementationClass;
}
@NotNull
public ConfigurableEP<?> getExtensionPoint() {
return myEp;
}
public String getParentId() {
return myEp.parentId;
}
public ConfigurableWrapper addChild(Configurable configurable) {
return new CompositeWrapper(myEp, configurable);
}
@Override
public String toString() {
return getDisplayName();
}
@Nullable
@Override
public Runnable enableSearch(String option) {
final UnnamedConfigurable configurable = getConfigurable();
return configurable instanceof SearchableConfigurable ? ((SearchableConfigurable)configurable).enableSearch(option) : null;
}
@NotNull
@Override
public Class<?> getOriginalClass() {
final UnnamedConfigurable configurable = getConfigurable();
return configurable instanceof SearchableConfigurable
? ((SearchableConfigurable)configurable).getOriginalClass()
: configurable != null
? configurable.getClass()
: getClass();
}
private static class CompositeWrapper extends ConfigurableWrapper implements Configurable.Composite {
private Configurable[] myKids;
private Comparator<Configurable> myComparator;
private boolean isInitialized;
private CompositeWrapper(@NotNull ConfigurableEP ep, Configurable... kids) {
super(ep);
myKids = kids;
}
@Override
public Configurable @NotNull [] getConfigurables() {
if (isInitialized) {
return myKids;
}
long time = System.currentTimeMillis();
ArrayList<Configurable> list = new ArrayList<>();
if (super.myEp.dynamic) {
Composite composite = cast(Composite.class, this);
if (composite != null) {
Collections.addAll(list, composite.getConfigurables());
}
}
if (super.myEp.children != null) {
for (ConfigurableEP<?> ep : super.myEp.getChildren()) {
if (ep.isAvailable()) {
list.add((Configurable)wrapConfigurable(ep));
}
}
}
if (super.myEp.childrenEPName != null) {
Project project = super.myEp.getProject();
ExtensionsArea area = project == null ? ApplicationManager.getApplication().getExtensionArea() : project.getExtensionArea();
ExtensionPoint<Object> point = area.getExtensionPointIfRegistered(super.myEp.childrenEPName);
List<Object> extensions;
if (point == null) {
LOG.warn("Cannot find extension point " + super.myEp.childrenEPName + " in " + area);
extensions = Collections.emptyList();
}
else {
extensions = point.getExtensionList();
}
if (!extensions.isEmpty()) {
if (extensions.get(0) instanceof ConfigurableEP) {
for (Object object : extensions) {
list.add((Configurable)wrapConfigurable((ConfigurableEP<?>)object));
}
}
else if (!super.myEp.dynamic) {
Composite composite = cast(Composite.class, this);
if (composite != null) {
Collections.addAll(list, composite.getConfigurables());
}
}
}
}
Collections.addAll(list, myKids);
// sort configurables is needed
for (Configurable configurable : list) {
if (configurable instanceof Weighted) {
if (((Weighted)configurable).getWeight() != 0) {
myComparator = COMPARATOR;
list.sort(myComparator);
break;
}
}
}
myKids = list.toArray(new Configurable[0]);
isInitialized = true;
ConfigurableCardPanel.warn(this, "children", time);
return myKids;
}
@Override
public ConfigurableWrapper addChild(Configurable configurable) {
if (myComparator != null) {
int index = Arrays.binarySearch(myKids, configurable, myComparator);
LOG.assertTrue(index < 0, "similar configurable is already exist");
myKids = ArrayUtil.insert(myKids, -1 - index, configurable);
}
else {
myKids = ArrayUtil.append(myKids, configurable);
}
return this;
}
}
}
|
package org.dspace.search;
// java classes
import java.io.*;
import java.util.*;
import java.sql.*;
// lucene search engine classes
import org.apache.lucene.index.*;
import org.apache.lucene.document.*;
import org.apache.lucene.queryParser.*;
import org.apache.lucene.search.*;
import org.apache.lucene.analysis.*;
import org.apache.log4j.Logger;
// dspace classes
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
// issues
// need to filter query string for security
// cmd line query needs to process args correctly (seems to split them up)
public class DSQuery
{
// Result types
static final String ALL = "999";
static final String ITEM = "" + Constants.ITEM;
static final String COLLECTION = "" + Constants.COLLECTION;
static final String COMMUNITY = "" + Constants.COMMUNITY;
/** log4j logger */
private static Logger log = Logger.getLogger(DSQuery.class);
/** Do a query, returning a List of DSpace Handles to objects matching the query.
* @param query string in Lucene query syntax
*
* @return HashMap with lists for items, communities, and collections
* (keys are strings from Constants.ITEM, Constants.COLLECTION, etc.
*/
public static synchronized HashMap doQuery(Context c, String querystring)
throws IOException
{
querystring = checkEmptyQuery( querystring );
querystring = querystring.toLowerCase();
ArrayList resultlist= new ArrayList();
ArrayList itemlist = new ArrayList();
ArrayList commlist = new ArrayList();
ArrayList colllist = new ArrayList();
HashMap metahash = new HashMap();
// initial results are empty
metahash.put(ALL, resultlist);
metahash.put(ITEM, itemlist );
metahash.put(COLLECTION,colllist );
metahash.put(COMMUNITY, commlist );
try
{
IndexSearcher searcher = new IndexSearcher(
ConfigurationManager.getProperty("search.dir"));
QueryParser qp = new QueryParser("default", new DSAnalyzer());
Query myquery = qp.parse(querystring);
Hits hits = searcher.search(myquery);
for (int i = 0; i < hits.length(); i++)
{
Document d = hits.doc(i);
String handletext = d.get("handle");
String handletype = d.get("type");
resultlist.add(handletext);
if (handletype.equals(ITEM))
{
itemlist.add(handletext);
}
else if (handletype.equals(COLLECTION))
{
colllist.add(handletext);
}
else if (handletype.equals(COMMUNITY))
{
commlist.add(handletext); break;
}
}
// close the IndexSearcher - and all its filehandles
searcher.close();
// store all of the different types of hits in the hash
metahash.put(ALL, resultlist);
metahash.put(ITEM, itemlist );
metahash.put(COLLECTION,colllist );
metahash.put(COMMUNITY, commlist );
}
catch (NumberFormatException e)
{
// a bad parse means that there are no results
// doing nothing with the exception gets you
// throw new SQLException( "Error parsing search results: " + e );
// ?? quit?
}
catch (ParseException e)
{
// a parse exception - log and return null results
log.warn(LogManager.getHeader(c,
"Lucene Parse Exception",
"" + e));
}
return metahash;
}
static String checkEmptyQuery( String myquery )
{
if( myquery.equals("") )
{
myquery = "empty_query_string";
}
return myquery;
}
/** Do a query, restricted to a collection
* @param query
* @param collection
*
* @return HashMap same results as doQuery, restricted to a collection
*/
public static HashMap doQuery(Context c, String querystring, Collection coll)
throws IOException, ParseException
{
querystring = checkEmptyQuery( querystring );
String location = "l" + (coll.getID());
String newquery = new String("+(" + querystring + ") +location:\"" + location + "\"");
return doQuery(c, newquery);
}
/** Do a query, restricted to a community
* @param querystring
* @param community
*
* @return HashMap results, same as full doQuery, only hits in a Community
*/
public static HashMap doQuery(Context c, String querystring, Community comm)
throws IOException, ParseException
{
querystring = checkEmptyQuery( querystring );
String location = "m" + (comm.getID());
String newquery = new String("+(" + querystring + ") +location:\"" + location + "\"");
return doQuery(c, newquery);
}
/** return everything from a query
* @param results hashmap from doQuery
*
* @return List of all objects returned by search
*/
public static List getResults(HashMap results)
{
return ((List)results.get(ALL));
}
/** return just the items from a query
* @param results hashmap from doQuery
*
* @return List of items found by query
*/
public static List getItemResults(HashMap results)
{
return ((List)results.get(ITEM));
}
/** return just the collections from a query
* @param results hashmap from doQuery
*
* @return List of collections found by query
*/
public static List getCollectionResults(HashMap results)
{
return ((List)results.get(COLLECTION));
}
/** return just the communities from a query
* @param results hashmap from doQuery
*
* @return list of Communities found by query
*/
public static List getCommunityResults(HashMap results)
{
return ((List)results.get(COMMUNITY));
}
/** returns true if anything found
* @param results hashmap from doQuery
*
* @return true if anything found, false if nothing
*/
public static boolean resultsFound(HashMap results)
{
List thislist = getResults(results);
return (!thislist.isEmpty());
}
/** returns true if items found
* @param results hashmap from doQuery
*
* @return true if items found, false if none found
*/
public static boolean itemsFound(HashMap results)
{
List thislist = getItemResults(results);
return (!thislist.isEmpty());
}
/** returns true if collections found
* @param results hashmap from doQuery
*
* @return true if collections found, false if none
*/
public static boolean collectionsFound(HashMap results)
{
List thislist = getCollectionResults(results);
return (!thislist.isEmpty());
}
/** returns true if communities found
* @param results hashmap from doQuery
*
* @return true if communities found, false if none
*/
public static boolean communitiesFound(HashMap results)
{
List thislist = getCommunityResults(results);
return (!thislist.isEmpty());
}
/** Do a query, printing results to stdout
* largely for testing, but it is useful
*/
public static void doCMDLineQuery(String query)
{
System.out.println("Command line query: " + query);
try
{
Context c = new Context();
HashMap results = doQuery(c, query);
List itemlist = getItemResults(results);
List colllist = getCollectionResults(results);
List commlist = getCommunityResults(results);
if (communitiesFound(results))
{
System.out.println("\n" + "Communities: ");
Iterator i = commlist.iterator();
while (i.hasNext())
{
Object thishandle = i.next();
System.out.println("\t" + thishandle.toString());
}
}
if (collectionsFound(results))
{
System.out.println("\n" + "Collections: ");
Iterator j = colllist.iterator();
while (j.hasNext())
{
Object thishandle = j.next();
System.out.println("\t" + thishandle.toString());
}
}
System.out.println("\n" + "Items: ");
Iterator k = itemlist.iterator();
while (k.hasNext())
{
Object thishandle = k.next();
System.out.println("\t" + thishandle.toString());
}
if (!itemsFound(results))
{
System.out.println ("\tNo items found!");
}
}
catch (Exception e)
{
System.out.println("Exception caught: " + e);
}
}
public static void main(String[] args)
{
DSQuery q = new DSQuery();
if (args.length > 0)
{
q.doCMDLineQuery(args[0]);
}
}
}
|
package li.vin.net;
import edu.emory.mathcs.backport.java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import rx.Subscriber;
import static junit.framework.Assert.assertTrue;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 22)
public class RulesIntegrationTests {
public VinliApp vinliApp;
@Before
public void setup(){
assertTrue(TestHelper.getAccessToken() != null);
vinliApp = TestHelper.getVinliApp();
}
@Test
public void testCreateAndDeleteRadiusBoundaryRule(){
assertTrue(TestHelper.getDeviceId() != null);
Rule.create().deviceId(TestHelper.getDeviceId()).name("testrule").radiusBoundary(
Rule.RadiusBoundary.create().lat(32.897480f).lon(-97.040443f).radius(100).build()).save()
.toBlocking().subscribe(new Subscriber<Rule>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Rule rule) {
assertTrue(rule.id() != null && rule.id().length() > 0);
assertTrue(rule.deviceId() != null && rule.deviceId().length() > 0);
assertTrue(rule.object().type().length() > 0);
assertTrue(rule.object().id().length() > 0);
rule.delete().toBlocking().subscribe(new Subscriber<Void>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Void aVoid) {
}
});
}
});
}
@Test
public void testCreateAndDeleteParametricBoundaryRule(){
assertTrue(TestHelper.getDeviceId() != null);
List<double[]> l = new ArrayList<>();
l.add(new double[]{32.792492f, -96.823495f});
l.add(new double[]{32.817846f, -96.670862f});
l.add(new double[]{32.67926f, -96.771103f});
l.add(new double[]{32.792492f, -96.823495f});
List<List<double[]>> ll = new ArrayList<>();
ll.add(l);
Rule.create().deviceId(TestHelper.getDeviceId()).name("testrule")
.parametricBoundaries(Arrays.asList(new Rule.ParametricBoundary.Seed[]{
Rule.ParametricBoundary.create().parameter("vehicleSpeed").max(32f).min(16f).build(),
Rule.ParametricBoundary.create().parameter("rpm").max(32f).min(16f).build(),
}))
.save()
.toBlocking().subscribe(new Subscriber<Rule>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Rule rule) {
assertTrue(rule.id() != null && rule.id().length() > 0);
assertTrue(rule.deviceId() != null && rule.deviceId().length() > 0);
assertTrue(rule.object().type().length() > 0);
assertTrue(rule.object().id().length() > 0);
rule.delete().toBlocking().subscribe(new Subscriber<Void>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Void aVoid) {
}
});
}
});
}
@Test
public void testCreateAndDeletePolygonBoundaryRule(){
assertTrue(TestHelper.getDeviceId() != null);
List<double[]> l = new ArrayList<>();
l.add(new double[]{32.792492f, -96.823495f});
l.add(new double[]{32.817846f, -96.670862f});
l.add(new double[]{32.67926f, -96.771103f});
l.add(new double[]{32.792492f, -96.823495f});
List<List<double[]>> ll = new ArrayList<>();
ll.add(l);
Rule.create().deviceId(TestHelper.getDeviceId()).name("testrule")
.polygonBoundary(Rule.PolygonBoundary.create().coordinates(ll).build())
.save()
.toBlocking().subscribe(new Subscriber<Rule>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Rule rule) {
assertTrue(rule.id() != null && rule.id().length() > 0);
assertTrue(rule.deviceId() != null && rule.deviceId().length() > 0);
assertTrue(rule.object().type().length() > 0);
assertTrue(rule.object().id().length() > 0);
rule.delete().toBlocking().subscribe(new Subscriber<Void>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Void aVoid) {
}
});
}
});
}
@Test
public void testGetRulesByDeviceId(){
assertTrue(TestHelper.getDeviceId() != null);
Rule.rulesWithDeviceId(TestHelper.getDeviceId(), null, null).toBlocking().subscribe(new Subscriber<Page<Rule>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override
public void onNext(Page<Rule> rulePage) {
assertTrue(rulePage.getItems().size() > 0);
for(Rule rule : rulePage.getItems()){
assertTrue(rule.id() != null && rule.id().length() > 0);
assertTrue(rule.deviceId() != null && rule.deviceId().length() > 0);
assertTrue(rule.object().type().length() > 0);
assertTrue(rule.object().id().length() > 0);
}
}
});
}
@Test
public void getRuleById(){
assertTrue(TestHelper.getRuleId() != null);
Rule.ruleWithId(TestHelper.getRuleId()).toBlocking().subscribe(new Subscriber<Rule>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Rule rule) {
assertTrue(rule.id() != null && rule.id().length() > 0);
assertTrue(rule.deviceId() != null && rule.deviceId().length() > 0);
assertTrue(rule.object().type().length() > 0);
assertTrue(rule.object().id().length() > 0);
}
});
}
@Test public void getRulesByUrl() {
assertTrue(TestHelper.getDeviceId() != null);
vinliApp.rules()
.rulesForUrl(
String.format("%sdevices/%s/rules", Endpoint.RULES.getUrl(), TestHelper.getDeviceId()))
.toBlocking()
.subscribe(new Subscriber<Page<Rule>>() {
@Override public void onCompleted() {
}
@Override public void onError(Throwable e) {
e.printStackTrace();
assertTrue(false);
}
@Override public void onNext(Page<Rule> rulePage) {
assertTrue(rulePage.getItems().size() > 0);
for(Rule rule : rulePage.getItems()){
assertTrue(rule.id() != null && rule.id().length() > 0);
assertTrue(rule.deviceId() != null && rule.deviceId().length() > 0);
assertTrue(rule.object().type().length() > 0);
assertTrue(rule.object().id().length() > 0);
}
}
});
}
}
|
package com.intellij.ui.popup.list;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.actionSystem.ShortcutProvider;
import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter;
import com.intellij.openapi.ui.popup.ListPopupStep;
import com.intellij.openapi.ui.popup.ListPopupStepEx;
import com.intellij.openapi.ui.popup.MnemonicNavigationFilter;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
public class PopupListElementRenderer<E> extends GroupedItemsListRenderer<E> {
protected final ListPopupImpl myPopup;
private JLabel myShortcutLabel;
private @Nullable JLabel myValueLabel;
public PopupListElementRenderer(final ListPopupImpl aPopup) {
super(new ListItemDescriptorAdapter<E>() {
@Override
public String getTextFor(E value) {
return aPopup.getListStep().getTextFor(value);
}
@Override
public Icon getIconFor(E value) {
return aPopup.getListStep().getIconFor(value);
}
@Override
public Icon getSelectedIconFor(E value) {
return aPopup.getListStep().getSelectedIconFor(value);
}
@Override
public boolean hasSeparatorAboveOf(E value) {
return aPopup.getListModel().isSeparatorAboveOf(value);
}
@Override
public String getCaptionAboveOf(E value) {
return aPopup.getListModel().getCaptionAboveOf(value);
}
@Nullable
@Override
public String getTooltipFor(E value) {
ListPopupStep<Object> listStep = aPopup.getListStep();
if (!(listStep instanceof ListPopupStepEx)) return null;
return ((ListPopupStepEx<E>)listStep).getTooltipTextFor(value);
}
});
myPopup = aPopup;
}
@Override
protected JComponent createItemComponent() {
JPanel panel = new JPanel(new BorderLayout());
createLabel();
panel.add(myTextLabel, BorderLayout.WEST);
myValueLabel = new JLabel();
myValueLabel.setEnabled(false);
myValueLabel.setBorder(JBUI.Borders.empty(0, JBUIScale.scale(8), 1, 0));
myValueLabel.setForeground(UIManager.getColor("MenuItem.acceleratorForeground"));
panel.add(myValueLabel, BorderLayout.CENTER);
myShortcutLabel = new JLabel();
myShortcutLabel.setBorder(JBUI.Borders.emptyRight(3));
myShortcutLabel.setForeground(UIManager.getColor("MenuItem.acceleratorForeground"));
panel.add(myShortcutLabel, BorderLayout.EAST);
return layoutComponent(panel);
}
@Override
protected void customizeComponent(JList<? extends E> list, E value, boolean isSelected) {
ListPopupStep<Object> step = myPopup.getListStep();
boolean isSelectable = step.isSelectable(value);
myTextLabel.setEnabled(isSelectable);
setSelected(myComponent, isSelected && isSelectable);
setSelected(myTextLabel, isSelected && isSelectable);
setSelected(myNextStepLabel, isSelected && isSelectable);
if (step instanceof BaseListPopupStep) {
Color bg = ((BaseListPopupStep<E>)step).getBackgroundFor(value);
Color fg = ((BaseListPopupStep<E>)step).getForegroundFor(value);
if (!isSelected && fg != null) myTextLabel.setForeground(fg);
if (!isSelected && bg != null) UIUtil.setBackgroundRecursively(myComponent, bg);
if (bg != null && mySeparatorComponent.isVisible() && myCurrentIndex > 0) {
E prevValue = list.getModel().getElementAt(myCurrentIndex - 1);
// separator between 2 colored items shall get color too
if (Comparing.equal(bg, ((BaseListPopupStep<E>)step).getBackgroundFor(prevValue))) {
myRendererComponent.setBackground(bg);
}
}
}
if (step.isMnemonicsNavigationEnabled()) {
MnemonicNavigationFilter<Object> filter = step.getMnemonicNavigationFilter();
int pos = filter == null ? -1 : filter.getMnemonicPos(value);
if (pos != -1) {
String text = myTextLabel.getText();
text = text.substring(0, pos) + text.substring(pos + 1);
myTextLabel.setText(text);
myTextLabel.setDisplayedMnemonicIndex(pos);
}
}
else {
myTextLabel.setDisplayedMnemonicIndex(-1);
}
if (step.hasSubstep(value) && isSelectable) {
myNextStepLabel.setVisible(true);
myNextStepLabel.setIcon(isSelected ? AllIcons.Icons.Ide.NextStepInverted : AllIcons.Icons.Ide.NextStep);
}
else {
myNextStepLabel.setVisible(false);
}
if (myShortcutLabel != null) {
myShortcutLabel.setEnabled(isSelectable);
myShortcutLabel.setText("");
if (value instanceof ShortcutProvider) {
ShortcutSet set = ((ShortcutProvider)value).getShortcut();
if (set != null) {
Shortcut shortcut = ArrayUtil.getFirstElement(set.getShortcuts());
if (shortcut != null) {
myShortcutLabel.setText(" " + KeymapUtil.getShortcutText(shortcut));
}
}
}
setSelected(myShortcutLabel, isSelected && isSelectable);
myShortcutLabel.setForeground(isSelected && isSelectable ? UIManager.getColor("MenuItem.acceleratorSelectionForeground") : UIManager.getColor("MenuItem.acceleratorForeground"));
}
if (myValueLabel != null) {
myValueLabel.setText(step instanceof ListPopupStepEx<?> ? ((ListPopupStepEx<E>)step).getValueFor(value) : null);
setSelected(myValueLabel, isSelected && isSelectable);
}
}
}
|
package io.fullstack.firestack;
import android.content.Context;
import android.util.Log;
import java.util.Map;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.ReactContext;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.auth.FirebaseAuthException;
class FirestackAuthModule extends ReactContextBaseJavaModule {
private final int NO_CURRENT_USER = 100;
private final int ERROR_FETCHING_TOKEN = 101;
private static final String TAG = "FirestackAuth";
private Context context;
private ReactContext mReactContext;
private FirebaseAuth mAuth;
private FirebaseApp app;
private FirebaseUser user;
private FirebaseAuth.AuthStateListener mAuthListener;
public FirestackAuthModule(ReactApplicationContext reactContext) {
super(reactContext);
this.context = reactContext;
mReactContext = reactContext;
Log.d(TAG, "New FirestackAuth instance");
}
@Override
public String getName() {
return TAG;
}
@ReactMethod
public void listenForAuth() {
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
WritableMap msgMap = Arguments.createMap();
msgMap.putString("eventName", "listenForAuth");
if (firebaseAuth.getCurrentUser() != null) {
WritableMap userMap = getUserMap();
msgMap.putBoolean("authenticated", true);
msgMap.putMap("user", userMap);
FirestackUtils.sendEvent(mReactContext, "listenForAuth", msgMap);
} else {
msgMap.putBoolean("authenticated", false);
FirestackUtils.sendEvent(mReactContext, "listenForAuth", msgMap);
}
}
};
mAuth = FirebaseAuth.getInstance();
mAuth.addAuthStateListener(mAuthListener);
}
@ReactMethod
public void unlistenForAuth(final Callback callback) {
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
WritableMap resp = Arguments.createMap();
resp.putString("status", "complete");
callback.invoke(null, resp);
}
}
@ReactMethod
public void createUserWithEmail(final String email, final String password, final Callback callback) {
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirestackAuthModule.this.user = task.getResult().getUser();
userCallback(FirestackAuthModule.this.user, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void signInWithEmail(final String email, final String password, final Callback callback) {
mAuth = FirebaseAuth.getInstance();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirestackAuthModule.this.user = task.getResult().getUser();
userCallback(FirestackAuthModule.this.user, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
Log.e(TAG, "An exception occurred: " + ex.getMessage());
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void signInWithProvider(final String provider, final String authToken, final String authSecret, final Callback callback) {
if (provider.equals("facebook")) {
this.facebookLogin(authToken,callback);
} else if (provider.equals("google")) {
this.googleLogin(authToken,callback);
} else
// TODO
FirestackUtils.todoNote(TAG, "signInWithProvider", callback);
}
@ReactMethod
public void signInAnonymously(final Callback callback) {
mAuth = FirebaseAuth.getInstance();
mAuth.signInAnonymously()
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());
if (task.isSuccessful()) {
FirestackAuthModule.this.user = task.getResult().getUser();
anonymousUserCallback(FirestackAuthModule.this.user, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void signInWithCustomToken(final String customToken, final Callback callback) {
mAuth = FirebaseAuth.getInstance();
mAuth.signInWithCustomToken(customToken)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCustomToken:onComplete:" + task.isSuccessful());
if (task.isSuccessful()) {
FirestackAuthModule.this.user = task.getResult().getUser();
userCallback(FirestackAuthModule.this.user, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void reauthenticateWithCredentialForProvider(final String provider, final String authToken, final String authSecret, final Callback callback) {
AuthCredential credential;
if (provider.equals("facebook")) {
credential = FacebookAuthProvider.getCredential(authToken);
} else if (provider.equals("google")) {
credential = GoogleAuthProvider.getCredential(authToken, null);
} else {
// TODO:
FirestackUtils.todoNote(TAG, "reauthenticateWithCredentialForProvider", callback);
// AuthCredential credential;
// Log.d(TAG, "reauthenticateWithCredentialForProvider called with: " + provider);
return;
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User re-authenticated with " + provider);
FirebaseUser u = FirebaseAuth.getInstance().getCurrentUser();
userCallback(u, callback);
} else {
// userErrorCallback(task, callback);
}
}
});
} else {
WritableMap err = Arguments.createMap();
err.putInt("errorCode", NO_CURRENT_USER);
err.putString("errorMessage", "No current user");
callback.invoke(err);
}
}
@ReactMethod
public void updateUserEmail(final String email, final Callback callback) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.updateEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User email address updated");
FirebaseUser u = FirebaseAuth.getInstance().getCurrentUser();
userCallback(u, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
} else {
WritableMap err = Arguments.createMap();
err.putInt("errorCode", NO_CURRENT_USER);
err.putString("errorMessage", "No current user");
callback.invoke(err);
}
}
@ReactMethod
public void updateUserPassword(final String newPassword, final Callback callback) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.updatePassword(newPassword)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User password updated");
FirebaseUser u = FirebaseAuth.getInstance().getCurrentUser();
userCallback(u, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
} else {
WritableMap err = Arguments.createMap();
err.putInt("errorCode", NO_CURRENT_USER);
err.putString("errorMessage", "No current user");
callback.invoke(err);
}
}
@ReactMethod
public void sendPasswordResetWithEmail(final String email, final Callback callback) {
mAuth = FirebaseAuth.getInstance();
mAuth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
WritableMap resp = Arguments.createMap();
resp.putString("status", "complete");
callback.invoke(null, resp);
} else {
callback.invoke(task.getException().toString());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void deleteUser(final Callback callback) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
user.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User account deleted");
WritableMap resp = Arguments.createMap();
resp.putString("status", "complete");
resp.putString("msg", "User account deleted");
callback.invoke(null, resp);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
} else {
WritableMap err = Arguments.createMap();
err.putInt("errorCode", NO_CURRENT_USER);
err.putString("errorMessage", "No current user");
callback.invoke(err);
}
}
@ReactMethod
public void getToken(final Callback callback) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.getToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
@Override
public void onComplete(@NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
WritableMap resp = Arguments.createMap();
resp.putString("status", "complete");
resp.putString("token", token);
callback.invoke(null, resp);
} else {
WritableMap err = Arguments.createMap();
err.putInt("errorCode", ERROR_FETCHING_TOKEN);
err.putString("errorMessage", task.getException().getMessage());
callback.invoke(err);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void updateUserProfile(ReadableMap props, final Callback callback) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest.Builder profileBuilder = new UserProfileChangeRequest.Builder();
Map<String, Object> m = FirestackUtils.recursivelyDeconstructReadableMap(props);
if (m.containsKey("displayName")) {
String displayName = (String) m.get("displayName");
profileBuilder.setDisplayName(displayName);
}
if (m.containsKey("photoUri")) {
String photoUriStr = (String) m.get("photoUri");
Uri uri = Uri.parse(photoUriStr);
profileBuilder.setPhotoUri(uri);
}
UserProfileChangeRequest profileUpdates = profileBuilder.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "User profile updated");
FirebaseUser u = FirebaseAuth.getInstance().getCurrentUser();
userCallback(u, callback);
} else {
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void signOut(final Callback callback) {
FirebaseAuth.getInstance().signOut();
this.user = null;
WritableMap resp = Arguments.createMap();
resp.putString("status", "complete");
resp.putString("msg", "User signed out");
callback.invoke(null, resp);
}
@ReactMethod
public void getCurrentUser(final Callback callback) {
mAuth = FirebaseAuth.getInstance();
this.user = mAuth.getCurrentUser();
if(this.user == null){
noUserCallback(callback);
}else{
userCallback(this.user, callback);
}
}
// TODO: Check these things
@ReactMethod
public void googleLogin(String IdToken, final Callback callback) {
mAuth = FirebaseAuth.getInstance();
AuthCredential credential = GoogleAuthProvider.getCredential(IdToken, null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirestackAuthModule.this.user = task.getResult().getUser();
userCallback(FirestackAuthModule.this.user, callback);
}else{
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
@ReactMethod
public void facebookLogin(String Token, final Callback callback) {
mAuth = FirebaseAuth.getInstance();
AuthCredential credential = FacebookAuthProvider.getCredential(Token);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirestackAuthModule.this.user = task.getResult().getUser();
userCallback(FirestackAuthModule.this.user, callback);
}else{
// userErrorCallback(task, callback);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
// Internal helpers
public void userCallback(FirebaseUser passedUser, final Callback callback) {
if (passedUser == null) {
mAuth = FirebaseAuth.getInstance();
this.user = mAuth.getCurrentUser();
} else {
this.user = passedUser;
}
this.user.getToken(false).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
@Override
public void onComplete(@NonNull Task<GetTokenResult> task) {
WritableMap msgMap = Arguments.createMap();
WritableMap userMap = getUserMap();
if (FirestackAuthModule.this.user != null) {
final String token = task.getResult().getToken();
userMap.putString("token", token);
userMap.putBoolean("anonymous", false);
}
msgMap.putMap("user", userMap);
msgMap.putBoolean("authenticated", true);
callback.invoke(null, msgMap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
// TODO: Reduce to one method
public void anonymousUserCallback(FirebaseUser passedUser, final Callback callback) {
if (passedUser == null) {
mAuth = FirebaseAuth.getInstance();
this.user = mAuth.getCurrentUser();
} else {
this.user = passedUser;
}
this.user.getToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
@Override
public void onComplete(@NonNull Task<GetTokenResult> task) {
WritableMap msgMap = Arguments.createMap();
WritableMap userMap = getUserMap();
if (FirestackAuthModule.this.user != null) {
final String token = task.getResult().getToken();
userMap.putString("token", token);
userMap.putBoolean("anonymous", true);
}
msgMap.putMap("user", userMap);
callback.invoke(null, msgMap);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception ex) {
userExceptionCallback(ex, callback);
}
});
}
public void noUserCallback(final Callback callback) {
WritableMap message = Arguments.createMap();
message.putString("errorMessage", "no_user");
message.putString("eventName", "no_user");
message.putBoolean("authenticated", false);
callback.invoke(null, message);
}
public void userErrorCallback(Task task, final Callback onFail) {
userExceptionCallback(task.getException(), onFail);
}
public void userExceptionCallback(Exception exp, final Callback onFail) {
WritableMap error = Arguments.createMap();
error.putString("errorMessage", exp.getMessage());
error.putString("allErrorMessage", exp.toString());
try {
throw exp;
} catch (FirebaseAuthException ex) {
error.putString("errorCode", ex.getErrorCode());
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
onFail.invoke(error);
}
private WritableMap getUserMap() {
WritableMap userMap = Arguments.createMap();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
final String email = user.getEmail();
final String uid = user.getUid();
final String provider = user.getProviderId();
final String name = user.getDisplayName();
final Uri photoUrl = user.getPhotoUrl();
userMap.putString("email", email);
userMap.putString("uid", uid);
userMap.putString("providerId", provider);
userMap.putBoolean("emailVerified", user.isEmailVerified());
if (name != null) {
userMap.putString("displayName", name);
}
if (photoUrl != null) {
userMap.putString("photoUrl", photoUrl.toString());
}
} else {
userMap.putString("msg", "no user");
}
return userMap;
}
}
|
package com.intellij.testFramework;
import com.intellij.CommonBundle;
import com.intellij.codeHighlighting.Pass;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
import com.intellij.codeInsight.daemon.impl.SeveritiesProvider;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.HighlighterColors;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.LineColumn;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.rt.execution.junit.FileComparisonFailure;
import com.intellij.testFramework.fixtures.CodeInsightTestFixture;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.ThreeState;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectHashingStrategy;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.text.ParsePosition;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.intellij.openapi.util.Pair.pair;
import static org.junit.Assert.*;
/**
* @author cdr
*/
public class ExpectedHighlightingData {
public static final String EXPECTED_DUPLICATION_MESSAGE =
"Expected duplication problem. Please remove this wrapper, if there is no such problem any more";
private static final String ERROR_MARKER = CodeInsightTestFixture.ERROR_MARKER;
private static final String WARNING_MARKER = CodeInsightTestFixture.WARNING_MARKER;
private static final String WEAK_WARNING_MARKER = CodeInsightTestFixture.WEAK_WARNING_MARKER;
private static final String INFO_MARKER = CodeInsightTestFixture.INFO_MARKER;
private static final String END_LINE_HIGHLIGHT_MARKER = CodeInsightTestFixture.END_LINE_HIGHLIGHT_MARKER;
private static final String END_LINE_WARNING_MARKER = CodeInsightTestFixture.END_LINE_WARNING_MARKER;
private static final String INJECT_MARKER = "inject";
private static final String SYMBOL_NAME_MARKER = "symbolName";
private static final String LINE_MARKER = "lineMarker";
private static final String ANY_TEXT = "*";
private static final HighlightInfoType WHATEVER =
new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, HighlighterColors.TEXT);
private static boolean isDuplicatedCheckDisabled = false;
private static int failedDuplicationChecks = 0;
public static class ExpectedHighlightingSet {
private final HighlightSeverity severity;
private final boolean endOfLine;
private final boolean enabled;
private final Set<HighlightInfo> infos;
public ExpectedHighlightingSet(@NotNull HighlightSeverity severity, boolean endOfLine, boolean enabled) {
this.severity = severity;
this.endOfLine = endOfLine;
this.enabled = enabled;
this.infos = new THashSet<>();
}
}
private final Map<String, ExpectedHighlightingSet> myHighlightingTypes = new LinkedHashMap<>();
private final Map<RangeMarker, LineMarkerInfo> myLineMarkerInfos = new THashMap<>();
private final Document myDocument;
private final PsiFile myFile;
private final String myText;
private boolean myIgnoreExtraHighlighting;
private final ResourceBundle[] myMessageBundles;
public ExpectedHighlightingData(@NotNull Document document, boolean checkWarnings, boolean checkInfos) {
this(document, checkWarnings, false, checkInfos);
}
public ExpectedHighlightingData(@NotNull Document document, boolean checkWarnings, boolean checkWeakWarnings, boolean checkInfos) {
this(document, checkWarnings, checkWeakWarnings, checkInfos, null);
}
public ExpectedHighlightingData(@NotNull Document document,
boolean checkWarnings,
boolean checkWeakWarnings,
boolean checkInfos,
@Nullable PsiFile file) {
this(document, checkWarnings, checkWeakWarnings, checkInfos, false, file);
}
public ExpectedHighlightingData(@NotNull Document document,
boolean checkWarnings,
boolean checkWeakWarnings,
boolean checkInfos,
boolean ignoreExtraHighlighting,
@Nullable PsiFile file,
ResourceBundle... messageBundles) {
this(document, file, messageBundles);
myIgnoreExtraHighlighting = ignoreExtraHighlighting;
if (checkWarnings) checkWarnings();
if (checkWeakWarnings) checkWeakWarnings();
if (checkInfos) checkInfos();
}
public ExpectedHighlightingData(@NotNull Document document, @Nullable PsiFile file, ResourceBundle... messageBundles) {
myDocument = document;
myFile = file;
myMessageBundles = messageBundles;
myText = document.getText();
registerHighlightingType(ERROR_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, false, true));
registerHighlightingType(WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, false));
registerHighlightingType(WEAK_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WEAK_WARNING, false, false));
registerHighlightingType(INJECT_MARKER, new ExpectedHighlightingSet(HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, false));
registerHighlightingType(INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, false));
registerHighlightingType(SYMBOL_NAME_MARKER, new ExpectedHighlightingSet(HighlightInfoType.SYMBOL_TYPE_SEVERITY, false, false));
for (SeveritiesProvider provider : SeveritiesProvider.EP_NAME.getExtensionList()) {
for (HighlightInfoType type : provider.getSeveritiesHighlightInfoTypes()) {
HighlightSeverity severity = type.getSeverity(null);
registerHighlightingType(severity.getName(), new ExpectedHighlightingSet(severity, false, true));
}
}
registerHighlightingType(END_LINE_HIGHLIGHT_MARKER, new ExpectedHighlightingSet(HighlightSeverity.ERROR, true, true));
registerHighlightingType(END_LINE_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, false));
}
public boolean hasLineMarkers() {
return !myLineMarkerInfos.isEmpty();
}
public void init() {
WriteCommandAction.runWriteCommandAction(null, () -> {
extractExpectedLineMarkerSet(myDocument);
extractExpectedHighlightsSet(myDocument);
refreshLineMarkers();
});
}
public void checkWarnings() {
registerHighlightingType(WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, false, true));
registerHighlightingType(END_LINE_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WARNING, true, true));
}
public void checkWeakWarnings() {
registerHighlightingType(WEAK_WARNING_MARKER, new ExpectedHighlightingSet(HighlightSeverity.WEAK_WARNING, false, true));
}
public void checkInfos() {
registerHighlightingType(INFO_MARKER, new ExpectedHighlightingSet(HighlightSeverity.INFORMATION, false, true));
registerHighlightingType(INJECT_MARKER, new ExpectedHighlightingSet(HighlightInfoType.INJECTED_FRAGMENT_SEVERITY, false, true));
}
public void checkSymbolNames() {
registerHighlightingType(SYMBOL_NAME_MARKER, new ExpectedHighlightingSet(HighlightInfoType.SYMBOL_TYPE_SEVERITY, false, true));
}
public void registerHighlightingType(@NotNull String key, @NotNull ExpectedHighlightingSet highlightingSet) {
myHighlightingTypes.put(key, highlightingSet);
}
private void refreshLineMarkers() {
for (Map.Entry<RangeMarker, LineMarkerInfo> entry : myLineMarkerInfos.entrySet()) {
RangeMarker rangeMarker = entry.getKey();
int startOffset = rangeMarker.getStartOffset();
int endOffset = rangeMarker.getEndOffset();
LineMarkerInfo value = entry.getValue();
PsiElement element = value.getElement();
assert element != null : value;
TextRange range = new TextRange(startOffset, endOffset);
String tooltip = value.getLineMarkerTooltip();
MyLineMarkerInfo markerInfo =
new MyLineMarkerInfo(element, range, value.updatePass, GutterIconRenderer.Alignment.RIGHT, tooltip);
entry.setValue(markerInfo);
}
}
private void extractExpectedLineMarkerSet(Document document) {
String text = document.getText();
String pat = ".*?((<" + LINE_MARKER + ")(?: descr=\"((?:[^\"\\\\]|\\\\\")*)\")?>)(.*)";
Pattern openingTagRx = Pattern.compile(pat, Pattern.DOTALL);
Pattern closingTagRx = Pattern.compile("(.*?)(</" + LINE_MARKER + ">)(.*)", Pattern.DOTALL);
while (true) {
Matcher opening = openingTagRx.matcher(text);
if (!opening.matches()) break;
int startOffset = opening.start(1);
String descr = opening.group(3) != null ? opening.group(3) : ANY_TEXT;
String rest = opening.group(4);
Matcher closing = closingTagRx.matcher(rest);
if (!closing.matches()) {
fail("Cannot find closing </" + LINE_MARKER + ">");
}
document.replaceString(startOffset, opening.end(1), "");
String content = closing.group(1);
int endOffset = startOffset + closing.start(3);
String endTag = closing.group(2);
document.replaceString(startOffset, endOffset, content);
endOffset -= endTag.length();
PsiElement leaf = Objects.requireNonNull(myFile.findElementAt(startOffset));
TextRange range = new TextRange(startOffset, endOffset);
String tooltip = StringUtil.unescapeStringCharacters(descr);
LineMarkerInfo<PsiElement> markerInfo =
new MyLineMarkerInfo(leaf, range, Pass.LINE_MARKERS, GutterIconRenderer.Alignment.RIGHT, tooltip);
myLineMarkerInfos.put(document.createRangeMarker(startOffset, endOffset), markerInfo);
text = document.getText();
}
}
/**
* Removes highlights (bounded with <marker>...</marker>) from test case file.
*/
private void extractExpectedHighlightsSet(Document document) {
String text = document.getText();
Set<String> markers = myHighlightingTypes.keySet();
String typesRx = "(?:" + StringUtil.join(markers, ")|(?:") + ")";
String openingTagRx = "<(" + typesRx + ")" +
"(?:\\s+descr=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\])*)\")?" +
"(?:\\s+type=\"([0-9A-Z_]+)\")?" +
"(?:\\s+foreground=\"([0-9xa-f]+)\")?" +
"(?:\\s+background=\"([0-9xa-f]+)\")?" +
"(?:\\s+effectcolor=\"([0-9xa-f]+)\")?" +
"(?:\\s+effecttype=\"([A-Z]+)\")?" +
"(?:\\s+fonttype=\"([0-9]+)\")?" +
"(?:\\s+textAttributesKey=\"((?:[^\"]|\\\\\"|\\\\\\\\\"|\\\\\\[|\\\\])*)\")?" +
"(?:\\s+bundleMsg=\"((?:[^\"]|\\\\\"|\\\\\\\\\")*)\")?" +
"(/)?>";
Matcher matcher = Pattern.compile(openingTagRx).matcher(text);
int pos = 0;
Ref<Integer> textOffset = Ref.create(0);
while (matcher.find(pos)) {
textOffset.set(textOffset.get() + matcher.start() - pos);
pos = extractExpectedHighlight(matcher, text, document, textOffset);
}
}
private int extractExpectedHighlight(Matcher matcher, String text, Document document, Ref<Integer> textOffset) {
document.deleteString(textOffset.get(), textOffset.get() + matcher.end() - matcher.start());
int groupIdx = 1;
String marker = matcher.group(groupIdx++);
String descr = matcher.group(groupIdx++);
String typeString = matcher.group(groupIdx++);
String foregroundColor = matcher.group(groupIdx++);
String backgroundColor = matcher.group(groupIdx++);
String effectColor = matcher.group(groupIdx++);
String effectType = matcher.group(groupIdx++);
String fontType = matcher.group(groupIdx++);
String attrKey = matcher.group(groupIdx++);
String bundleMessage = matcher.group(groupIdx++);
boolean closed = matcher.group(groupIdx) != null;
if (descr == null) {
descr = ANY_TEXT; // no descr means any string by default
}
else if (descr.equals("null")) {
descr = null; // explicit "null" descr
}
if (descr != null) {
descr = descr.replaceAll("\\\\\\\\\"", "\""); // replace: \\" to ", doesn't check symbol before sequence \\"
descr = descr.replaceAll("\\\\\"", "\"");
}
HighlightInfoType type = WHATEVER;
if (typeString != null) {
try {
type = getTypeByName(typeString);
}
catch (Exception e) {
throw new RuntimeException(e);
}
if (type == null) {
fail("Wrong highlight type: " + typeString);
}
}
TextAttributes forcedAttributes = null;
if (foregroundColor != null) {
@JdkConstants.FontStyle int ft = Integer.parseInt(fontType);
forcedAttributes = new TextAttributes(
Color.decode(foregroundColor), Color.decode(backgroundColor), Color.decode(effectColor), EffectType.valueOf(effectType), ft);
}
int rangeStart = textOffset.get();
int toContinueFrom;
if (closed) {
toContinueFrom = matcher.end();
}
else {
int pos = matcher.end();
Matcher closingTagMatcher = Pattern.compile("</" + marker + ">").matcher(text);
while (true) {
if (!closingTagMatcher.find(pos)) {
toContinueFrom = pos;
break;
}
int nextTagStart = matcher.find(pos) ? matcher.start() : text.length();
if (closingTagMatcher.start() < nextTagStart) {
textOffset.set(textOffset.get() + closingTagMatcher.start() - pos);
document.deleteString(textOffset.get(), textOffset.get() + closingTagMatcher.end() - closingTagMatcher.start());
toContinueFrom = closingTagMatcher.end();
break;
}
textOffset.set(textOffset.get() + nextTagStart - pos);
pos = extractExpectedHighlight(matcher, text, document, textOffset);
}
}
ExpectedHighlightingSet expectedHighlightingSet = myHighlightingTypes.get(marker);
if (expectedHighlightingSet.enabled) {
TextAttributesKey forcedTextAttributesKey = attrKey == null ? null : TextAttributesKey.createTextAttributesKey(attrKey);
HighlightInfo.Builder builder =
HighlightInfo.newHighlightInfo(type).range(rangeStart, textOffset.get()).severity(expectedHighlightingSet.severity);
if (forcedAttributes != null) builder.textAttributes(forcedAttributes);
if (forcedTextAttributesKey != null) builder.textAttributes(forcedTextAttributesKey);
if (bundleMessage != null) {
descr = extractDescrFromBundleMessage(bundleMessage);
}
if (descr != null) {
builder.description(descr);
builder.unescapedToolTip(descr);
}
if (expectedHighlightingSet.endOfLine) builder.endOfLine();
HighlightInfo highlightInfo = builder.createUnconditionally();
expectedHighlightingSet.infos.add(highlightInfo);
}
return toContinueFrom;
}
@NotNull
private String extractDescrFromBundleMessage(String bundleMessage) {
String descr = null;
List<String> split = StringUtil.split(bundleMessage, "|");
String key = split.get(0);
List<String> keySplit = StringUtil.split(key, "
ResourceBundle[] bundles = myMessageBundles;
if (keySplit.size() == 2) {
key = keySplit.get(1);
bundles = new ResourceBundle[]{ResourceBundle.getBundle(keySplit.get(0))};
}
else {
assertEquals("Format for bundleMsg attribute is: [bundleName#] bundleKey [|argument]... ", 1, keySplit.size());
}
assertTrue("messageBundles must be provided for bundleMsg tags in test data", bundles.length > 0);
Object[] params = split.stream().skip(1).toArray();
for (ResourceBundle bundle : bundles) {
String message = CommonBundle.messageOrDefault(bundle, key, null, params);
if (message != null) {
if (descr != null) fail("Key " + key + " is not unique in bundles for expected highlighting data");
descr = message;
}
}
if (descr == null) fail("Can't find bundle message " + bundleMessage);
return descr;
}
protected HighlightInfoType getTypeByName(String typeString) throws Exception {
Field field = HighlightInfoType.class.getField(typeString);
return (HighlightInfoType)field.get(null);
}
public void checkLineMarkers(@NotNull Collection<? extends LineMarkerInfo> markerInfos, @NotNull String text) {
String fileName = myFile == null ? "" : myFile.getName() + ": ";
StringBuilder failMessage = new StringBuilder();
for (LineMarkerInfo info : markerInfos) {
if (!containsLineMarker(info, myLineMarkerInfos.values())) {
if (failMessage.length() > 0) failMessage.append('\n');
failMessage.append(fileName).append("extra ")
.append(rangeString(text, info.startOffset, info.endOffset))
.append(": '").append(info.getLineMarkerTooltip()).append('\'');
}
}
for (LineMarkerInfo expectedLineMarker : myLineMarkerInfos.values()) {
if (markerInfos.isEmpty() || !containsLineMarker(expectedLineMarker, markerInfos)) {
if (failMessage.length() > 0) failMessage.append('\n');
failMessage.append(fileName).append("missing ")
.append(rangeString(text, expectedLineMarker.startOffset, expectedLineMarker.endOffset))
.append(": '").append(expectedLineMarker.getLineMarkerTooltip()).append('\'');
}
}
if (failMessage.length() > 0) {
String filePath = null;
if (myFile != null) {
VirtualFile file = myFile.getVirtualFile();
if (file != null) {
filePath = file.getUserData(VfsTestUtil.TEST_DATA_FILE_PATH);
}
}
throw new FileComparisonFailure(failMessage.toString(), myText, getActualLineMarkerFileText(markerInfos), filePath);
}
}
@NotNull
private String getActualLineMarkerFileText(@NotNull Collection<? extends LineMarkerInfo> markerInfos) {
StringBuilder result = new StringBuilder();
int index = 0;
List<LineMarkerInfo> lineMarkerInfos = markerInfos
.stream()
.sorted(Comparator.comparingInt(o -> o.startOffset))
.collect(Collectors.toList());
String documentText = myDocument.getText();
for (LineMarkerInfo expectedLineMarker : lineMarkerInfos) {
result.append(documentText, index, expectedLineMarker.startOffset);
result.append("<lineMarker descr=\"");
result.append(expectedLineMarker.getLineMarkerTooltip());
result.append("\">");
result.append(documentText, expectedLineMarker.startOffset, expectedLineMarker.endOffset);
result.append("</lineMarker>");
index = expectedLineMarker.endOffset;
}
result.append(documentText, index, myDocument.getTextLength());
return result.toString();
}
private static boolean containsLineMarker(LineMarkerInfo info, Collection<? extends LineMarkerInfo> where) {
String infoTooltip = info.getLineMarkerTooltip();
for (LineMarkerInfo markerInfo : where) {
String markerInfoTooltip;
if (markerInfo.startOffset == info.startOffset &&
markerInfo.endOffset == info.endOffset &&
(Comparing.equal(infoTooltip, markerInfoTooltip = markerInfo.getLineMarkerTooltip()) ||
ANY_TEXT.equals(markerInfoTooltip) ||
ANY_TEXT.equals(infoTooltip))) {
return true;
}
}
return false;
}
public void checkResult(Collection<HighlightInfo> infos, String text) {
checkResult(infos, text, null);
}
public void checkResult(Collection<HighlightInfo> infos, String text, @Nullable String filePath) {
StringBuilder failMessage = new StringBuilder();
Set<HighlightInfo> expectedFound = new THashSet<>(new TObjectHashingStrategy<HighlightInfo>() {
@Override
public int computeHashCode(HighlightInfo object) {
return object.hashCode();
}
@Override
public boolean equals(HighlightInfo o1, HighlightInfo o2) {
return haveSamePresentation(o1, o2, true);
}
});
if (!myIgnoreExtraHighlighting) {
for (HighlightInfo info : reverseCollection(infos)) {
ThreeState state = expectedInfosContainsInfo(info);
if (state == ThreeState.NO) {
reportProblem(failMessage, text, info, "extra ");
failMessage.append(" [").append(info.type).append(']');
}
else if (state == ThreeState.YES) {
if (expectedFound.contains(info)) {
if (isDuplicatedCheckDisabled) {
//noinspection AssignmentToStaticFieldFromInstanceMethod
failedDuplicationChecks++;
}
else {
reportProblem(failMessage, text, info, "duplicated ");
}
}
expectedFound.add(info);
}
}
}
Collection<ExpectedHighlightingSet> expectedHighlights = myHighlightingTypes.values();
for (ExpectedHighlightingSet highlightingSet : reverseCollection(expectedHighlights)) {
Set<HighlightInfo> expInfos = highlightingSet.infos;
for (HighlightInfo expectedInfo : expInfos) {
if (!infosContainsExpectedInfo(infos, expectedInfo) && highlightingSet.enabled) {
reportProblem(failMessage, text, expectedInfo, "missing ");
}
}
}
if (failMessage.length() > 0) {
if (filePath == null && myFile != null) {
VirtualFile file = myFile.getVirtualFile();
if (file != null) {
filePath = file.getUserData(VfsTestUtil.TEST_DATA_FILE_PATH);
}
}
failMessage.append('\n');
compareTexts(infos, text, failMessage.toString(), filePath);
}
}
private void reportProblem(@NotNull StringBuilder failMessage,
@NotNull String text,
@NotNull HighlightInfo info,
@NotNull String messageType) {
String fileName = myFile == null ? "" : myFile.getName() + ": ";
int startOffset = info.startOffset;
int endOffset = info.endOffset;
String s = text.substring(startOffset, endOffset);
String desc = info.getDescription();
if (failMessage.length() > 0) {
failMessage.append('\n');
}
failMessage.append(fileName).append(messageType)
.append(rangeString(text, startOffset, endOffset))
.append(": '").append(s).append('\'');
if (desc != null) {
failMessage.append(" (").append(desc).append(')');
}
}
private static <T> List<T> reverseCollection(Collection<? extends T> infos) {
return ContainerUtil.reverse(infos instanceof List ? (List<T>)infos : new ArrayList<>(infos));
}
private void compareTexts(Collection<HighlightInfo> infos, String text, String failMessage, @Nullable String filePath) {
String actual = composeText(myHighlightingTypes, infos, text, myMessageBundles);
if (filePath != null && !myText.equals(actual)) {
// uncomment to overwrite, don't forget to revert on commit!
//VfsTestUtil.overwriteTestData(filePath, actual);
//return;
throw new FileComparisonFailure(failMessage, myText, actual, filePath);
}
assertEquals(failMessage + "\n", myText, actual);
fail(failMessage);
}
private static String findTag(Map<String, ExpectedHighlightingSet> types, HighlightInfo info) {
Map.Entry<String, ExpectedHighlightingSet> entry = ContainerUtil.find(
types.entrySet(),
e -> e.getValue().enabled && e.getValue().severity == info.getSeverity() && e.getValue().endOfLine == info.isAfterEndOfLine());
return entry != null ? entry.getKey() : null;
}
@NotNull
public static String composeText(@NotNull Map<String, ExpectedHighlightingSet> types,
@NotNull Collection<HighlightInfo> infos,
@NotNull String text,
@NotNull ResourceBundle... messageBundles) {
// filter highlighting data and map each highlighting to a tag name
List<Pair<String, HighlightInfo>> list = infos.stream()
.map(info -> pair(findTag(types, info), info))
.filter(p -> p.first != null)
.collect(Collectors.toList());
boolean showAttributesKeys =
types.values().stream().flatMap(set -> set.infos.stream()).anyMatch(i -> i.forcedTextAttributesKey != null);
// sort filtered highlighting data by end offset in descending order
Collections.sort(list, (o1, o2) -> {
HighlightInfo i1 = o1.second;
HighlightInfo i2 = o2.second;
int byEnds = i2.endOffset - i1.endOffset;
if (byEnds != 0) return byEnds;
if (!i1.isAfterEndOfLine() && !i2.isAfterEndOfLine()) {
int byStarts = i1.startOffset - i2.startOffset;
if (byStarts != 0) return byStarts;
}
else {
int byEOL = Comparing.compare(i2.isAfterEndOfLine(), i1.isAfterEndOfLine());
if (byEOL != 0) return byEOL;
}
int bySeverity = i2.getSeverity().compareTo(i1.getSeverity());
if (bySeverity != 0) return bySeverity;
return Comparing.compare(i1.getDescription(), i2.getDescription());
});
// combine highlighting data with original text
StringBuilder sb = new StringBuilder();
int[] offsets = composeText(sb, list, 0, text, text.length(), -1, showAttributesKeys, messageBundles);
sb.insert(0, text.substring(0, offsets[1]));
return sb.toString();
}
/**
* @deprecated This is temporary wrapper to provide time to fix failing tests
*/
@Deprecated
public static void expectedDuplicatedHighlighting(@NotNull Runnable check) {
try {
isDuplicatedCheckDisabled = true;
failedDuplicationChecks = 0;
check.run();
}
finally {
isDuplicatedCheckDisabled = false;
}
if (failedDuplicationChecks == 0) {
throw new IllegalStateException(EXPECTED_DUPLICATION_MESSAGE);
}
}
private static int[] composeText(StringBuilder sb,
List<? extends Pair<String, HighlightInfo>> list, int index,
String text, int endPos, int startPos,
boolean showAttributesKeys,
ResourceBundle... messageBundles) {
int i = index;
while (i < list.size()) {
Pair<String, HighlightInfo> pair = list.get(i);
HighlightInfo info = pair.second;
if (info.endOffset <= startPos) {
break;
}
String severity = pair.first;
HighlightInfo prev = i < list.size() - 1 ? list.get(i + 1).second : null;
sb.insert(0, text.substring(info.endOffset, endPos));
sb.insert(0, "</" + severity + '>');
endPos = info.endOffset;
if (prev != null && prev.endOffset > info.startOffset) {
int[] offsets = composeText(sb, list, i + 1, text, endPos, info.startOffset, showAttributesKeys, messageBundles);
i = offsets[0] - 1;
endPos = offsets[1];
}
sb.insert(0, text.substring(info.startOffset, endPos));
String str = '<' + severity + " ";
String bundleMsg = composeBundleMsg(info, messageBundles);
if (bundleMsg != null) {
str += "bundleMsg=\"" + StringUtil.escapeQuotes(bundleMsg) + '"';
}
else {
str += "descr=\"" + StringUtil.escapeQuotes(String.valueOf(info.getDescription())) + '"';
}
if (showAttributesKeys) {
str += " textAttributesKey=\"" + info.forcedTextAttributesKey + '"';
}
str += '>';
sb.insert(0, str);
endPos = info.startOffset;
i++;
}
return new int[]{i, endPos};
}
private static String composeBundleMsg(HighlightInfo info, ResourceBundle... messageBundles) {
String bundleKey = null;
Object[] bundleMsgParams = null;
for (ResourceBundle bundle : messageBundles) {
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
ParsePosition position = new ParsePosition(0);
String value = bundle.getString(key);
Object[] parse;
boolean matched;
if (value.contains("{0")) {
parse = new MessageFormat(value).parse(info.getDescription(), position);
matched = parse != null && info.getDescription() != null && position.getIndex() == info.getDescription().length() && position.getErrorIndex() == -1;
}
else {
parse = ArrayUtilRt.EMPTY_OBJECT_ARRAY;
matched = value.equals(info.getDescription());
}
if (matched) {
if (bundleKey != null) {
bundleKey = null;
break; // several keys matched, don't suggest bundle key
}
bundleKey = key;
bundleMsgParams = parse;
}
}
}
if (bundleKey == null) return null;
String bundleMsg = bundleKey;
if (bundleMsgParams.length > 0) {
bundleMsg += '|' + StringUtil.join(ContainerUtil.map(bundleMsgParams, Objects::toString), "|");
}
return bundleMsg;
}
private static boolean infosContainsExpectedInfo(Collection<? extends HighlightInfo> infos, HighlightInfo expectedInfo) {
for (HighlightInfo info : infos) {
if (matchesPattern(expectedInfo, info, false)) {
return true;
}
}
return false;
}
private ThreeState expectedInfosContainsInfo(HighlightInfo info) {
if (info.getTextAttributes(null, null) == TextAttributes.ERASE_MARKER) return ThreeState.UNSURE;
Collection<ExpectedHighlightingSet> expectedHighlights = myHighlightingTypes.values();
for (ExpectedHighlightingSet highlightingSet : expectedHighlights) {
if (highlightingSet.severity != info.getSeverity()) continue;
if (!highlightingSet.enabled) return ThreeState.UNSURE;
Set<HighlightInfo> infos = highlightingSet.infos;
for (HighlightInfo expectedInfo : infos) {
if (matchesPattern(expectedInfo, info, false)) {
return ThreeState.YES;
}
}
}
return ThreeState.NO;
}
private static boolean matchesPattern(@NotNull HighlightInfo expectedInfo, @NotNull HighlightInfo info, boolean strictMatch) {
if (expectedInfo == info) return true;
boolean typeMatches = expectedInfo.type.equals(info.type) || !strictMatch && expectedInfo.type == WHATEVER;
boolean textAttributesMatches = Comparing.equal(expectedInfo.getTextAttributes(null, null), info.getTextAttributes(null, null)) ||
!strictMatch && expectedInfo.forcedTextAttributes == null;
boolean attributesKeyMatches = !strictMatch && expectedInfo.forcedTextAttributesKey == null ||
Objects.equals(expectedInfo.forcedTextAttributesKey, info.forcedTextAttributesKey);
return
haveSamePresentation(info, expectedInfo, strictMatch) &&
info.getSeverity() == expectedInfo.getSeverity() &&
typeMatches &&
textAttributesMatches &&
attributesKeyMatches;
}
private static boolean haveSamePresentation(@NotNull HighlightInfo info1, @NotNull HighlightInfo info2, boolean strictMatch) {
return info1.startOffset == info2.startOffset &&
info1.endOffset == info2.endOffset &&
info1.isAfterEndOfLine() == info2.isAfterEndOfLine() &&
(Comparing.strEqual(info1.getDescription(), info2.getDescription()) ||
!strictMatch && Comparing.strEqual(ANY_TEXT, info2.getDescription()));
}
private static String rangeString(String text, int startOffset, int endOffset) {
LineColumn start = StringUtil.offsetToLineColumn(text, startOffset);
assert start != null: "textLength = " + text.length() + ", startOffset = " + startOffset;
LineColumn end = StringUtil.offsetToLineColumn(text, endOffset);
assert end != null : "textLength = " + text.length() + ", endOffset = " + endOffset;
if (start.line == end.line) {
return String.format("(%d:%d/%d)", start.line + 1, start.column + 1, end.column - start.column);
}
else {
return String.format("(%d:%d..%d:%d)", start.line + 1, end.line + 1, start.column + 1, end.column + 1);
}
}
private static class MyLineMarkerInfo extends LineMarkerInfo<PsiElement> {
private final String myTooltip;
MyLineMarkerInfo(PsiElement element, TextRange range, int updatePass, GutterIconRenderer.Alignment alignment, String tooltip) {
super(element, range, null, updatePass, null, null, alignment);
myTooltip = tooltip;
}
@Override
public String getLineMarkerTooltip() {
return myTooltip;
}
}
}
|
package org.pmiops.workbench.config;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.oauth2.model.Userinfoplus;
import com.google.apphosting.api.ApiProxy;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import org.pmiops.workbench.auth.UserAuthentication;
import org.pmiops.workbench.db.model.User;
import org.pmiops.workbench.interceptors.AuthInterceptor;
import org.pmiops.workbench.interceptors.CorsInterceptor;
import org.pmiops.workbench.interceptors.ClearCdrVersionContextInterceptor;
import org.pmiops.workbench.interceptors.CronInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private AuthInterceptor authInterceptor;
@Autowired
private CorsInterceptor corsInterceptor;
@Autowired
private ClearCdrVersionContextInterceptor clearCdrVersionInterceptor;
@Autowired
private CronInterceptor cronInterceptor;
@Bean
@RequestScope(proxyMode = ScopedProxyMode.DEFAULT)
public UserAuthentication userAuthentication() {
return (UserAuthentication) SecurityContextHolder.getContext().getAuthentication();
}
@Bean
@RequestScope(proxyMode = ScopedProxyMode.DEFAULT)
public Userinfoplus userInfo(UserAuthentication userAuthentication) {
return userAuthentication.getPrincipal();
}
@Bean
@RequestScope(proxyMode = ScopedProxyMode.DEFAULT)
public User user(UserAuthentication userAuthentication) {
return userAuthentication.getUser();
}
@Bean("apiHostName")
public String getHostName() {
ApiProxy.Environment env = ApiProxy.getCurrentEnvironment();
// TODO: see if there's a better way of doing this?
String version = System.getProperty("com.google.appengine.application.version");
// Strip off the timestamp suffix.
version = version.substring(0, version.lastIndexOf('.'));
return version + "-dot-" + (String) env.getAttributes().get("com.google.appengine.runtime.default_version_hostname");
}
@Bean
public WorkbenchEnvironment workbenchEnvironment() {
return new WorkbenchEnvironment();
}
/**
* Service account credentials for Gsuite administration. These are derived from a key JSON file
* copied from GCS deployed to /WEB-INF/gsuite-admin-sa.json during the build step. They can be used
* to make API calls to directory service on behalf of AofU (as opposed to using end user credentials.)
*
* We may in future rotate key files in production, but will be sure to keep the ones currently
* in use in cloud environments working when that happens.
*/
@Lazy
@Bean
public GoogleCredential gsuiteAdminCredential() {
ServletContext context = getRequestServletContext();
InputStream saFileAsStream = context.getResourceAsStream("/WEB-INF/gsuite-admin-sa.json");
GoogleCredential credential = null;
try {
return GoogleCredential.fromStream(saFileAsStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(corsInterceptor);
registry.addInterceptor(authInterceptor);
registry.addInterceptor(cronInterceptor);
registry.addInterceptor(clearCdrVersionInterceptor);
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
static ServletContext getRequestServletContext() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest().getServletContext();
}
}
|
package com.enrique.stackblur;
import java.io.FileOutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
public class StackBlurManager {
/**
* Original set of pixels from the image
*/
private int [] originalPixels;
/**
* Current set of pixels from the image (the one that will be exported
*/
private int [] currentPixels;
/**
* Original width of the image
*/
private int _width = -1;
/**
* Original height of the image
*/
private int _height= -1;
/**
* Original image
*/
private Bitmap _image;
private boolean alpha = false;
/**
* Constructor method (basic initialization and construction of the pixel array)
* @param image The image that will be analyed
*/
public StackBlurManager(Bitmap image) {
_width=image.getWidth();
_height=image.getHeight();
_image = image;
originalPixels= new int[_width*_height];
_image.getPixels(originalPixels, 0, _width, 0, 0, _width, _height);
}
/**
* Process the image on the given radius. Radius must be at least 1
* @param radius
*/
public void process(int radius) {
if (radius < 1 )
radius = 1;
currentPixels = originalPixels.clone();
int wm=_width-1;
int hm=_height-1;
int wh=_width*_height;
int div=radius+radius+1;
int r[]=new int[wh];
int g[]=new int[wh];
int b[]=new int[wh];
int rsum,gsum,bsum,x,y,i,p,yp,yi,yw;
int vmin[] = new int[Math.max(_width,_height)];
int divsum=(div+1)>>1;
divsum*=divsum;
int dv[]=new int[256*divsum];
for (i=0;i<256*divsum;i++){
dv[i]=(i/divsum);
}
yw=yi=0;
int[][] stack=new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1=radius+1;
int routsum,goutsum,boutsum;
int rinsum,ginsum,binsum;
for (y=0;y<_height;y++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
for(i=-radius;i<=radius;i++){
p=currentPixels[yi+Math.min(wm,Math.max(i,0))];
sir=stack[i+radius];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rbs=r1-Math.abs(i);
rsum+=sir[0]*rbs;
gsum+=sir[1]*rbs;
bsum+=sir[2]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
}
stackpointer=radius;
for (x=0;x<_width;x++){
if (!alpha)
alpha = (int)(Color.alpha(originalPixels[y*_width+x])) != 255;
r[yi]=dv[rsum];
g[yi]=dv[gsum];
b[yi]=dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(y==0){
vmin[x]=Math.min(x+radius+1,wm);
}
p=currentPixels[yw+vmin[x]];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[(stackpointer)%div];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi++;
}
yw+=_width;
}
for (x=0;x<_width;x++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
yp=-radius*_width;
for(i=-radius;i<=radius;i++){
yi=Math.max(0,yp)+x;
sir=stack[i+radius];
sir[0]=r[yi];
sir[1]=g[yi];
sir[2]=b[yi];
rbs=r1-Math.abs(i);
rsum+=r[yi]*rbs;
gsum+=g[yi]*rbs;
bsum+=b[yi]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if(i<hm){
yp+=_width;
}
}
yi=x;
stackpointer=radius;
for (y=0;y<_height;y++){
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
if ( alpha )
currentPixels[yi] = (0xff000000 & currentPixels[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
else
currentPixels[yi]=0xff000000 | (dv[rsum]<<16) | (dv[gsum]<<8) | dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(x==0){
vmin[y]=Math.min(y+r1,hm)*_width;
}
p=x+vmin[y];
sir[0]=r[p];
sir[1]=g[p];
sir[2]=b[p];
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[stackpointer];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi+=_width;
}
}
}
/**
* Returns the blurred image as a bitmap
* @return blurred image
*/
public Bitmap returnBlurredImage() {
Bitmap newBmp = Bitmap.createBitmap(_image.getWidth(), _image.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(newBmp);
c.drawBitmap(_image, 0, 0, new Paint());
newBmp.setPixels(currentPixels, 0, _width, 0, 0, _width, _height);
return newBmp;
}
/**
* Save the image into the file system
* @param path The path where to save the image
*/
public void saveIntoFile(String path) {
Bitmap newBmp = Bitmap.createBitmap(_image.getWidth(), _image.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(newBmp);
c.drawBitmap(_image, 0, 0, new Paint());
newBmp.setPixels(currentPixels, 0, _width, 0, 0, _width, _height);
try {
FileOutputStream out = new FileOutputStream(path);
newBmp.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the original image as a bitmap
* @return the original bitmap image
*/
public Bitmap getImage() {
return this._image;
}
}
|
package dbConnectors;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Abstracts SQL connections
* @author William Falcon
*
*/
public class MYSQLConnector {
//DB settings
private static final String DB_USER_NAME = "root";
private static final String USER_PASSWORD = "";
private static final String CONNECTION_URL = "jdbc:mysql://localhost:3306/";
private static final String DB_NAME = "Sample";
//JDBC Driver
private static final String DRIVER = "com.mysql.jdbc.Driver";
/**
* Class constructor
*/
public MYSQLConnector(){
//Connect JDBC driver
connectJDBCDriver();
}
/**
* Connects JDBC driver
*/
private void connectJDBCDriver(){
try {
//Connect
Class.forName(DRIVER).newInstance();
System.out.println("Driver started succesfully");
System.out.println("Connected to MYSQL database");
} catch (ClassNotFoundException e) {
// Error message
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Executes a SQL query and returns an arrayList of objects from the result
* @param sqlQuery
* @param Object template
* @return arrayList of objects
* @author William Falcon
*/
public ArrayList<Object> getObjectResultsFromQuery(String sqlQuery, Object template) throws Exception{
//Init results
ArrayList<Object> results = new ArrayList<Object>();
//Connect and execute query
Connection connection = DriverManager.getConnection(CONNECTION_URL+DB_NAME,DB_USER_NAME,USER_PASSWORD);
Statement statement = connection.createStatement();
//Handle queries without results needed
if (template==null) {
if (sqlQuery.contains("DELETE")) {
statement.executeUpdate(sqlQuery);
return null;
}
statement.executeQuery(sqlQuery);
return null;
}
//execute sql query
ResultSet resultSet = statement.executeQuery(sqlQuery);
Class<?> newClass = Class.forName(template.getClass().getName());
Object result;
//Extract results
while (resultSet.next()) {
//Get object back
result = newClass.newInstance();
result = MYSQLParser.mapSQLResultToObject(result, resultSet);
//Add to results
results.add(result);
}
//Close resources
connection.close();
statement.close();
resultSet.close();
//Return results
return results;
}
/**
* Executes any sql query.
* Takes an array of parameters to apply to query.
* Query should have a question mark in every parameter.
*
* Sample use: sql.executeGenericQuery("SELECT * FROM db.user WHERE name LIKE ?", new ArrayList(Arrays.asList("bob")));
*
* @param sqlQuery
* @param preparedStatementParameters
* @return
* @throws Exception
*/
public ArrayList<Object> executeGenericQuery(String sqlQuery, ArrayList<String> preparedStatementParameters) throws Exception{
//Standardize query
sqlQuery = sqlQuery.toLowerCase();
ArrayList<Object> results = new ArrayList<Object>();
ResultSet resultSet = null;
Connection connection = null;
PreparedStatement statement = null;
try {
//Connect and execute query
connection = DriverManager.getConnection(CONNECTION_URL+DB_NAME,DB_USER_NAME,USER_PASSWORD);
statement = connection.prepareStatement(sqlQuery);
//Add the parameter values to the statement
if (preparedStatementParameters!=null) {
for (int i = 0; i < preparedStatementParameters.size(); i++) {
statement.setString(i+1, preparedStatementParameters.get(i));
}
}
//Handle all other cases except select
if (!sqlQuery.contains("select")) {
statement.executeUpdate();
//Handle select statement
}else {
//execute sql query
resultSet = statement.executeQuery();
//Parse results
results = MYSQLParser.resultSetToArrayList(resultSet);
}
}catch (Exception e) {
//Pass the exception up
throw e;
}finally{
//Close resources whether successful or not
if (connection!=null) {
connection.close();
}
if (statement!=null) {
statement.close();
}
if (resultSet!=null) {
resultSet.close();
}
}
//Return results
return results;
}
/**
* Inserts list of objects into a specific table
* @param tableName
* @param objects
* @throws Exception
* @author waf04
*/
public void insertObjectList(String tableName, ArrayList<?> objects) throws Exception{
//Init connection
Connection connection = DriverManager.getConnection(CONNECTION_URL+DB_NAME,DB_USER_NAME,USER_PASSWORD);
int count =0;
//Iterate over objects
for (Object object : objects) {
//Track progress
count ++;
System.out.println(count+"/"+objects.size());
//Insert
insertObject(object, tableName, connection);
}
//Close resources
connection.close();
}
/**
* Inserts any object into SQL using the corresponding table
* @param tableName
* @param object
* @throws Exception
* @author waf04
*/
public void insertObject(String tableName, Object object) throws Exception{
//Create connection
Connection connection = DriverManager.getConnection(CONNECTION_URL+DB_NAME,DB_USER_NAME,USER_PASSWORD);
//Insert object
insertObject(object, tableName, connection);
//Close resources
connection.close();
}
/**
* Inserts ANY object into the database using it's own prepared statement
* It uses reflection to create the query and the prepared statement
*
* myId will NOT be inserted (allow auto increment to do its thing)
* @param object
* @return
* @author waf04
*/
private void insertObject(Object object, String tableName, Connection connection) throws Exception{
//Get the object's fields
Field[] objectFields = object.getClass().getDeclaredFields();
//Set which fields are not relationships
ArrayList<String>allowedFields = new ArrayList<String>();
allowedFields.add("int");
allowedFields.add("java.lang.String");
allowedFields.add("double");
allowedFields.add("java.lang.Double");
allowedFields.add("java.lang.Integer");
//Only the fields to insert for the object
ArrayList<Field> mainObjectQueryFields = new ArrayList<Field>();
String type;
//Remove all array types
for (Field field : objectFields) {
//Get the name of that type
type = field.getType().getName();
//If the array has the field, add to array for main insert
if (allowedFields.contains(type) && field.getName()!="myId") {
mainObjectQueryFields.add(field);
}
}
//Create joint columns string (id, name, etc...) and (?,?)
String columns = new String();
String questionMarks = new String();
Field field = null;
//Iterate over fields
for (int i=0; i<mainObjectQueryFields.size(); i++) {
//Get field
field = mainObjectQueryFields.get(i);
//If the last object don't add a comma
if (i==mainObjectQueryFields.size()-1) {
columns+= field.getName();
questionMarks += "?";
}else {
//Append to string
columns += field.getName() + ", ";
questionMarks += "?,";
}
}
//Make private connection
Connection privateConnection = connection;
//Create prepared statement
PreparedStatement genericStatement = privateConnection.prepareStatement("INSERT INTO " + tableName + " (" + columns + ") VALUES (" +questionMarks+ ")");
Object value = null;
//For each field add to prepared statement
for (int i = 0; i < mainObjectQueryFields.size(); i++) {
//Get the field
field = mainObjectQueryFields.get(i);
field.setAccessible(true);
//Get the value at that field
value = field.get(object);
//Set the object at that prepared statement index
genericStatement.setObject(i+1, value);
}
//Execute the prepared statement
genericStatement.execute();
//Close resources
genericStatement.close();
}
/**
* Updates an object in the specific table
* @param tableName
* @param object
* @throws Exception
*/
public void updateObject(String tableName, Object object, Connection connection) throws Exception{
//Insert object
updateObject(object, tableName, connection);
}
/**
* Updates an object in the specific table
* @param tableName
* @param object
* @throws Exception
*/
public void updateObject(String tableName, Object object) throws Exception{
//Init connection
Connection connection = DriverManager.getConnection(CONNECTION_URL+DB_NAME,DB_USER_NAME,USER_PASSWORD);
//Insert object
updateObject(object, tableName, connection);
//Close resources
connection.close();
}
/**
* Updates a list of objects in a specific table
* @param tableName
* @param objects
* @throws Exception
*/
public void updateObjectList(String tableName, ArrayList<?> objects) throws Exception{
//Init connection
Connection connection = DriverManager.getConnection(CONNECTION_URL+DB_NAME,DB_USER_NAME,USER_PASSWORD);
int count =0;
//Iterate and insert
for (Object object : objects) {
count++;
System.out.println(count);
updateObject(object, tableName, connection);
}
//Close resources
connection.close();
}
/**
* Inserts ANY object into the database using it's own prepared statement
* It uses reflection to create the query and the prepared statement
*
* myId will NOT be inserted (allow auto increment to do its thing)
* @param object
* @return
* @author waf04
*/
private void updateObject(Object object, String tableName, Connection connection) throws Exception{
//Get the object's fields
Field[] objectFields = object.getClass().getDeclaredFields();
//Set which fields are not relationships
ArrayList<String>allowedFields = new ArrayList<String>();
allowedFields.add("int");
allowedFields.add("java.lang.String");
allowedFields.add("double");
allowedFields.add("java.lang.Double");
allowedFields.add("java.lang.Integer");
//Only the fields to insert for the object
ArrayList<Field> mainObjectQueryFields = new ArrayList<Field>();
//Init myId
String myId = new String();
String type = new String();
//Remove all array types
for (Field field : objectFields) {
field.setAccessible(true);
//Get the name of that type
type = field.getType().getName();
//If the array has the field, add to array for main insert
if (allowedFields.contains(type) && !field.getName().equals("myId")) {
mainObjectQueryFields.add(field);
}else if (field.getName().equals("myId")) {
//Get myId
Integer myIdInt = field.getInt(object);
myId = Integer.toString(myIdInt);
}
}
//Create joint columns string (id, name, etc...) and (?,?)
String columns = new String();
Field field = null;
//Iterate over fields
for (int i=0; i<mainObjectQueryFields.size(); i++) {
//Get field
field = mainObjectQueryFields.get(i);
//If the last object don't add a comma
if (i==mainObjectQueryFields.size()-1) {
columns+= field.getName()+" = ?";
}else {
//Append to string
columns += field.getName() + " = ? , ";
}
}
//Make private connection
Connection privateConnection = connection;
//Create prepared statement
PreparedStatement genericStatement = privateConnection.prepareStatement("UPDATE " + tableName + " SET " + columns + " WHERE myId = "+myId);
Object value = new Object();
//For each field add to prepared statement
for (int i = 0; i < mainObjectQueryFields.size(); i++) {
//Get the field
mainObjectQueryFields.get(i);
field.setAccessible(true);
//Get the value at that field
value = field.get(object);
//Set the object at that prepared statement index
genericStatement.setObject(i+1, value);
}
//Execute the prepared statement
genericStatement.execute();
//Close resources
genericStatement.close();
}
}
|
package api.web.gw2.mapping.v2.wvw.objectives;
import api.web.gw2.mapping.core.Coord2DValue;
import api.web.gw2.mapping.core.Coord3DValue;
import api.web.gw2.mapping.v2.wvw.MapType;
import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.core.OptionalValue;
import api.web.gw2.mapping.core.Point2D;
import api.web.gw2.mapping.core.Point3D;
import api.web.gw2.mapping.core.URLReference;
import api.web.gw2.mapping.core.URLValue;
import api.web.gw2.mapping.v2.APIv2;
import java.util.OptionalInt;
@APIv2(endpoint = "v2/wvw/objectives") // NOI18N.
public interface Objective {
/**
* Gets the id of this objective.
* @return A {@code String} instance, never {@code null}.
*/
@IdValue(flavor = IdValue.Flavor.STRING)
String getId();
/**
* Gets the i18n abstract name of this objective.
* <br>Note: this may not be the same as the name in game.
* @return A {@code String} instance, never {@code null}.
*/
@LocalizedResource
String getName();
/**
* Gets the id of the sector containing this objective.
* @return An {@code int} > 0.
*/
@IdValue
int getSectorId();
/**
* Gets the type of this objective.
* @return An {@code ObjectiveType} instance, never {@code null}.
*/
ObjectiveType getType();
/**
* Gets the map type of this objective.
* @return An {@code MapType} instance, never {@code null}.
*/
MapType getMapType();
/**
* Gets the if of the map of this objective.
* @return An {@code int}.
*/
@IdValue
int getMapId();
/**
* Gets the coordinates of this objective.
* @return An {@code Point3D} instance, never {@code null}.
*/
@Coord3DValue
Point3D getCoord();
/**
* Gets the coordinates of of the label for this objective.
* @return An {@code Point2D} instance, never {@code null}.
*/
@Coord2DValue
Point2D getLabelCoord();
/**
* Gets the URL to the marker icon for this objective.
* @return A {@code URLReference} instance, never {@code null}.
*/
@URLValue
URLReference getMarker();
/**
* Gets the chat link needed to pass this objective to other players.
* @return A {@code String} instance, never {@code null}.
* <br>Old JSON files from earlier versions of the API or objectives that
* cannot be linked may return an empty {@code string}.
*/
String getChatLink();
/**
* Gets the id of the upgrade of this objective.
* @return An {@code OptionalInt} instance, never {@code null}.
*/
@IdValue
@OptionalValue
OptionalInt getUpgradeId();
}
|
package bramble.webserver;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpStatus;
public class TotalJobSlotsHandler extends HttpServlet {
private static final long serialVersionUID = 5414855470057516723L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.setStatus(HttpStatus.OK_200);
resp.getWriter().print(WebAPI.getTotalJobSlots());
}
}
|
package com.zireck.remotecraft.view.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import butterknife.BindView;
import com.zireck.remotecraft.R;
import com.zireck.remotecraft.imageloader.ImageLoader;
import com.zireck.remotecraft.imageloader.PicassoImageLoader;
import com.zireck.remotecraft.presenter.SearchPresenter;
import javax.inject.Inject;
public class SearchActivity extends BaseActivity {
@Inject SearchPresenter presenter;
@BindView(R.id.background) ImageView background;
public static Intent getCallingIntent(Context context) {
return new Intent(context, SearchActivity.class);
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
initInjector();
initUi();
}
@Override protected void onResume() {
super.onResume();
presenter.resume();
}
@Override protected void onPause() {
super.onPause();
presenter.pause();
}
@Override protected void onDestroy() {
super.onDestroy();
presenter.destroy();
}
private void initInjector() {
getApplicationComponent().inject(this);
}
private void initUi() {
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
ImageLoader imageLoader = new PicassoImageLoader(this);
imageLoader.load(R.drawable.mesa, background);
}
}
|
package org.bouncycastle.jce.provider.test;
import junit.framework.TestCase;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Assert;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.security.Security;
import java.util.*;
import java.util.stream.Collectors;
public class BouncyCastleProviderTest extends TestCase {
private BouncyCastleProvider provider;
protected void setUp() {
provider = new BouncyCastleProvider();
Security.addProvider(provider);
}
protected void tearDown() {
Security.removeProvider(provider.getName());
}
public void testRegisteredClasses() {
Set<Object> keys = new TreeSet<>(provider.keySet());
List<String> errors = new ArrayList<>();
for (Object rawKey : keys) {
try {
Assert.assertTrue(rawKey instanceof String);
String key = (String) rawKey;
if (key.startsWith("Alg.Alias.")) {
// Skip aliases
} else {
Object rawValue = provider.get(key);
Assert.assertTrue(rawValue instanceof String);
String value = (String) rawValue;
if (value.startsWith("org.bouncycastle.")) {
if (key.startsWith("CertStore.")) {
// CertStore classes have no appropriate constructors
resolveClass(key, value);
} else {
newInstance(key, resolveClass(key, value));
}
}
}
} catch (AssertionError e) {
errors.add(e.getMessage());
}
}
if (!errors.isEmpty()) {
throw new AssertionError("Failed with the following errors:\n" + String.join("\n", errors));
}
}
/*
public void testAliases() {
Set<Object> keys = new TreeSet<>(provider.keySet());
List<String> errors = new ArrayList<>();
for (Object rawKey : keys) {
try {
Assert.assertTrue(rawKey instanceof String);
String key = (String) rawKey;
if (key.startsWith("Alg.Alias.")) {
Object rawValue = provider.get(key);
Assert.assertTrue(rawValue instanceof String);
String value = (String) rawValue;
String internal = key.substring("Alg.Alias.".length()).split("\\.")[0];
if (!value.startsWith("org.bouncycastle.")) {
String chainedKey = internal + "." + value;
Object rawChainedValue = provider.get(chainedKey);
Assert.assertNotNull(String.format("Key [%s] links to missed key [%s]", key, chainedKey), rawChainedValue);
Assert.assertTrue(rawChainedValue instanceof String);
}
}
} catch (AssertionError e) {
errors.add(e.getMessage());
}
}
if (!errors.isEmpty()) {
throw new AssertionError("Failed with the following errors:\n" + String.join("\n", errors));
}
}
*/
private static <T> Class<T> resolveClass(String key, String className) {
try {
return (Class<T>) Class.forName(className);
} catch (ClassNotFoundException e) {
throw new AssertionError(String.format("Key [%s] contains wrong class name: %s", key, className));
}
}
private static <T> T newInstance(String key, Class<T> clazz, Object... params) {
try {
if (params.length == 0) {
return clazz.getConstructor().newInstance();
} else {
MethodType constructorType = MethodType.methodType(void.class, Arrays.stream(params).map(Object::getClass).toArray(Class[]::new));
MethodHandle constructor = MethodHandles.publicLookup().findConstructor(clazz, constructorType);
return (T) constructor.invokeWithArguments(Arrays.asList(params));
}
} catch (IllegalAccessException | NoSuchMethodException e) {
throw new AssertionError(String.format("Key [%s] contains class which failed on instance creation: %s %s", key, clazz.getName(), e.getMessage()));
} catch (Throwable e) {
Throwable cause = e.getCause();
if (cause == null) {
cause = e;
}
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
throw new AssertionError(String.format("Key [%s] contains class which failed on instance creation: %s %s\n%s", key, clazz.getName(), cause.getMessage(), out.toString()));
}
}
}
|
package railo.transformer.cfml.evaluator.func.impl;
import railo.commons.lang.StringList;
import railo.runtime.exp.TemplateException;
import railo.runtime.interpreter.VariableInterpreter;
import railo.runtime.type.Collection;
import railo.runtime.type.Scope;
import railo.runtime.type.util.ArrayUtil;
import railo.transformer.bytecode.expression.Expression;
import railo.transformer.bytecode.expression.type.CollectionKey;
import railo.transformer.bytecode.expression.type.LiteralStringArray;
import railo.transformer.bytecode.expression.var.Argument;
import railo.transformer.bytecode.expression.var.BIF;
import railo.transformer.bytecode.literal.LitDouble;
import railo.transformer.bytecode.literal.LitString;
import railo.transformer.cfml.evaluator.FunctionEvaluator;
import railo.transformer.library.function.FunctionLibFunction;
public class IsDefined implements FunctionEvaluator{
public void evaluate(BIF bif, FunctionLibFunction flf) throws TemplateException {
Argument arg = bif.getArguments()[0];
Expression value = arg.getValue();
if(value instanceof LitString) {
String str=((LitString)value).getString();
StringList sl = VariableInterpreter.parse(str,false);
if(sl!=null){
// scope
str=sl.next();
int scope = VariableInterpreter.scopeString2Int(str);
if(scope==Scope.SCOPE_UNDEFINED)sl.reset();
// keys
String[] arr=sl.toArray();
ArrayUtil.trim(arr);
// update first arg
arg.setValue(new LitDouble(scope,-1),"number");
// add second argument
if(arr.length==1){
Expression expr = new CollectionKey(arr[0],-1);//LitString.toExprString(str);
arg=new Argument(expr,Collection.Key.class.getName());
bif.addArgument(arg);
}
else {
LiteralStringArray expr = new LiteralStringArray(arr,-1);
arg=new Argument(expr,String[].class.getName());
bif.addArgument(arg);
}
}
}
//print.out("bif:"+arg.getValue().getClass().getName());
}
}
|
package org.saiku.service.olap;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.olap4j.AllocationPolicy;
import org.olap4j.Axis;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.OlapConnection;
import org.olap4j.OlapException;
import org.olap4j.OlapStatement;
import org.olap4j.Scenario;
import org.olap4j.mdx.IdentifierNode;
import org.olap4j.mdx.IdentifierSegment;
import org.olap4j.metadata.Cube;
import org.olap4j.metadata.Dimension;
import org.olap4j.metadata.Hierarchy;
import org.olap4j.metadata.Level;
import org.olap4j.metadata.Member;
import org.olap4j.query.Query;
import org.olap4j.query.QueryAxis;
import org.olap4j.query.QueryDimension;
import org.olap4j.query.Selection;
import org.saiku.olap.dto.SaikuCube;
import org.saiku.olap.dto.SaikuDimensionSelection;
import org.saiku.olap.dto.SaikuQuery;
import org.saiku.olap.dto.resultset.CellDataSet;
import org.saiku.olap.query.IQuery;
import org.saiku.olap.query.MdxQuery;
import org.saiku.olap.query.OlapQuery;
import org.saiku.olap.query.QueryDeserializer;
import org.saiku.olap.util.ObjectUtil;
import org.saiku.olap.util.OlapResultSetUtil;
import org.saiku.olap.util.exception.SaikuOlapException;
import org.saiku.olap.util.formatter.CellSetFormatter;
import org.saiku.olap.util.formatter.CheatCellSetFormatter;
import org.saiku.olap.util.formatter.HierarchicalCellSetFormatter;
import org.saiku.olap.util.formatter.ICellSetFormatter;
import org.saiku.service.util.OlapUtil;
import org.saiku.service.util.exception.SaikuServiceException;
import org.saiku.service.util.export.CsvExporter;
import org.saiku.service.util.export.ExcelExporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OlapQueryService {
private static final Logger log = LoggerFactory.getLogger(OlapQueryService.class);
private OlapDiscoverService olapDiscoverService;
private Map<String,IQuery> queries = new HashMap<String,IQuery>();
public void setOlapDiscoverService(OlapDiscoverService os) {
olapDiscoverService = os;
}
public SaikuQuery createNewOlapQuery(String queryName, SaikuCube cube) {
try {
Cube cub = olapDiscoverService.getNativeCube(cube);
if (cub != null) {
IQuery query = new OlapQuery(new Query(queryName, cub),cube);
queries.put(queryName, query);
return ObjectUtil.convert(query);
}
} catch (Exception e) {
log.error("Cannot create new query for cube :" + cube,e);
}
return null;
}
public SaikuQuery createNewOlapQuery(String name, String xml) {
try {
SaikuCube scube = QueryDeserializer.getFakeCube(xml);
OlapConnection con = olapDiscoverService.getNativeConnection(scube.getConnectionName());
IQuery query = QueryDeserializer.unparse(xml, con);
if (name == null) {
queries.put(query.getName(), query);
}
else {
queries.put(name, query);
}
return ObjectUtil.convert(query);
} catch (Exception e) {
throw new SaikuServiceException("Error creating query from xml",e);
}
}
public void closeQuery(String queryName) {
queries.remove(queryName);
OlapUtil.deleteCellSet(queryName);
}
public List<String> getQueries() {
List<String> queryList = new ArrayList<String>();
queryList.addAll(queries.keySet());
return queryList;
}
public SaikuQuery getQuery(String queryName) {
IQuery q = getIQuery(queryName);
return ObjectUtil.convert(q);
}
public void deleteQuery(String queryName) {
queries.remove(queryName);
}
public CellDataSet execute(String queryName) {
return execute(queryName,new HierarchicalCellSetFormatter());
}
public CellDataSet execute(String queryName, String formatter) {
formatter = formatter == null ? "" : formatter.toLowerCase();
if(formatter.equals("flat")) {
return execute(queryName, new CellSetFormatter());
}
else if (formatter.equals("hierarchical")) {
return execute(queryName, new HierarchicalCellSetFormatter());
}
else if (formatter.equals("cheat")) {
return execute(queryName, new CheatCellSetFormatter());
}
return execute(queryName, new HierarchicalCellSetFormatter());
}
public CellDataSet execute(String queryName, ICellSetFormatter formatter) {
try {
IQuery query = getIQuery(queryName);
OlapConnection con = olapDiscoverService.getNativeConnection(query.getSaikuCube().getConnectionName());
Long start = (new Date()).getTime();
if (query.getScenario() != null) {
log.info("Query (" + queryName + ") Setting scenario:" + query.getScenario().getId());
con.setScenario(query.getScenario());
}
CellSet cellSet = query.execute();
Long exec = (new Date()).getTime();
if (query.getScenario() != null) {
log.info("Query (" + queryName + ") removing scenario:" + query.getScenario().getId());
con.setScenario(null);
}
CellDataSet result = OlapResultSetUtil.cellSet2Matrix(cellSet,formatter);
Long format = (new Date()).getTime();
log.info("Size: " + result.getWidth() + "/" + result.getHeight() + "\tExecute:\t" + (exec - start)
+ "ms\tFormat:\t" + (format - exec) + "ms\t Total: " + (format - start) + "ms");
result.setRuntime(new Double(format - start).intValue());
OlapUtil.storeCellSet(queryName, cellSet);
return result;
} catch (Exception e) {
throw new SaikuServiceException("Can't execute query: " + queryName,e);
}
}
public void setMdx(String queryName, String mdx) {
IQuery q = getIQuery(queryName);
q.setMdx(mdx);
}
public CellDataSet executeMdx(String queryName, String mdx) {
qm2mdx(queryName);
setMdx(queryName, mdx);
return execute(queryName, new HierarchicalCellSetFormatter());
}
public CellDataSet executeMdx(String queryName, String mdx, ICellSetFormatter formatter) {
setMdx(queryName, mdx);
return execute(queryName, formatter);
}
public ResultSet drillthrough(String queryName, int maxrows) {
try {
final OlapConnection con = olapDiscoverService.getNativeConnection(getQuery(queryName).getCube().getConnectionName());
final OlapStatement stmt = con.createStatement();
String mdx = getMDXQuery(queryName);
if (maxrows > 0) {
mdx = "DRILLTHROUGH MAXROWS " + maxrows + " " + mdx;
}
else {
mdx = "DRILLTHROUGH " + mdx;
}
return stmt.executeQuery(mdx);
} catch (SQLException e) {
throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName,e);
}
}
public ResultSet drillthrough(String queryName, List<Integer> cellPosition, Integer maxrows) {
try {
IQuery q = getIQuery(queryName);
CellSet cs = OlapUtil.getCellSet(queryName);
SaikuCube cube = getQuery(queryName).getCube();
final OlapConnection con = olapDiscoverService.getNativeConnection(cube.getConnectionName());
final OlapStatement stmt = con.createStatement();
String select = "SELECT (";
for (int i = 0; i < cellPosition.size(); i++) {
List<Member> members = cs.getAxes().get(i).getPositions().get(cellPosition.get(i)).getMembers();
for (int k = 0; k < members.size(); k++) {
Member m = members.get(k);
if (k > 0 || i > 0) {
select += ", ";
}
select += m.getUniqueName();
}
}
List<QueryDimension> dims = q.getAxes().get(Axis.FILTER).getDimensions();
for (QueryDimension dim : dims) {
for (Selection sel : dim.getInclusions()) {
if ((sel.getRootElement() instanceof Member)) {
select += ", " + sel.getUniqueName();
}
}
}
select += ") ON COLUMNS \r\n";
select += "FROM " + cube.getCubeName();
if (maxrows > 0) {
select = "DRILLTHROUGH MAXROWS " + maxrows + " " + select + "\r\n";
}
else {
select = "DRILLTHROUGH " + select + "\r\n";
}
log.debug("Drill Through for query (" + queryName + ") : \r\n" + select);
return stmt.executeQuery(select);
} catch (Exception e) {
throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName,e);
}
}
public byte[] exportDrillthroughCsv(String queryName, int maxrows) {
try {
final OlapConnection con = olapDiscoverService.getNativeConnection(getQuery(queryName).getCube().getConnectionName());
final OlapStatement stmt = con.createStatement();
String mdx = getMDXQuery(queryName);
if (maxrows > 0) {
mdx = "DRILLTHROUGH MAXROWS " + maxrows + " " + mdx;
}
else {
mdx = "DRILLTHROUGH " + mdx;
}
ResultSet rs = stmt.executeQuery(mdx);
return CsvExporter.exportCsv(rs);
} catch (SQLException e) {
throw new SaikuServiceException("Error DRILLTHROUGH: " + queryName,e);
}
}
public byte[] exportResultSetCsv(ResultSet rs) {
return CsvExporter.exportCsv(rs);
}
public void setCellValue(String queryName, List<Integer> position, String value, String allocationPolicy) {
try {
IQuery query = getIQuery(queryName);
OlapConnection con = olapDiscoverService.getNativeConnection(query.getSaikuCube().getConnectionName());
Scenario s;
if (query.getScenario() == null) {
s = con.createScenario();
query.setScenario(s);
con.setScenario(s);
System.out.println("Created scenario:" + s + " : cell:" + position + " value" + value);
} else {
s = query.getScenario();
con.setScenario(s);
System.out.println("Using scenario:" + s + " : cell:" + position + " value" + value);
}
CellSet cs1 = query.execute();
OlapUtil.storeCellSet(queryName, cs1);
Object v = null;
try {
v = Integer.parseInt(value);
} catch (Exception e) {
v = Double.parseDouble(value);
}
if (v == null) {
throw new SaikuServiceException("Error setting value of query " + queryName + " to:" + v);
}
allocationPolicy = AllocationPolicy.EQUAL_ALLOCATION.toString();
AllocationPolicy ap = AllocationPolicy.valueOf(allocationPolicy);
CellSet cs = OlapUtil.getCellSet(queryName);
cs.getCell(position).setValue(v, ap);
con.setScenario(null);
} catch (Exception e) {
throw new SaikuServiceException("Error setting value: " + queryName,e);
}
}
public void swapAxes(String queryName) {
getIQuery(queryName).swapAxes();
}
public boolean includeMember(String queryName, String dimensionName, String uniqueMemberName, String selectionType, int memberposition){
IQuery query = getIQuery(queryName);
List<IdentifierSegment> memberList = IdentifierNode.parseIdentifier(uniqueMemberName).getSegmentList();
QueryDimension dimension = query.getDimension(dimensionName);
final Selection.Operator selectionMode = Selection.Operator.valueOf(selectionType);
try {
Selection sel = dimension.createSelection(selectionMode, memberList);
if (dimension.getInclusions().contains(sel)) {
dimension.getInclusions().remove(sel);
}
if (memberposition < 0) {
memberposition = dimension.getInclusions().size();
}
dimension.getInclusions().add(memberposition, sel);
return true;
} catch (OlapException e) {
throw new SaikuServiceException("Cannot include member query ("+queryName+") dimension (" + dimensionName + ") member ("+
uniqueMemberName+") operator (" + selectionType + ") position " + memberposition,e);
}
}
public boolean removeMember(String queryName, String dimensionName, String uniqueMemberName, String selectionType) throws SaikuServiceException{
IQuery query = getIQuery(queryName);
List<IdentifierSegment> memberList = IdentifierNode.parseIdentifier(uniqueMemberName).getSegmentList();
QueryDimension dimension = query.getDimension(dimensionName);
final Selection.Operator selectionMode = Selection.Operator.valueOf(selectionType);
try {
if (log.isDebugEnabled()) {
log.debug("query: "+queryName+" remove:" + selectionMode.toString() + " " + memberList.size());
}
Selection selection = dimension.createSelection(selectionMode, memberList);
dimension.getInclusions().remove(selection);
if (dimension.getInclusions().size() == 0) {
moveDimension(queryName, null, dimensionName, -1);
}
return true;
} catch (OlapException e) {
throw new SaikuServiceException("Error removing member (" + uniqueMemberName + ") of dimension (" +dimensionName+")",e);
}
}
public boolean includeLevel(String queryName, String dimensionName, String uniqueHierarchyName, String uniqueLevelName) {
IQuery query = getIQuery(queryName);
QueryDimension dimension = query.getDimension(dimensionName);
for (Hierarchy hierarchy : dimension.getDimension().getHierarchies()) {
if (hierarchy.getUniqueName().equals(uniqueHierarchyName)) {
for (Level level : hierarchy.getLevels()) {
if (level.getUniqueName().equals(uniqueLevelName)) {
Selection sel = dimension.createSelection(level);
if (!dimension.getInclusions().contains(sel)) {
dimension.include(level);
}
return true;
}
}
}
}
return false;
}
public boolean removeLevel(String queryName, String dimensionName, String uniqueHierarchyName, String uniqueLevelName) {
IQuery query = getIQuery(queryName);
QueryDimension dimension = query.getDimension(dimensionName);
try {
for (Hierarchy hierarchy : dimension.getDimension().getHierarchies()) {
if (hierarchy.getUniqueName().equals(uniqueHierarchyName)) {
for (Level level : hierarchy.getLevels()) {
if (level.getUniqueName().equals(uniqueLevelName)) {
Selection inclusion = dimension.createSelection(level);
dimension.getInclusions().remove(inclusion);
ArrayList<Selection> removals = new ArrayList<Selection>();
for (Selection sel :dimension.getInclusions()) {
if ((sel.getRootElement() instanceof Member)) {
if (((Member) sel.getRootElement()).getLevel().equals(level)) {
if (dimension.getInclusions().contains(sel)) {
removals.add(sel);
}
}
}
}
dimension.getInclusions().removeAll(removals);
if (dimension.getInclusions().size() == 0) {
moveDimension(queryName, null , dimensionName, -1);
}
}
}
}
}
} catch (Exception e) {
throw new SaikuServiceException("Cannot remove level" + uniqueLevelName + "from dimension " + dimensionName,e);
}
return true;
}
public void moveDimension(String queryName, String axisName, String dimensionName, int position) {
try {
if (log.isDebugEnabled()) {
log.debug("move query: " + queryName + " dimension " + dimensionName + " to axis " + axisName + " position" + position);
}
IQuery query = getIQuery(queryName);
QueryDimension dimension = query.getDimension(dimensionName);
Axis newAxis = axisName != null ? ( "UNUSED".equals(axisName) ? null : Axis.Standard.valueOf(axisName)) : null;
if(position==-1){
query.moveDimension(dimension, newAxis);
}
else{
query.moveDimension(dimension, newAxis, position);
}
}
catch (Exception e) {
throw new SaikuServiceException("Cannot move dimension:" + dimensionName + " to axis: "+axisName,e);
}
}
public void removeDimension(String queryName, String axisName, String dimensionName) {
IQuery query = getIQuery(queryName);
moveDimension(queryName, "UNUSED" , dimensionName, -1);
query.getDimension(dimensionName).getExclusions().clear();
query.getDimension(dimensionName).getInclusions().clear();
}
public List<SaikuDimensionSelection> getAxisSelection(String queryName, String axis) {
IQuery query = getIQuery(queryName);
List<SaikuDimensionSelection> dimsel = new ArrayList<SaikuDimensionSelection>();
try {
QueryAxis qaxis = query.getAxis(axis);
if (qaxis != null) {
for (QueryDimension dim : qaxis.getDimensions()) {
dimsel.add(ObjectUtil.convertDimensionSelection(dim));
}
}
} catch (SaikuOlapException e) {
throw new SaikuServiceException("Cannot get dimension selections",e);
}
return dimsel;
}
public SaikuDimensionSelection getAxisDimensionSelections(String queryName, String axis, String dimension) {
IQuery query = getIQuery(queryName);
try {
QueryAxis qaxis = query.getAxis(axis);
if (qaxis != null) {
QueryDimension dim = query.getDimension(dimension);
if (dim != null) {
return ObjectUtil.convertDimensionSelection(dim);
}
else
{
throw new SaikuOlapException("Cannot find dimension with name:" + dimension);
}
}
else {
throw new SaikuOlapException("Cannot find axis with name:" + axis);
}
} catch (SaikuOlapException e) {
throw new SaikuServiceException("Cannot get dimension selections",e);
}
}
public void clearQuery(String queryName) {
IQuery query = getIQuery(queryName);
query.clearAllQuerySelections();
}
public void clearAxis(String queryName, String axisName) {
IQuery query = getIQuery(queryName);
if (Axis.Standard.valueOf(axisName) != null) {
QueryAxis qAxis = query.getAxis(Axis.Standard.valueOf(axisName));
query.resetAxisSelections(qAxis);
for (QueryDimension dim : qAxis.getDimensions()) {
qAxis.removeDimension(dim);
}
}
}
public void clearAxisSelections(String queryName, String axisName) {
IQuery query = getIQuery(queryName);
if (Axis.Standard.valueOf(axisName) != null) {
QueryAxis qAxis = query.getAxis(Axis.Standard.valueOf(axisName));
query.resetAxisSelections(qAxis);
}
}
public void resetQuery(String queryName) {
IQuery query = getIQuery(queryName);
query.resetQuery();
}
public void setNonEmpty(String queryName, String axisName, boolean bool) {
IQuery query = getIQuery(queryName);
QueryAxis newAxis = query.getAxis(Axis.Standard.valueOf(axisName));
newAxis.setNonEmpty(bool);
}
public Properties setProperties(String queryName, Properties props) {
IQuery query = getIQuery(queryName);
query.setProperties(props);
return getProperties(queryName);
}
public Properties getProperties(String queryName) {
IQuery query = getIQuery(queryName);
OlapConnection con = olapDiscoverService.getNativeConnection(query.getSaikuCube().getConnectionName());
Properties props = query.getProperties();
try {
con.createScenario();
if (query.getDimension("Scenario") != null) {
props.put("org.saiku.connection.scenario", Boolean.toString(true));
}
else {
props.put("org.saiku.connection.scenario", Boolean.toString(false));
}
} catch (Exception e) {
props.put("org.saiku.connection.scenario", Boolean.toString(false));
}
return props;
}
public String getMDXQuery(String queryName) {
return getIQuery(queryName).getMdx();
}
public String getQueryXml(String queryName) {
IQuery query = getIQuery(queryName);
return query.toXml();
}
public byte[] getExport(String queryName, String type) {
return getExport(queryName,type,new HierarchicalCellSetFormatter());
}
public byte[] getExport(String queryName, String type, String formatter) {
formatter = formatter == null ? "" : formatter.toLowerCase();
if (formatter.equals("flat")) {
return getExport(queryName, type, new CellSetFormatter());
} else if (formatter.equals("hierarchical")) {
return getExport(queryName, type, new HierarchicalCellSetFormatter());
}
return getExport(queryName, type, new HierarchicalCellSetFormatter());
}
public byte[] getExport(String queryName, String type, ICellSetFormatter formatter) {
if (type != null) {
CellSet rs = OlapUtil.getCellSet(queryName);
if (type.toLowerCase().equals("xls")) {
return ExcelExporter.exportExcel(rs,formatter);
}
if (type.toLowerCase().equals("csv")) {
return CsvExporter.exportCsv(rs,",","\"", formatter);
}
}
return new byte[0];
}
public void qm2mdx(String queryName) {
IQuery query = queries.get(queryName);
OlapConnection con = olapDiscoverService.getNativeConnection(query.getSaikuCube().getConnectionName());
MdxQuery mdx = new MdxQuery(con, query.getSaikuCube(), query.getName(),getMDXQuery(queryName));
queries.put(queryName, mdx);
query = null;
}
private IQuery getIQuery(String queryName) {
IQuery query = queries.get(queryName);
if (query == null) {
throw new SaikuServiceException("No query with name ("+queryName+") found");
}
return query;
}
}
|
package com.snobot2016;
import com.snobot.xlib.PropertyManager.BooleanProperty;
import com.snobot.xlib.PropertyManager.DoubleProperty;
import com.snobot.xlib.PropertyManager.IntegerProperty;
import com.snobot.xlib.PropertyManager.StringProperty;
import edu.wpi.first.wpilibj.RobotBase;
public class Properties2016
{
public static final boolean sIS_REAL_ROBOT = true;
public static final boolean sUSE_SPI_GYRO = true;
public static final boolean sUSE_IMU_POSITIONER = false;
|
package com.smartdevicelink.api.screen;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import com.smartdevicelink.R;
import com.smartdevicelink.api.BaseSubManager;
import com.smartdevicelink.api.FileManager;
import com.smartdevicelink.api.SdlArtwork;
import com.smartdevicelink.proxy.interfaces.ISdl;
import com.smartdevicelink.proxy.rpc.DisplayCapabilities;
import com.smartdevicelink.proxy.rpc.MetadataTags;
import com.smartdevicelink.proxy.rpc.Show;
import com.smartdevicelink.proxy.rpc.TextField;
import com.smartdevicelink.proxy.rpc.enums.FileType;
import com.smartdevicelink.proxy.rpc.enums.MetadataType;
import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType;
import org.json.JSONException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* <strong>TextAndGraphicManager</strong> <br>
*
* Note: This class must be accessed through the SdlManager. Do not instantiate it by itself. <br>
*
* The TextAndGraphicManager <br>
*
* It is broken down to these areas: <br>
*
* 1. <br>
*/
class TextAndGraphicManager extends BaseSubManager {
private static final String TAG = "TextAndGraphicManager";
private FileManager fileManager;
private Show currentScreenData;
private Context context;
private SdlArtwork blankArtwork;
private DisplayCapabilities displayCapabilities;
protected boolean batchUpdates;
protected SdlArtwork primaryGraphic, secondaryGraphic;
protected TextAlignment textAlignment;
protected String textField1, textField2, textField3, textField4, mediaTrackTextField;
protected MetadataType textField1Type, textField2Type, textField3Type, textField4Type;
//Constructors
TextAndGraphicManager(ISdl internalInterface, FileManager fileManager, Context context) {
// set class vars
super(internalInterface);
this.fileManager = fileManager;
this.context = context;
batchUpdates = false;
getBlankArtwork();
getDisplayCapabilities();
transitionToState(READY);
}
@Override
public void dispose(){
textField1 = null;
textField1Type = null;
textField2 = null;
textField2Type = null;
textField3 = null;
textField3Type = null;
textField4 = null;
textField4Type = null;
mediaTrackTextField = null;
textAlignment = null;
primaryGraphic = null;
secondaryGraphic = null;
blankArtwork = null;
displayCapabilities = null;
// transition state
transitionToState(SHUTDOWN);
}
// Upload / Send
protected void update() {
// check if is batch update
// make sure hmi is not none
// create show
// check if only text
// if image is already there, send
// if image not there, upload
// send show
}
// Images
private void uploadImages() {
//ArrayList<SDLArtwork> artworksToUpload = new ArrayList<>();
// add primary image
// add secondary image
// use file manager to upload art
}
private Show assembleShowImages(Show show){
// attach primary and secondary images if there
return show;
}
// Text
private Show assembleShowText(Show show){
if (mediaTrackTextField != null){
show.setMediaTrack(mediaTrackTextField);
} else {
show.setMediaTrack("");
}
List<String> nonNullFields = findNonNullTextFields();
if (nonNullFields.size() == 0){
return show;
}
int numberOfLines = getNumberOfLines();
if (numberOfLines == 1){
show = assembleOneLineShowText(show, nonNullFields);
}else if (numberOfLines == 2){
show = assembleTwoLineShowText(show);
}else if (numberOfLines == 3){
show = assembleThreeLineShowText(show);
}else if (numberOfLines == 4){
show = assembleFourLineShowText(show);
}
return show;
}
private Show assembleOneLineShowText(Show show, List<String> showFields){
StringBuilder showString1 = new StringBuilder();
for (int i = 1; i < showFields.size(); i++) {
showString1.append(" - ").append(showFields.get(i));
}
show.setMainField1(showString1.toString());
MetadataTags tags = new MetadataTags();
tags.setMainField1(findNonNullMetadataFields());
return show;
}
private Show assembleTwoLineShowText(Show show){
StringBuilder tempString = new StringBuilder();
MetadataTags tags = show.getMetadataTags();
if (textField1 != null && textField1.length() > 0) {
tempString.append(textField1);
if (textField1Type != null){
tags.setMainField1(textField1Type);
}
}
if (textField2 != null && textField2.length() > 0) {
if (textField3 == null || !(textField3.length() > 0) || textField4 == null || !(textField4.length() > 0)){
// text does not exist in slots 3 or 4, put i slot 2
show.setMainField2(textField2);
if (textField2Type != null){
tags.setMainField2(textField2Type);
}
} else if (textField1 != null && textField1.length() > 0) {
// If text 1 exists, put it in slot 1 formatted
tempString.append(" - ").append(textField2);
if (textField2Type != null){
List<MetadataType> tags2 = tags.getMainField1();
tags2.add(textField2Type);
tags.setMainField1(tags2);
}
}else {
// If text 1 does not exist, put it in slot 1 unformatted
tempString.append(textField2);
if (textField2Type != null){
tags.setMainField1(textField2Type);
}
}
}
// set mainfield 1
show.setMainField1(tempString.toString());
// new stringbuilder object
tempString = new StringBuilder();
if (textField3 != null && textField3.length() > 0){
// If text 3 exists, put it in slot 2
tempString.append(textField3);
if (textField3Type != null){
tags.setMainField2(textField3Type);
}
}
if (textField4 != null && textField4.length() > 0){
if (textField3 != null && textField3.length() > 0){
// If text 3 exists, put it in slot 2 formatted
tempString.append(" - ").append(textField4);
if (textField4Type != null){
List<MetadataType> tags3 = tags.getMainField1();
tags3.add(textField4Type);
tags.setMainField2(tags3);
}
} else {
// If text 3 does not exist, put it in slot 3 unformatted
tempString.append(textField4);
if (textField4Type != null){
tags.setMainField2(textField4Type);
}
}
}
if (tempString.toString().length() > 0){
show.setMainField2(tempString.toString());
}
show.setMetadataTags(tags);
return show;
}
private Show assembleThreeLineShowText(Show show){
MetadataTags tags = show.getMetadataTags();
if (textField1 != null && textField1.length() > 0) {
show.setMainField1(textField1);
if (textField1Type != null){
tags.setMainField1(textField1Type);
}
}
if (textField2 != null && textField2.length() > 0) {
show.setMainField2(textField2);
if (textField2Type != null){
tags.setMainField2(textField2Type);
}
}
StringBuilder tempString = new StringBuilder();
if (textField3 != null && textField3.length() > 0){
tempString.append(textField3);
if (textField3Type != null){
tags.setMainField2(textField3Type);
}
}
if (textField4 != null && textField4.length() > 0) {
if (textField3 != null && textField3.length() > 0) {
// If text 3 exists, put it in slot 3 formatted
tempString.append(" - ").append(textField4);
if (textField4Type != null){
List<MetadataType> tags4 = tags.getMainField3();
tags4.add(textField4Type);
tags.setMainField3(tags4);
}
} else {
// If text 3 does not exist, put it in slot 3 formatted
tempString.append(textField4);
if (textField4Type != null){
tags.setMainField3(textField4Type);
}
}
}
show.setMainField3(tempString.toString());
show.setMetadataTags(tags);
return show;
}
private Show assembleFourLineShowText(Show show){
MetadataTags tags = show.getMetadataTags();
if (textField1 != null && textField1.length() > 0) {
show.setMainField1(textField1);
if (textField1Type != null){
tags.setMainField1(textField1Type);
}
}
if (textField2 != null && textField2.length() > 0) {
show.setMainField2(textField2);
if (textField2Type != null){
tags.setMainField2(textField2Type);
}
}
if (textField3 != null && textField3.length() > 0) {
show.setMainField3(textField3);
if (textField3Type != null){
tags.setMainField3(textField3Type);
}
}
if (textField4 != null && textField4.length() > 0) {
show.setMainField4(textField4);
if (textField4Type != null){
tags.setMainField2(textField4Type);
}
}
show.setMetadataTags(tags);
return show;
}
// Extraction
private Show extractTextFromShow(Show show){
Show newShow = new Show();
newShow.setMainField1(show.getMainField1());
newShow.setMainField2(show.getMainField2());
newShow.setMainField3(show.getMainField3());
newShow.setMainField4(show.getMainField4());
return newShow;
}
private Show extractImageFromShow(Show show){
Show newShow = new Show();
newShow.setGraphic(show.getGraphic());
return newShow;
}
private Show setBlankTextFields(){
Show newShow = new Show();
newShow.setMainField1("");
newShow.setMainField2("");
newShow.setMainField3("");
newShow.setMainField4("");
newShow.setMediaTrack("");
return newShow;
}
private void updateCurrentScreenDataFromShow(Show show){
// set all of the show fields, make sure items are not null before setting in the show
}
// Helpers
private List<String> findNonNullTextFields(){
List<String> array = new ArrayList<>();
if (textField1.length() > 0) {
array.add(textField1);
}
if (textField2.length() > 0) {
array.add(textField2);
}
if (textField3.length() > 0) {
array.add(textField3);
}
if (textField4.length() > 0) {
array.add(textField4);
}
return array;
}
private List<MetadataType> findNonNullMetadataFields(){
List<MetadataType> array = new ArrayList<>();
if (textField1Type != null) {
array.add(textField1Type);
}
if (textField2Type != null) {
array.add(textField2Type);
}
if (textField3Type != null) {
array.add(textField3Type);
}
if (textField4Type != null) {
array.add(textField4Type);
}
return array;
}
private void getBlankArtwork(){
if (blankArtwork != null){
blankArtwork = new SdlArtwork();
blankArtwork.setType(FileType.GRAPHIC_PNG);
blankArtwork.setName("blankArtwork");
blankArtwork.setFileData(contentsOfResource(R.drawable.transparent));
}
}
private void getDisplayCapabilities() {
if (displayCapabilities != null) {
displayCapabilities = (DisplayCapabilities) internalInterface.getCapability(SystemCapabilityType.DISPLAY);
try {
Log.i(TAG, "DISPLAY CAPABILITIES: "+ displayCapabilities.serializeJSON().toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private int getNumberOfLines() {
if (displayCapabilities == null){
return 4;
}
List<TextField> textFields = displayCapabilities.getTextFields();
return textFields.size();
}
/**
* Helper method to take resource files and turn them into byte arrays
* @param resource Resource file id
* @return Resulting byte array
*/
private byte[] contentsOfResource(int resource) {
InputStream is = null;
try {
is = context.getResources().openRawResource(resource);
return contentsOfInputStream(is);
} catch (Resources.NotFoundException e) {
Log.w(TAG, "Can't read from resource", e);
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Helper method to take InputStream and turn it into byte array
* @param is valid InputStream
* @return Resulting byte array
*/
private byte[] contentsOfInputStream(InputStream is){
if(is == null){
return null;
}
try{
ByteArrayOutputStream os = new ByteArrayOutputStream();
final int bufferSize = 4096;
final byte[] buffer = new byte[bufferSize];
int available;
while ((available = is.read(buffer)) >= 0) {
os.write(buffer, 0, available);
}
return os.toByteArray();
} catch (IOException e){
Log.w(TAG, "Can't read from InputStream", e);
return null;
}
}
// Equality
}
|
package org.openbaton.nfvo.security.components;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.openbaton.catalogue.nfvo.ManagerCredentials;
import org.openbaton.catalogue.nfvo.ServiceMetadata;
import org.openbaton.catalogue.nfvo.VnfmManagerEndpoint;
import org.openbaton.exceptions.NotFoundException;
import org.openbaton.nfvo.repositories.ManagerCredentialsRepository;
import org.openbaton.nfvo.repositories.ServiceRepository;
import org.openbaton.nfvo.repositories.VnfmEndpointRepository;
import org.openbaton.nfvo.security.authentication.OAuth2AuthorizationServerConfig;
import org.openbaton.utils.key.KeyHelper;
import org.openbaton.vnfm.interfaces.register.VnfmRegister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import static org.openbaton.utils.rabbit.RabbitManager.createRabbitMqUser;
import static org.openbaton.utils.rabbit.RabbitManager.removeRabbitMqUser;
import static org.openbaton.utils.rabbit.RabbitManager.setRabbitMqUserPermissions;
//import java.util.Base64;
@Service
@ConfigurationProperties
public class ComponentManager implements org.openbaton.nfvo.security.interfaces.ComponentManager {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired private OAuth2AuthorizationServerConfig serverConfig;
// @Autowired private TokenStore tokenStore;
// @Autowired private DefaultTokenServices tokenServices;
@Autowired private Gson gson;
@Autowired private ServiceRepository serviceRepository;
@Autowired private ManagerCredentialsRepository managerCredentialsRepository;
@Autowired private VnfmRegister vnfmRegister;
@Value("${nfvo.security.service.token.validity:31556952}")
private int serviceTokenValidityDuration;
@Value("${nfvo.rabbit.brokerIp:localhost}")
private String brokerIp;
@Value("${nfvo.rabbit.managementPort:15672}")
private String managementPort;
@Value("${spring.rabbitmq.password:openbaton}")
private String rabbitPassword;
@Value("${spring.rabbitmq.username:admin}")
private String rabbitUsername;
@Value("${spring.rabbitmq.virtual-host:/}")
private String vhost;
@Autowired private VnfmEndpointRepository vnfmManagerEndpointRepository;
/*
* Service related operations
*/
@Override
public String registerService(byte[] body)
throws NotFoundException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
NoSuchAlgorithmException, NoSuchPaddingException {
ServiceMetadata service = null;
String unencryptedBody = null;
for (ServiceMetadata serviceMetadata : serviceRepository.findAll()) {
try {
unencryptedBody =
KeyHelper.decrypt(body, KeyHelper.restoreKey(serviceMetadata.getKeyValue()));
} catch (NoSuchPaddingException e) {
e.printStackTrace();
continue;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
continue;
} catch (InvalidKeyException e) {
e.printStackTrace();
continue;
} catch (BadPaddingException e) {
e.printStackTrace();
continue;
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
continue;
}
if (unencryptedBody == null)
throw new NotFoundException("Could not decrypt the body, did you enabled the service?");
service = serviceMetadata;
break;
}
if (service == null) {
log.error("Please create your Service first in order to get the super duper secret key");
throw new NotFoundException(
"No Service found. Please create your Service before registering it.");
}
JsonObject bodyJson = gson.fromJson(unencryptedBody, JsonObject.class);
String serviceName = bodyJson.getAsJsonPrimitive("name").getAsString();
String action = bodyJson.getAsJsonPrimitive("action").getAsString();
if (!service.getName().equals(serviceName)) {
log.error(
"The name of the found Service does not match to the requested name " + serviceName);
throw new NotFoundException(
"The name of the found Service does not match to the requested name " + serviceName);
}
if (action.toLowerCase().equals("register")) {
if (service.getToken() != null && !service.getToken().equals("")) {
if (service.getTokenExpirationDate() > (new Date()).getTime()) return service.getToken();
}
OAuth2AccessToken token = serverConfig.getNewServiceToken(serviceName);
service.setToken(
KeyHelper.encryptToString(token.getValue(), KeyHelper.restoreKey(service.getKeyValue())));
service.setTokenExpirationDate(token.getExpiration().getTime());
serviceRepository.save(service);
return service.getToken();
} else if (action.toLowerCase().equals("remove") || action.toLowerCase().equals("delete")) {
serviceRepository.delete(service);
log.info("Removed service " + serviceName);
return null;
} else {
log.error("Action " + action + " unknown!");
throw new RuntimeException("Action " + action + " unknown!");
}
}
@Override
public byte[] createService(String serviceName, String projectId)
throws NoSuchAlgorithmException, IOException {
for (ServiceMetadata serviceMetadata : serviceRepository.findAll()) {
if (serviceMetadata.getName().equals(serviceName)) {
log.debug("Service " + serviceName + " already exists.");
return serviceMetadata.getKeyValue();
}
}
ServiceMetadata serviceMetadata = new ServiceMetadata();
serviceMetadata.setName(serviceName);
serviceMetadata.setKeyValue(KeyHelper.genKey().getEncoded());
log.debug("Saving ServiceMetadata: " + serviceMetadata);
serviceRepository.save(serviceMetadata);
return serviceMetadata.getKeyValue();
}
@Override
public boolean isService(String tokenToCheck)
throws InvalidKeyException, BadPaddingException, NoSuchAlgorithmException,
IllegalBlockSizeException, NoSuchPaddingException {
for (ServiceMetadata serviceMetadata : serviceRepository.findAll()) {
if (serviceMetadata.getToken() != null && !serviceMetadata.getToken().equals("")) {
String encryptedServiceToken = serviceMetadata.getToken();
byte[] keyData = serviceMetadata.getKeyValue();
Key key = KeyHelper.restoreKey(keyData);
try {
if (KeyHelper.decrypt(encryptedServiceToken, key).equals(tokenToCheck)) return true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
return false;
}
@Override
public Iterable<ServiceMetadata> listServices() {
return serviceRepository.findAll();
}
@Override
public void removeService(String id) {
//TODO remove also associated toker
ServiceMetadata serviceMetadataToRemove = serviceRepository.findById(id);
log.debug("Found service: " + serviceMetadataToRemove);
if (serviceMetadataToRemove.getToken() != null)
serverConfig.tokenServices().revokeToken(serviceMetadataToRemove.getToken());
serviceRepository.delete(id);
}
/*
* Manager related operations
*/
public ManagerCredentials enableManager(byte[] message) {
return enableManager(new String(message));
}
/**
* Handles the registration requests of VNFMs and returns a ManagerCredential object from which
* the VNFMs can get the rabbitmq username and password.
*
* @param message
* @return
* @throws IOException
*/
@Override
public ManagerCredentials enableManager(String message) {
try {
// deserialize message
JsonObject body = gson.fromJson(message, JsonObject.class);
if (!body.has("action")) {
log.error("Could not process Json message. The 'action' property is missing.");
return null;
}
if (body.get("action").getAsString().toLowerCase().equals("register")) {
// register plugin or vnfm
if (!body.has("type")) {
log.error("Could not process Json message. The 'type' property is missing.");
return null;
}
String username = body.get("type").getAsString();
String password = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(16);
ManagerCredentials managerCredentials =
managerCredentialsRepository.findFirstByRabbitUsername(username);
VnfmManagerEndpoint endpoint;
if (managerCredentials != null) {
log.error("Manager already registered.");
return managerCredentials;
} else {
managerCredentials = new ManagerCredentials();
endpoint = gson.fromJson(body.get("vnfmManagerEndpoint"), VnfmManagerEndpoint.class);
}
// String regexOpenbaton = "(^nfvo)";
// String regexManager = "(^" + username + ")|(openbaton-exchange)";
// String regexBoth = regexOpenbaton + "|" + regexManager;
String configurePermissions = "(" + username + ")|(nfvo." + username + ".actions)";
String writePermissions =
"^amq\\.gen.*|amq\\.default$|("
+ username
+ ")|(vnfm.nfvo.actions)|(vnfm.nfvo.actions.reply)|(nfvo."
+ username
+ ".actions)|(openbaton-exchange)";
String readPermissions =
"(nfvo." + username + ".actions)|(" + username + ")|(openbaton-exchange)";
createRabbitMqUser(
rabbitUsername, rabbitPassword, brokerIp, managementPort, username, password, vhost);
try {
setRabbitMqUserPermissions(
rabbitUsername,
rabbitPassword,
brokerIp,
managementPort,
username,
vhost,
configurePermissions,
writePermissions,
readPermissions);
} catch (Exception e) {
try {
removeRabbitMqUser(rabbitUsername, rabbitPassword, brokerIp, managementPort, username);
} catch (Exception e2) {
log.error("Clean up failed. Could not remove RabbitMQ user " + username);
e2.printStackTrace();
}
throw e;
}
managerCredentials.setRabbitUsername(username);
managerCredentials.setRabbitPassword(password);
managerCredentials = managerCredentialsRepository.save(managerCredentials);
if (endpoint != null) vnfmManagerEndpointRepository.save(endpoint);
return managerCredentials;
} else if (body.get("action").getAsString().toLowerCase().equals("unregister")
|| body.get("action").getAsString().toLowerCase().equals("deregister")) {
if (!body.has("username")) {
log.error("Could not process Json message. The 'username' property is missing.");
return null;
}
if (!body.has("password")) {
log.error("Could not process Json message. The 'password' property is missing.");
return null;
}
String username = body.get("username").getAsString();
ManagerCredentials managerCredentials =
managerCredentialsRepository.findFirstByRabbitUsername(username);
if (managerCredentials == null) {
log.error("Did not find manager with name " + body.get("username"));
return null;
}
if (body.get("password").getAsString().equals(managerCredentials.getRabbitPassword())) {
managerCredentialsRepository.delete(managerCredentials);
// if message comes from a vnfm, remove the endpoint
if (body.has("vnfmManagerEndpoint"))
vnfmRegister.unregister(
gson.fromJson(body.get("vnfmManagerEndpoint"), VnfmManagerEndpoint.class));
removeRabbitMqUser(rabbitUsername, rabbitPassword, brokerIp, managementPort, username);
}
return null;
} else return null;
} catch (Exception e) {
log.error("Exception while enabling manager or plugin.");
e.printStackTrace();
return null;
}
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// 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 com.kyloth.serleena.sensors;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import com.kyloth.serleena.common.GeoPoint;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Concretizza ILocationManager.
*
* Fornisce al codice client la posizione dell'utente utilizzando il modulo
* GPS del dispositivo con il supporto delle API Android.
*
* @use Viene istanziato da SerleenaSensorManager e restituito al codice client dietro interfaccia.
* @field lastKnownLocation : GeoPoint Ultima posizione geografica nota dell'utente
* @field lastUpdate : long Istante di tempo, in UNIX time, a cui corrisponde l'ultimo dato di posizione noto
* @field observer : Map<ILocationObserver, Integer> Mappa gli Observer agli intervalli di notifica
* @field locationManager : LocationManager Gestore della posizione di Android
* @field singleUpdates : Set<ILocationObserver> Insieme degli Observer la cui notifica deve avvenire solamente una volta
* @field currentInterval : int Intervallo con cui al momento viene richiesto l'aggiornamento sulla posizione alle API Android
* @author Filippo Sestini <sestini.filippo@gmail.com>
* @version 1.0.0
*/
class SerleenaLocationManager implements ILocationManager,
LocationListener {
public static final long LOCATION_EXPIRATION_TIME = 30;
private GeoPoint lastKnownLocation;
private long lastUpdate;
private Map<ILocationObserver, Integer> observers;
private android.location.LocationManager locationManager;
private Set<ILocationObserver> singleUpdates;
private int currentInterval;
public SerleenaLocationManager(LocationManager locationManager) {
if (locationManager == null)
throw new IllegalArgumentException("Illegal null location manager");
this.observers = new HashMap<ILocationObserver, Integer>();
this.singleUpdates = new HashSet<ILocationObserver>();
this.currentInterval = Integer.MAX_VALUE;
this.locationManager = locationManager;
}
@Override
public synchronized void attachObserver(final ILocationObserver observer,
int interval)
throws IllegalArgumentException {
if (observer == null)
throw new IllegalArgumentException("Illegal null observer");
if (interval <= 0)
throw new IllegalArgumentException("Illegal interval");
observers.put(observer, interval);
adjustGpsUpdateRate();
}
@Override
public synchronized void detachObserver(ILocationObserver observer)
throws IllegalArgumentException {
if (observer == null)
throw new IllegalArgumentException("Illegal null observer");
if (observers.containsKey(observer)) {
observers.remove(observer);
adjustGpsUpdateRate();
}
}
@Override
public synchronized void getSingleUpdate(final ILocationObserver observer,
int timeout)
throws IllegalArgumentException {
if (observer == null)
throw new IllegalArgumentException("Illegal null observer");
if (timeout <= 0)
throw new IllegalArgumentException("Illegal timeout");
if (observers.size() > 0 && ((System.currentTimeMillis() / 1000L) -
lastUpdate) < LOCATION_EXPIRATION_TIME)
notifyObserver(observer);
else {
final LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
singleUpdates.remove(observer);
lastKnownLocation = new GeoPoint(location.getLatitude(),
location.getLongitude());
lastUpdate = System.currentTimeMillis() / 1000L;
notifyObserver(observer);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) { }
@Override
public void onProviderEnabled(String s) { }
@Override
public void onProviderDisabled(String s) { }
};
singleUpdates.add(observer);
String provider = android.location.LocationManager.GPS_PROVIDER;
locationManager.requestSingleUpdate(provider, listener, null);
final Handler timeoutHandler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
if (singleUpdates.contains(observer)) {
locationManager.removeUpdates(listener);
notifyObserver(observer);
singleUpdates.remove(observer);
}
}
};
timeoutHandler.postDelayed(runnable, timeout * 1000);
}
}
@Override
public synchronized void notifyObserver(ILocationObserver observer)
throws IllegalArgumentException {
if (observer == null)
throw new IllegalArgumentException("Illegal null observer");
observer.onLocationUpdate(lastKnownLocation);
}
@Override
public synchronized void onLocationChanged(Location location) {
lastKnownLocation = new GeoPoint(location.getLatitude(),
location.getLongitude());
lastUpdate = System.currentTimeMillis() / 1000L;
for (ILocationObserver observer : observers.keySet())
notifyObserver(observer);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) { }
@Override
public void onProviderEnabled(String s) { }
@Override
public void onProviderDisabled(String s) { }
/**
* Regola la frequenza delle richieste di aggiornamento sulla posizione
* utente in base agli observer correntemente registrati e le loro
* esigenze in termini di tempo.
*/
private synchronized void adjustGpsUpdateRate() {
if (observers.size() == 0) {
currentInterval = Integer.MAX_VALUE;
locationManager.removeUpdates(this);
} else {
int minInterval = Integer.MAX_VALUE;
for (int interval : observers.values())
if (interval < minInterval)
minInterval = interval;
locationManager.removeUpdates(this);
locationManager.requestLocationUpdates(LocationManager
.GPS_PROVIDER, minInterval * 1000, 10, this);
currentInterval = minInterval;
}
}
}
|
// This file is part of Serleena.
// Nicola Mometto, Filippo Sestini, Tobia Tesan, Sebastiano Valle.
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// 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 com.kyloth.serleena.view.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.view.KeyEvent;
import android.widget.TextView;
import com.kyloth.serleena.R;
import com.kyloth.serleena.presentation.IContactsPresenter;
import com.kyloth.serleena.presentation.IContactsView;
public class ContactsFragment extends Fragment implements IContactsView {
/**
* Presenter collegato a un ContactsFragment
*/
private IContactsPresenter presenter;
/**
* Metodo che collega un ContactsFragment al proprio Presenter.
*/
@Override
public void attachPresenter(IContactsPresenter presenter) throws IllegalArgumentException {
this.presenter = presenter;
}
/**
* Metodo che richiede a un ContactsFragment di visualizzare un contatto
*/
@Override
public void displayContact(String name, String contact) {
TextView textName = (TextView) getActivity().findViewById(R.id.contact_name);
TextView textValue = (TextView) getActivity().findViewById(R.id.contact_value);
textName.setText(name);
textValue.setText(contact);
}
/**
* Metodo che rimuove il contatto visualizzato
*/
@Override
public void clearView() {
TextView textName = (TextView) getActivity().findViewById(R.id.contact_name);
TextView textValue = (TextView) getActivity().findViewById(R.id.contact_value);
textValue.setText("NESSUN CONTATTO");
textName.setText("DA VISUALIZZARE");
}
/**
* Metodo che richiede la visualizzazione del contatto successivo alla pressione del pulsante
* centrale.
*
* @param keyCode tasto premuto
* @param event KeyEvent avvenuto
*/
public void keyDown(int keyCode, KeyEvent event) {
presenter.nextContact();
}
/**
* Metodo invocato quando il Fragment viene visualizzato.
*
*/
@Override
public void onResume() {
super.onResume();
presenter.resume();
}
/**
* Metodo invocato quando il Fragment smette di essere visualizzato.
*
*/
@Override
public void onPause() {
super.onPause();
presenter.pause();
}
}
|
package io.loli.sc.server.redirect.socket;
import io.loli.sc.server.redirect.bean.Pair;
import io.loli.sc.server.redirect.config.Config;
import io.loli.sc.server.redirect.dao.ImageDao;
import io.loli.sc.server.redirect.dao.LogDao;
import io.loli.sc.server.redirect.file.Cache;
import io.loli.sc.server.redirect.file.FileCache;
import io.loli.storage.redirect.RedirectHandler;
import io.loli.storage.redirect.RequestAuthFilter;
import io.loli.util.concurrent.TaskExecutor;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.util.Header;
import org.glassfish.grizzly.http.util.HttpStatus;
public class RedirectFilter implements RequestAuthFilter {
private static ImageDao imageDao = new ImageDao();
private static LogDao logDao = new LogDao();
private static final Cache cache = new FileCache();
private static final Logger logger = LogManager.getLogger(RedirectHandler.class);
private static final TaskExecutor executor = new TaskExecutor(30);
private void send404(Response response) {
response.setStatus(HttpStatus.NOT_FOUND_404);
response.setContentType("image/png");
try (InputStream is = this.getClass().getResourceAsStream("/404.png");
OutputStream os = response.getOutputStream();) {
byte[] b = new byte[1024];
while (is.read(b) >= 0) {
os.write(b);
}
} catch (IOException e) {
logger.error(e);
}
}
/*
* (excludeurlexclude)
*/
public void filter(final Request request, final Response response) {
try {
String code = request.getRequestURI();
logger.info("url:" + code);
if (code.startsWith("/")) {
code = code.substring(1);
}
Pair<String, String> result = imageDao.findUrlByCode(code);
String url = result.getKey();
if (null == url || "".equals(url.trim())) {
logger.warn("url");
send404(response);
} else {
logger.info("url:" + url);
String referer = request.getHeader(Header.Referer);
String ip = request.getRemoteAddr();
if (ip != null && ip.equals("127.0.0.1")) {
ip = request.getHeader("X-Real-IP");
}
final String fip = ip;
String ua = request.getHeader(Header.UserAgent);
executor.execute(() -> logDao.save(url, ua, referer, fip, new Date()));
InputStream input = null;
try {
OutputStream output = response.getOutputStream();
long total = 0;
if (Config.useCache) {
byte[] bytes = cache.getBytes(url);
total = bytes.length;
input = new BufferedInputStream(new ByteArrayInputStream(bytes));
} else {
Pair<Long, InputStream> pair = cache.get(url);
input = pair.getValue();
total = pair.getKey();
}
if ((!"".equals(result.getValue())) && null != result.getValue()) {
response.setContentType(result.getValue());
}
response.setHeader("Cache-Control", "max-age=15552000");
if (total != 0) {
response.setContentLengthLong(total);
}
byte[] buffer = new byte[2048];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} catch (Exception e) {
send404(response);
} finally {
if (input != null) {
input.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
send404(response);
}
}
}
|
package com.digi.xbee.api.packet.common;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.digi.xbee.api.models.ATStringCommands;
import com.digi.xbee.api.packet.XBeeAPIPacket;
import com.digi.xbee.api.packet.APIFrameType;
import com.digi.xbee.api.utils.HexUtils;
/**
* This class represents an AT Command XBee packet. Packet is built
* using the parameters of the constructor or providing a valid API payload.
*
* <p>Used to query or set module parameters on the local device. This API
* command applies changes after executing the command. (Changes made to
* module parameters take effect once changes are applied.).</p>
*
* <p>Command response is received as an {@code ATCommandResponsePacket}.</p>
*
* @see ATCommandResponsePacket
* @see XBeeAPIPacket
*/
public class ATCommandPacket extends XBeeAPIPacket {
// Constants.
private static final int MIN_API_PAYLOAD_LENGTH = 4; // 1 (Frame type) + 1 (frame ID) + 2 (AT command)
// Variables
private final String command;
private byte[] parameter;
private Logger logger;
public static ATCommandPacket createPacket(byte[] payload) {
if (payload == null)
throw new NullPointerException("AT Command packet payload cannot be null.");
// 1 (Frame type) + 1 (frame ID) + 2 (AT command)
if (payload.length < MIN_API_PAYLOAD_LENGTH)
throw new IllegalArgumentException("Incomplete AT Command packet.");
if ((payload[0] & 0xFF) != APIFrameType.AT_COMMAND.getValue())
throw new IllegalArgumentException("Payload is not an AT Command packet.");
// payload[0] is the frame type.
int index = 1;
// Frame ID byte.
int frameID = payload[index] & 0xFF;
index = index + 1;
// 2 bytes of AT command, starting at 2nd byte.
String command = new String(new byte[]{payload[index], payload[index + 1]});
index = index + 2;
// Get data.
byte[] parameterData = null;
if (index < payload.length)
parameterData = Arrays.copyOfRange(payload, index, payload.length);
return new ATCommandPacket(frameID, command, parameterData);
}
public ATCommandPacket(int frameID, String command, String parameter) {
this(frameID, command, parameter == null ? null : parameter.getBytes());
}
public ATCommandPacket(int frameID, String command, byte[] parameter) {
super(APIFrameType.AT_COMMAND);
if (command == null)
throw new NullPointerException("Command cannot be null.");
if (frameID < 0 || frameID > 255)
throw new IllegalArgumentException("Frame ID must be between 0 and 255.");
this.frameID = frameID;
this.command = command;
this.parameter = parameter;
this.logger = LoggerFactory.getLogger(ATCommandPacket.class);
}
/*
* (non-Javadoc)
* @see com.digi.xbee.api.packet.XBeeAPIPacket#getAPIData()
*/
@Override
public byte[] getAPIData() {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
os.write(frameID);
os.write(command.getBytes());
if (parameter != null)
os.write(parameter);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return os.toByteArray();
}
/*
* (non-Javadoc)
* @see com.digi.xbee.api.packet.XBeeAPIPacket#needsAPIFrameID()
*/
@Override
public boolean needsAPIFrameID() {
return true;
}
/**
* Retrieves the AT command.
*
* @return The AT command.
*/
public String getCommand() {
return command;
}
/**
* Sets the AT command parameter as String.
*
* @param parameter The AT command parameter as String.
*/
public void setParameter(String parameter) {
if (parameter == null)
this.parameter = null;
else
this.parameter = parameter.getBytes();
}
/**
* Sets the AT command parameter.
*
* @param parameter The AT command parameter.
*/
public void setParameter(byte[] parameter) {
this.parameter = parameter;
}
/**
* Retrieves the AT command parameter.
*
* @return The AT command parameter.
*/
public byte[] getParameter() {
return parameter;
}
/**
* Retrieves the AT command parameter as String.
*
* @return The AT command parameter as String, {@code null} if no parameter
* is set.
*/
public String getParameterAsString() {
if (parameter == null)
return null;
return new String(parameter);
}
/*
* (non-Javadoc)
* @see com.digi.xbee.api.packet.XBeeAPIPacket#getAPIPacketParameters()
*/
@Override
public LinkedHashMap<String, String> getAPIPacketParameters() {
LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
parameters.put("Frame ID", HexUtils.prettyHexString(HexUtils.integerToHexString(frameID, 1)) + " (" + frameID + ")");
parameters.put("AT Command", HexUtils.prettyHexString(HexUtils.byteArrayToHexString(command.getBytes())) + " (" + command + ")");
if (parameter != null) {
if (ATStringCommands.get(command) != null)
parameters.put("Parameter", HexUtils.prettyHexString(HexUtils.byteArrayToHexString(parameter)) + " (" + new String(parameter) + ")");
else
parameters.put("Parameter", HexUtils.prettyHexString(HexUtils.byteArrayToHexString(parameter)));
}
return parameters;
}
}
|
package com.example.whuassist.schedule;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Fragment;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.whuassist.MainActivity;
import com.example.whuassist.MyPagerAdapter;
import com.example.whuassist.R;
import com.example.whuassist.WhuHttpUtil;
import com.example.whuassist.WhuUtil;
import com.example.whuassist.db.ScheduleTableHelper;
import com.example.whuassist.db.ScoreTableHelper;
import com.example.whuassist.score.Scoremodel;
public class ScheduleFragment extends Fragment {
List<Fragment> fraglist=new ArrayList<Fragment>();
ViewPager mdayspager;
MyPagerAdapter adapter;
ScheduleTableHelper sdbhelper;
ProgressBar prgbar;
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
sdbhelper=new ScheduleTableHelper(getActivity(),"WHU"+MainActivity.Account+"schedule.db",null,1);
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.schedule_fragment, container, false);
mdayspager=(ViewPager) v.findViewById(R.id.id_dayspager);
prgbar=(ProgressBar) v.findViewById(R.id.schedule_progressbar);
adapter=new MyPagerAdapter(getChildFragmentManager()) {
@Override
public int getCount() {
// TODO Auto-generated method stub
return 25;
}
@Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
while(position>=fraglist.size()){
fraglist.add(new DayTimeFragment(fraglist.size()));
}
return fraglist.get(position);
}
};
mdayspager.setAdapter(adapter);
mdayspager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
if(WhuUtil.courseSchedule.size()==0){
queryScheduleData();
}
return v;
}
public void queryScheduleData(){
try {
queryScheduleFromdb();
if(WhuUtil.courseScore.size()==0){
queryScheduleFromServer();
}
} catch (Exception e) {
// TODO: handle exception
queryScheduleFromServer();
}
}
public void queryScheduleFromdb(){
SQLiteDatabase sdb=sdbhelper.getWritableDatabase();
Cursor cursor=sdb.rawQuery("select * from Schedule", null);
if(cursor.moveToFirst()){
do {
String id=cursor.getString(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String timetxt=cursor.getString(cursor.getColumnIndex("timetxt"));
WhuUtil.courseSchedule.add(WhuUtil.parse2Schedulemodel(id, name, timetxt));
} while (cursor.moveToNext());
}
}
public void queryScheduleFromServer(){
new DownloadScheduleTask().execute();
}
class DownloadScheduleTask extends AsyncTask<Void, Integer, Boolean>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
prgbar.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String rtxt=WhuHttpUtil.getInstance().reqwebinfo(
"http://210.42.121.241//servlet/Svlt_QueryStuLsn?action=normalLsn", null);
WhuUtil.courseSchedule.clear();
WhuUtil.scheduleParse(rtxt);
return true;
} catch (Exception e) {
// TODO: handle exception
return false;
}
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result){
mdayspager.setCurrentItem(WhuUtil.weeknum-1);
adapter.notifyDataSetChanged();
}else{
Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
}
saveSchedule2db();
prgbar.setVisibility(View.GONE);
}
}
public void saveSchedule2db(){
SQLiteDatabase sdb=sdbhelper.getWritableDatabase();
sdb.beginTransaction();
sdb.execSQL("delete from Schedule");
for(Schedulemodel cschedule:WhuUtil.courseSchedule){
sdb.execSQL("insert into Schedule(id,name,time) values(?,?,?)",
new String[]{cschedule.id,cschedule.name,cschedule.timetxt});
}
sdb.setTransactionSuccessful();
sdb.endTransaction();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.