answer
stringlengths
17
10.2M
package org.realityforge.arez; import java.util.ArrayList; import java.util.HashSet; import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.TestOnly; import org.realityforge.arez.spy.ComputeCompletedEvent; import org.realityforge.arez.spy.ComputeStartedEvent; import org.realityforge.arez.spy.ObserverDisposedEvent; import org.realityforge.arez.spy.ReactionCompletedEvent; import org.realityforge.arez.spy.ReactionStartedEvent; /** * A node within Arez that is notified of changes in 0 or more Observables. */ public final class Observer extends Node { /** * The reference to the ComputedValue if this observer is a derivation. */ @Nullable private final ComputedValue<?> _computedValue; /** * Hook action called when the Observer changes from the INACTIVE state to any other state. */ @Nullable private Procedure _onActivate; /** * Hook action called when the Observer changes to the INACTIVE state to any other state. */ @Nullable private Procedure _onDeactivate; /** * Hook action called when the Observer changes from the UP_TO_DATE state to STALE or POSSIBLY_STALE. */ @Nullable private Procedure _onStale; /** * The stalest state of the associated observables that are also derivations. */ @Nonnull private ObserverState _state = ObserverState.INACTIVE; /** * The observables that this observer receives notifications from. * These are the dependencies within the dependency graph and will * typically correspond to the observables that were accessed in last * transaction that this observer was tracking. * * This list should contain no duplicates. */ @Nonnull private ArrayList<Observable> _dependencies = new ArrayList<>(); /** * Flag indicating whether this observer has been scheduled. * Should always be false unless _reaction is non-null. */ private boolean _scheduled; /** * The transaction mode in which the observer executes. */ @Nonnull private final TransactionMode _mode; /** * The code responsible for responding to changes if any. */ @Nullable private final Reaction _reaction; @Nullable private final Observable _derivedValue; /** * Flag set to true after Observer has been disposed. */ private boolean _disposed; Observer( @Nonnull final ComputedValue<?> computedValue ) { this( computedValue.getContext(), ArezConfig.enableNames() ? computedValue.getName() : null, computedValue, TransactionMode.READ_WRITE_OWNED, o -> computedValue.compute() ); setOnStale( () -> getDerivedValue().reportPossiblyChanged() ); } Observer( @Nonnull final ArezContext context, @Nullable final String name, @Nonnull final TransactionMode mode, @Nullable final Reaction reaction ) { this( context, name, null, mode, reaction ); } Observer( @Nonnull final ArezContext context, @Nullable final String name, @Nullable final ComputedValue<?> computedValue, @Nonnull final TransactionMode mode, @Nullable final Reaction reaction ) { super( context, name ); if ( TransactionMode.READ_WRITE_OWNED == mode ) { Guards.invariant( () -> null != computedValue, () -> String.format( "Attempted to construct an observer named '%s' with READ_WRITE_OWNED " + "transaction mode but no ComputedValue.", getName() ) ); assert null != computedValue; assert !ArezConfig.enableNames() || computedValue.getName().equals( name ); } else if ( null != computedValue ) { Guards.fail( () -> String.format( "Attempted to construct an observer named '%s' with %s " + "transaction mode and a ComputedValue.", getName(), mode ) ); } _computedValue = computedValue; _mode = Objects.requireNonNull( mode ); _reaction = reaction; if ( TransactionMode.READ_WRITE_OWNED == mode ) { _derivedValue = new Observable( context, name, this ); } else { _derivedValue = null; } } @Nonnull Observable getDerivedValue() { Guards.invariant( this::isLive, () -> String.format( "Attempted to invoke getDerivedValue on disposed observer named '%s'.", getName() ) ); Guards.invariant( this::isDerivation, () -> String.format( "Attempted to invoke getDerivedValue on observer named " + "'%s' when is not a computed observer.", getName() ) ); assert null != _derivedValue; return _derivedValue; } boolean isDerivation() { /* * We do not use "null != _derivedValue" as it is called from constructor of observable * prior to assigning it to _derivedValue. */ return TransactionMode.READ_WRITE_OWNED == getMode(); } /** * Make the Observer INACTIVE and release any resources associated with observer. * The applications should NOT interact with the Observer after it has been disposed. */ @Override public void dispose() { if ( !_disposed ) { getContext().safeProcedure( ArezConfig.enableNames() ? getName() : null, TransactionMode.READ_WRITE, this, () -> getContext().getTransaction().markTrackerAsDisposed() ); if ( willPropagateSpyEvents() && !isDerivation() ) { reportSpyEvent( new ObserverDisposedEvent( this ) ); } } } void setDisposed( final boolean disposed ) { _disposed = disposed; } /** * {@inheritDoc} */ @Override public boolean isDisposed() { return _disposed; } /** * Return true before dispose() method has been invoked. * * @return true if observer has not been disposed. */ boolean isLive() { return !isDisposed(); } /** * Return the state of the observer. * * @return the state of the observer. */ @Nonnull ObserverState getState() { return _state; } /** * Return the transaction mode in which the observer executes. * * @return the transaction mode in which the observer executes. */ @Nonnull TransactionMode getMode() { return _mode; } /** * Return the reaction. * * @return the reaction. */ @Nullable Reaction getReaction() { return _reaction; } /** * Return true if Observer has an associated reaction. * * @return true if Observer has an associated reaction. */ boolean hasReaction() { return null != _reaction; } /** * Return true if the observer is active. * Being "active" means that the state of the observer is not {@link ObserverState#INACTIVE}. * * <p>An inactive observer has no dependencies and depending on the type of observer may * have other consequences. i.e. An inactive observer will never be scheduled even if it has a * reaction.</p> * * @return true if the Observer is active. */ boolean isActive() { return ObserverState.INACTIVE != getState(); } /** * Return true if the observer is not active. * The inverse of {@link #isActive()} * * @return true if the Observer is inactive. */ boolean isInactive() { return !isActive(); } /** * Set the state of the observer. * Call the hook actions for relevant state change. * * @param state the new state of the observer. */ void setState( @Nonnull final ObserverState state ) { Guards.invariant( () -> getContext().isTransactionActive(), () -> String.format( "Attempt to invoke setState on observer named '%s' when there is no active transaction.", getName() ) ); invariantState(); if ( !state.equals( _state ) ) { final ObserverState originalState = _state; _state = state; if ( ObserverState.UP_TO_DATE == originalState && ( ObserverState.STALE == state || ObserverState.POSSIBLY_STALE == state ) ) { runHook( getOnStale(), ObserverError.ON_STALE_ERROR ); if ( hasReaction() ) { schedule(); } } else if ( ObserverState.INACTIVE == _state ) { runHook( getOnDeactivate(), ObserverError.ON_DEACTIVATE_ERROR ); clearDependencies(); } else if ( ObserverState.INACTIVE == originalState ) { Guards.invariant( this::isLive, () -> String.format( "Attempted to activate disposed observer named '%s'.", getName() ) ); runHook( getOnActivate(), ObserverError.ON_ACTIVATE_ERROR ); } invariantState(); } } /** * Run the supplied hook if non null. * * @param hook the hook to run. */ void runHook( @Nullable final Procedure hook, @Nonnull final ObserverError error ) { if ( null != hook ) { try { hook.call(); } catch ( final Throwable t ) { getContext().reportObserverError( this, error, t ); } } } /** * Set the onActivate hook. * * @param onActivate the hook. */ void setOnActivate( @Nullable final Procedure onActivate ) { _onActivate = onActivate; } /** * Return the onActivate hook. * * @return the onActivate hook. */ @Nullable Procedure getOnActivate() { return _onActivate; } /** * Set the onDeactivate hook. * * @param onDeactivate the hook. */ void setOnDeactivate( @Nullable final Procedure onDeactivate ) { _onDeactivate = onDeactivate; } /** * Return the onDeactivate hook. * * @return the onDeactivate hook. */ @Nullable Procedure getOnDeactivate() { return _onDeactivate; } /** * Set the onStale hook. * * @param onStale the hook. */ void setOnStale( @Nullable final Procedure onStale ) { _onStale = onStale; } /** * Return the onStale hook. * * @return the onStale hook. */ @Nullable Procedure getOnStale() { return _onStale; } /** * Remove all dependencies, removing this observer from all dependencies in the process. */ void clearDependencies() { getDependencies().forEach( dependency -> dependency.removeObserver( this ) ); getDependencies().clear(); } /** * Return true if this observer has a pending reaction. * * @return true if this observer has a pending reaction. */ boolean isScheduled() { return _scheduled; } /** * Clear the scheduled flag. This is called when the observer's reaction is executed so it can be scheduled again. */ void clearScheduledFlag() { _scheduled = false; } /** * Schedule this observer if it does not already have a reaction pending. * * This method should not be invoked unless {@link #hasReaction()} returns true. */ void schedule() { if ( isLive() ) { Guards.invariant( this::hasReaction, () -> String.format( "Observer named '%s' has no reaction but an attempt has been made to schedule observer.", getName() ) ); Guards.invariant( this::isActive, () -> String.format( "Observer named '%s' is not active but an attempt has been made to schedule observer.", getName() ) ); if ( !_scheduled ) { _scheduled = true; getContext().scheduleReaction( this ); } } } /** * Run the reaction in a transaction with the name and mode defined * by the observer. If the reaction throws an exception, the exception is reported * to the context global ObserverErrorHandlers */ void invokeReaction() { if ( isLive() ) { clearScheduledFlag(); final String name = ArezConfig.enableNames() ? getName() : null; final TransactionMode mode = getMode(); final Reaction reaction = getReaction(); Guards.invariant( () -> null != reaction, () -> String.format( "invokeReaction called on observer named '%s' but observer has no associated reaction.", name ) ); assert null != reaction; final long start; if ( willPropagateSpyEvents() ) { start = System.currentTimeMillis(); if ( isDerivation() ) { reportSpyEvent( new ComputeStartedEvent( getComputedValue() ) ); } else { reportSpyEvent( new ReactionStartedEvent( this ) ); } } else { start = 0; } try { // ComputedValues may have calculated their values and thus be up to date so no need to recalculate. if ( ObserverState.UP_TO_DATE != getState() ) { getContext().procedure( name, mode, this, () -> reaction.react( this ) ); } } catch ( final Throwable t ) { getContext().reportObserverError( this, ObserverError.REACTION_ERROR, t ); } if ( willPropagateSpyEvents() ) { final long duration = System.currentTimeMillis() - start; if ( isDerivation() ) { reportSpyEvent( new ComputeCompletedEvent( getComputedValue(), duration ) ); } else { reportSpyEvent( new ReactionCompletedEvent( this, duration ) ); } } } } /** * Utility to mark all dependencies least stale observer as up to date. * Used when the Observer is determined to be up todate. */ void markDependenciesLeastStaleObserverAsUpToDate() { for ( final Observable dependency : getDependencies() ) { dependency.setLeastStaleObserverState( ObserverState.UP_TO_DATE ); } } /** * Determine if any dependency of the Observer has actually changed. * If the state is POSSIBLY_STALE then recalculate any ComputedValue dependencies. * If any ComputedValue dependencies actually changed then the STALE state will * be propagated. * * <p>By iterating over the dependencies in the same order that they were reported and * stopping on the first change, all the recalculations are only called for ComputedValues * that will be tracked by derivation. That is because we assume that if the first N * dependencies of the derivation doesn't change then the derivation should run the same way * up until accessing N-th dependency.</p> * * @return true if the Observer should be recomputed. */ boolean shouldCompute() { switch ( getState() ) { case UP_TO_DATE: return false; case INACTIVE: case STALE: return true; case POSSIBLY_STALE: { for ( final Observable observable : getDependencies() ) { if ( observable.hasOwner() ) { final Observer owner = observable.getOwner(); final ComputedValue computedValue = owner.getComputedValue(); computedValue.get(); // Call to get() will update this state if ComputedValue changed if ( ObserverState.STALE == getState() ) { return true; } } } } } /* * This results in POSSIBLY_STALE returning to UP_TO_DATE */ markDependenciesLeastStaleObserverAsUpToDate(); return false; } /** * Return the dependencies. * * @return the dependencies. */ @Nonnull ArrayList<Observable> getDependencies() { return _dependencies; } /** * Replace the current set of dependencies with supplied dependencies. * This should be the only mechanism via which the dependencies are updated. * * @param dependencies the new set of dependencies. */ void replaceDependencies( @Nonnull final ArrayList<Observable> dependencies ) { invariantDependenciesUnique( "Pre replaceDependencies" ); _dependencies = Objects.requireNonNull( dependencies ); invariantDependenciesUnique( "Post replaceDependencies" ); invariantDependenciesBackLink( "Post replaceDependencies" ); invariantDependenciesNotDisposed(); } /** * Ensure the dependencies list contain no duplicates. * Should be optimized away if invariant checking is disabled. * * @param context some useful debugging context used in invariant checks. */ void invariantDependenciesUnique( @Nonnull final String context ) { // This invariant check should not be needed but this guarantees the (GWT) optimizer removes this code if ( ArezConfig.checkInvariants() ) { Guards.invariant( () -> getDependencies().size() == new HashSet<>( getDependencies() ).size(), () -> String.format( "%s: The set of dependencies in observer named '%s' is not unique. Current list: '%s'.", context, getName(), getDependencies().stream().map( Node::getName ).collect( Collectors.toList() ).toString() ) ); } } /** * Ensure all dependencies contain this observer in the list of observers. * Should be optimized away if invariant checking is disabled. * * @param context some useful debugging context used in invariant checks. */ void invariantDependenciesBackLink( @Nonnull final String context ) { // This invariant check should not be needed but this guarantees the (GWT) optimizer removes this code if ( ArezConfig.checkInvariants() ) { getDependencies().forEach( observable -> Guards.invariant( () -> observable.getObservers().contains( this ), () -> String.format( "%s: Observer named '%s' has dependency observable named '%s' which does not contain the observer in the list of observers.", context, getName(), observable.getName() ) ) ); invariantDerivationState(); } } /** * Ensure all dependencies are not disposed. */ void invariantDependenciesNotDisposed() { // This invariant check should not be needed but this guarantees the (GWT) optimizer removes this code if ( ArezConfig.checkInvariants() ) { getDependencies().forEach( observable -> Guards.invariant( () -> !observable.isDisposed(), () -> String.format( "Observer named '%s' has dependency observable named '%s' which is disposed.", getName(), observable.getName() ) ) ); invariantDerivationState(); } } /** * Ensure that state field and other fields of the Observer are consistent. */ void invariantState() { if ( isInactive() ) { Guards.invariant( () -> getDependencies().isEmpty(), () -> String.format( "Observer named '%s' is inactive but still has dependencies: %s.", getName(), getDependencies().stream(). map( Node::getName ). collect( Collectors.toList() ) ) ); } if ( isDerivation() && isLive() ) { Guards.invariant( () -> Objects.equals( getDerivedValue().hasOwner() ? getDerivedValue().getOwner() : null, this ), () -> String.format( "Observer named '%s' has a derived value that does not link back to observer.", getName() ) ); } } void invariantDerivationState() { if ( isDerivation() && isActive() && !isDisposed() ) { Guards.invariant( () -> !getDerivedValue().getObservers().isEmpty() || Objects.equals( getContext().getTransaction().getTracker(), this ), () -> String.format( "Observer named '%s' is a derivation and active but the derived " + "value has no observers.", getName() ) ); } } /** * Return the ComputedValue for Observer. * This should not be called if observer is not a derivation and will generate an invariant failure * if invariants are enabled. * * @return the associated ComputedValue. */ @Nonnull ComputedValue<?> getComputedValue() { Guards.invariant( this::isLive, () -> String.format( "Attempted to invoke getComputedValue on disposed observer named '%s'.", getName() ) ); Guards.invariant( this::isDerivation, () -> String.format( "Attempted to invoke getComputedValue on observer named '%s' when is not a computed observer.", getName() ) ); assert null != _computedValue; return _computedValue; } @TestOnly void markAsScheduled() { _scheduled = true; } }
package tech.tablesaw.api; import com.google.common.base.Preconditions; import it.unimi.dsi.fastutil.doubles.DoubleArrayList; import it.unimi.dsi.fastutil.doubles.DoubleArrays; import it.unimi.dsi.fastutil.doubles.DoubleComparator; import it.unimi.dsi.fastutil.doubles.DoubleIterator; import it.unimi.dsi.fastutil.doubles.DoubleListIterator; import it.unimi.dsi.fastutil.doubles.DoubleOpenHashSet; import it.unimi.dsi.fastutil.doubles.DoubleSet; import tech.tablesaw.columns.Column; import tech.tablesaw.columns.StringParser; import tech.tablesaw.columns.numbers.DoubleColumnType; import tech.tablesaw.columns.numbers.FloatColumnType; import tech.tablesaw.columns.numbers.NumberFillers; import tech.tablesaw.columns.numbers.fillers.DoubleRangeIterable; import tech.tablesaw.selection.Selection; import java.nio.ByteBuffer; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.function.DoubleConsumer; import java.util.function.DoublePredicate; import java.util.function.DoubleSupplier; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.ToDoubleFunction; public class DoubleColumn extends NumberColumn<Double> implements NumberFillers<DoubleColumn> { private static final ColumnType COLUMN_TYPE = ColumnType.DOUBLE; /** * Compares two doubles, such that a sort based on this comparator would sort in descending order */ private final DoubleComparator descendingComparator = (o2, o1) -> (Double.compare(o1, o2)); private final DoubleArrayList data; protected DoubleColumn(final String name, final DoubleArrayList data) { super(COLUMN_TYPE, name, data); this.data = data; } public static DoubleColumn create(final String name, final double[] arr) { return new DoubleColumn(name, new DoubleArrayList(arr)); } public static DoubleColumn create(final String name) { return new DoubleColumn(name, new DoubleArrayList()); } public static DoubleColumn create(final String name, final float[] arr) { final double[] doubles = new double[arr.length]; for (int i = 0; i < arr.length; i++) { doubles[i] = arr[i]; } return new DoubleColumn(name, new DoubleArrayList(doubles)); } public static DoubleColumn create(final String name, final int[] arr) { final double[] doubles = new double[arr.length]; for (int i = 0; i < arr.length; i++) { doubles[i] = arr[i]; } return new DoubleColumn(name, new DoubleArrayList(doubles)); } public static DoubleColumn create(final String name, final long[] arr) { final double[] doubles = new double[arr.length]; for (int i = 0; i < arr.length; i++) { doubles[i] = arr[i]; } return new DoubleColumn(name, new DoubleArrayList(doubles)); } public static DoubleColumn create(final String name, final List<Number> numberList) { // TODO This should be pushed down to the dataWrappers final double[] doubles = new double[numberList.size()]; for (int i = 0; i < numberList.size(); i++) { doubles[i] = numberList.get(i).doubleValue(); } return new DoubleColumn(name, new DoubleArrayList(doubles)); } public static DoubleColumn create(final String name, final Number[] numbers) { final double[] doubles = new double[numbers.length]; for (int i = 0; i < numbers.length; i++) { doubles[i] = numbers[i].doubleValue(); } return new DoubleColumn(name, new DoubleArrayList(doubles)); } public static DoubleColumn create(final String name, final int initialSize) { return new DoubleColumn(name, new DoubleArrayList(initialSize)); } @Override public DoubleColumn createCol(final String name, final int initialSize) { return create(name, initialSize); } @Override public Double get(int index) { return getDouble(index); } @Override public DoubleColumn subset(final int[] rows) { final DoubleColumn c = this.emptyCopy(); for (final int row : rows) { c.append(getDouble(row)); } return c; } @Override public DoubleColumn unique() { final DoubleSet doubles = new DoubleOpenHashSet(); for (int i = 0; i < size(); i++) { if (!isMissing(i)) { doubles.add(getDouble(i)); } } final DoubleColumn column = DoubleColumn.create(name() + " Unique values", doubles.size()); doubles.forEach((DoubleConsumer) column::append); return column; } @Override public DoubleColumn top(int n) { DoubleArrayList top = new DoubleArrayList(); double[] values = data.toDoubleArray(); DoubleArrays.parallelQuickSort(values, descendingComparator); for (int i = 0; i < n && i < values.length; i++) { top.add(values[i]); } return new DoubleColumn(name() + "[Top " + n + "]", top); } @Override public DoubleColumn bottom(final int n) { DoubleArrayList bottom = new DoubleArrayList(); double[] values = data.toDoubleArray(); DoubleArrays.parallelQuickSort(values); for (int i = 0; i < n && i < values.length; i++) { bottom.add(values[i]); } return new DoubleColumn(name() + "[Bottoms " + n + "]", bottom); } @Override public DoubleColumn lag(int n) { final int srcPos = n >= 0 ? 0 : 0 - n; final double[] dest = new double[size()]; final int destPos = n <= 0 ? 0 : n; final int length = n >= 0 ? size() - n : size() + n; for (int i = 0; i < size(); i++) { dest[i] = FloatColumnType.missingValueIndicator(); } double[] array = data.toDoubleArray(); System.arraycopy(array, srcPos, dest, destPos, length); return new DoubleColumn(name() + " lag(" + n + ")", new DoubleArrayList(dest)); } @Override public DoubleColumn removeMissing() { DoubleColumn result = copy(); result.clear(); DoubleListIterator iterator = data.iterator(); while (iterator.hasNext()) { double v = iterator.nextDouble(); if (!isMissingValue(v)) { result.append(v); } } return result; } public double firstElement() { if (size() > 0) { return getDouble(0); } return (Double) COLUMN_TYPE.getMissingValueIndicator(); } /** * Adds the given float to this column */ public DoubleColumn append(final float f) { data.add(f); return this; } /** * Adds the given double to this column */ public DoubleColumn append(double d) { data.add(d); return this; } public DoubleColumn append(int i) { data.add(i); return this; } @Override public DoubleColumn append(Double val) { this.append(val.doubleValue()); return this; } public DoubleColumn append(Integer val) { this.append(val.doubleValue()); return this; } @Override public DoubleColumn emptyCopy() { return (DoubleColumn) super.emptyCopy(); } @Override public DoubleColumn emptyCopy(final int rowSize) { return (DoubleColumn) super.emptyCopy(rowSize); } @Override public DoubleColumn copy() { return new DoubleColumn(name(), data.clone()); } @Override public Iterator<Double> iterator() { return (Iterator<Double>) data.iterator(); } @Override public Object[] asObjectArray() { final Double[] output = new Double[size()]; for (int i = 0; i < size(); i++) { output[i] = getDouble(i); } return output; } @Override public int compare(Double o1, Double o2) { return Double.compare(o1, o2); } @Override public DoubleColumn set(int i, Double val) { return set(i, (double) val); } public DoubleColumn set(int i, double val) { data.set(i, val); return this; } @Override public DoubleColumn append(final Column<Double> column) { Preconditions.checkArgument(column.type() == this.type()); final DoubleColumn numberColumn = (DoubleColumn) column; for (int i = 0; i < numberColumn.size(); i++) { append(numberColumn.getDouble(i)); } return this; } @Override public DoubleColumn append(Column<Double> column, int row) { Preconditions.checkArgument(column.type() == this.type()); return append(column.getDouble(row)); } /** * Maps the function across all rows, appending the results to a new NumberColumn * * @param fun function to map * @return the NumberColumn with the results */ public DoubleColumn map(ToDoubleFunction<Double> fun) { DoubleColumn result = DoubleColumn.create(name()); for (double t : this) { try { result.append(fun.applyAsDouble(t)); } catch (Exception e) { result.appendMissing(); } } return result; } /** * Returns a new NumberColumn with only those rows satisfying the predicate * * @param test the predicate * @return a new NumberColumn with only those rows satisfying the predicate */ public DoubleColumn filter(DoublePredicate test) { DoubleColumn result = DoubleColumn.create(name()); for (int i = 0; i < size(); i++) { double d = getDouble(i); if (test.test(d)) { result.append(d); } } return result; } @Override public byte[] asBytes(int rowNumber) { return ByteBuffer.allocate(COLUMN_TYPE.byteSize()).putDouble(getDouble(rowNumber)).array(); } @Override public int countUnique() { DoubleSet uniqueElements = new DoubleOpenHashSet(); for (int i = 0; i < size(); i++) { if (!isMissing(i)) { uniqueElements.add(getDouble(i)); } } return uniqueElements.size(); } @Override public double getDouble(int row) { return data.getDouble(row); } public boolean isMissingValue(double value) { return DoubleColumnType.isMissingValue(value); } @Override public boolean isMissing(int rowNumber) { return isMissingValue(getDouble(rowNumber)); } @Override public void sortAscending() { DoubleArrays.parallelQuickSort(data.elements()); } @Override public void sortDescending() { DoubleArrays.parallelQuickSort(data.elements(), descendingComparator); } @Override public DoubleColumn appendMissing() { return append(DoubleColumnType.missingValueIndicator()); } @Override public DoubleColumn appendObj(Object obj) { if (obj == null) { return appendMissing(); } if (obj instanceof Double) { return append((double) obj); } throw new IllegalArgumentException("Could not append " + obj.getClass()); } @Override public DoubleColumn appendCell(final String value) { try { return append(DoubleColumnType.DEFAULT_PARSER.parseDouble(value)); } catch (final NumberFormatException e) { throw new NumberFormatException("Error adding value to column " + name() + ": " + e.getMessage()); } } @Override public DoubleColumn appendCell(final String value, StringParser<?> parser) { try { return append(parser.parseDouble(value)); } catch (final NumberFormatException e) { throw new NumberFormatException("Error adding value to column " + name() + ": " + e.getMessage()); } } @Override public String getUnformattedString(final int row) { final double value = getDouble(row); if (DoubleColumnType.isMissingValue(value)) { return ""; } return String.valueOf(value); } // fillWith methods @Override public DoubleColumn fillWith(final DoubleIterator iterator) { for (int r = 0; r < size(); r++) { if (!iterator.hasNext()) { break; } set(r, iterator.nextDouble()); } return this; } @Override public DoubleColumn fillWith(final DoubleRangeIterable iterable) { DoubleIterator iterator = iterable.iterator(); for (int r = 0; r < size(); r++) { if (iterator == null || (!iterator.hasNext())) { iterator = iterable.iterator(); if (!iterator.hasNext()) { break; } } set(r, iterator.nextDouble()); } return this; } @Override public DoubleColumn fillWith(final DoubleSupplier supplier) { for (int r = 0; r < size(); r++) { try { set(r, supplier.getAsDouble()); } catch (final Exception e) { break; } } return this; } @Override public DoubleColumn inRange(int start, int end) { return (DoubleColumn) super.inRange(start, end); } @Override public DoubleColumn where(Selection selection) { return (DoubleColumn) super.where(selection); } @Override public DoubleColumn lead(int n) { return (DoubleColumn) super.lead(n); } @Override public DoubleColumn setName(String name) { return (DoubleColumn) super.setName(name); } @Override public DoubleColumn filter(Predicate<? super Double> test) { return (DoubleColumn) super.filter(test); } @Override public DoubleColumn sorted(Comparator<? super Double> comp) { return (DoubleColumn) super.sorted(comp); } @Override public DoubleColumn map(Function<? super Double, ? extends Double> fun) { return (DoubleColumn) super.map(fun); } @Override public DoubleColumn min(Column<Double> other) { return (DoubleColumn) super.min(other); } @Override public DoubleColumn max(Column<Double> other) { return (DoubleColumn) super.max(other); } @Override public DoubleColumn set(Selection condition, Column<Double> other) { return (DoubleColumn) super.set(condition, other); } @Override public DoubleColumn set(Selection rowSelection, Double newValue) { return (DoubleColumn) super.set(rowSelection, newValue); } @Override public DoubleColumn first(int numRows) { return (DoubleColumn) super.first(numRows); } @Override public DoubleColumn last(int numRows) { return (DoubleColumn) super.last(numRows); } @Override public DoubleColumn sampleN(int n) { return (DoubleColumn) super.sampleN(n); } @Override public DoubleColumn sampleX(double proportion) { return (DoubleColumn) super.sampleX(proportion); } }
package acr.browser.lightning.utils; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.util.Log; import com.squareup.otto.Bus; import net.i2p.android.ui.I2PAndroidHelper; import acr.browser.lightning.R; import acr.browser.lightning.app.BrowserApp; import acr.browser.lightning.bus.BrowserEvents; import acr.browser.lightning.constant.Constants; import acr.browser.lightning.preference.PreferenceManager; import info.guardianproject.netcipher.proxy.OrbotHelper; import info.guardianproject.netcipher.web.WebkitProxy; /** * 6/4/2015 Anthony Restaino */ public class ProxyUtils { // Helper private final I2PAndroidHelper mI2PHelper; private static boolean mI2PHelperBound; private static boolean mI2PProxyInitialized; private final PreferenceManager mPreferences; private static ProxyUtils mInstance; private final Bus mEventBus; private ProxyUtils(Context context) { mPreferences = BrowserApp.getPreferenceManager(); mEventBus = BrowserApp.getBus(); mI2PHelper = new I2PAndroidHelper(context.getApplicationContext()); } public static ProxyUtils getInstance() { if (mInstance == null) { mInstance = new ProxyUtils(BrowserApp.getContext()); } return mInstance; } /* * If Orbot/Tor or I2P is installed, prompt the user if they want to enable * proxying for this session */ public void checkForProxy(final Activity activity) { boolean useProxy = mPreferences.getUseProxy(); final boolean orbotInstalled = OrbotHelper.isOrbotInstalled(activity); boolean orbotChecked = mPreferences.getCheckedForTor(); boolean orbot = orbotInstalled && !orbotChecked; boolean i2pInstalled = mI2PHelper.isI2PAndroidInstalled(); boolean i2pChecked = mPreferences.getCheckedForI2P(); boolean i2p = i2pInstalled && !i2pChecked; // TODO Is the idea to show this per-session, or only once? if (!useProxy && (orbot || i2p)) { if (orbot) mPreferences.setCheckedForTor(true); if (i2p) mPreferences.setCheckedForI2P(true); AlertDialog.Builder builder = new AlertDialog.Builder(activity); if (orbotInstalled && i2pInstalled) { String[] proxyChoices = activity.getResources().getStringArray(R.array.proxy_choices_array); builder.setTitle(activity.getResources().getString(R.string.http_proxy)) .setSingleChoiceItems(proxyChoices, mPreferences.getProxyChoice(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mPreferences.setProxyChoice(which); } }) .setNeutralButton(activity.getResources().getString(R.string.action_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mPreferences.getUseProxy()) initializeProxy(activity); } }); } else { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: mPreferences.setProxyChoice(orbotInstalled ? Constants.PROXY_ORBOT : Constants.PROXY_I2P); initializeProxy(activity); break; case DialogInterface.BUTTON_NEGATIVE: mPreferences.setProxyChoice(Constants.NO_PROXY); break; } } }; builder.setMessage(orbotInstalled ? R.string.use_tor_prompt : R.string.use_i2p_prompt) .setPositiveButton(R.string.yes, dialogClickListener) .setNegativeButton(R.string.no, dialogClickListener); } builder.show(); } } /* * Initialize WebKit Proxying */ private void initializeProxy(Activity activity) { String host; int port; switch (mPreferences.getProxyChoice()) { case Constants.NO_PROXY: // We shouldn't be here return; case Constants.PROXY_ORBOT: if (!OrbotHelper.isOrbotRunning(activity)) OrbotHelper.requestStartTor(activity); host = "localhost"; port = 8118; break; case Constants.PROXY_I2P: mI2PProxyInitialized = true; if (mI2PHelperBound && !mI2PHelper.isI2PAndroidRunning()) { mI2PHelper.requestI2PAndroidStart(activity); } host = "localhost"; port = 4444; break; default: host = mPreferences.getProxyHost(); port = mPreferences.getProxyPort(); } try { WebkitProxy.setProxy(BrowserApp.class.getName(), activity.getApplicationContext(), null, host, port); } catch (Exception e) { Log.d(Constants.TAG, "error enabling web proxying", e); } } public boolean isProxyReady() { if (mPreferences.getProxyChoice() == Constants.PROXY_I2P) { if (!mI2PHelper.isI2PAndroidRunning()) { mEventBus.post(new BrowserEvents.ShowSnackBarMessage(R.string.i2p_not_running)); return false; } else if (!mI2PHelper.areTunnelsActive()) { mEventBus.post(new BrowserEvents.ShowSnackBarMessage(R.string.i2p_tunnels_not_ready)); return false; } } return true; } public void updateProxySettings(Activity activity) { if (mPreferences.getUseProxy()) { initializeProxy(activity); } else { try { WebkitProxy.resetProxy(BrowserApp.class.getName(), activity.getApplicationContext()); } catch (Exception e) { e.printStackTrace(); } mI2PProxyInitialized = false; } } public void onStop() { mI2PHelper.unbind(); mI2PHelperBound = false; } public void onStart(final Activity activity) { if (mPreferences.getProxyChoice() == Constants.PROXY_I2P) { // Try to bind to I2P Android mI2PHelper.bind(new I2PAndroidHelper.Callback() { @Override public void onI2PAndroidBound() { mI2PHelperBound = true; if (mI2PProxyInitialized && !mI2PHelper.isI2PAndroidRunning()) mI2PHelper.requestI2PAndroidStart(activity); } }); } } public static int setProxyChoice(int choice, Activity activity) { switch (choice) { case Constants.PROXY_ORBOT: if (!OrbotHelper.isOrbotInstalled(activity)) { choice = Constants.NO_PROXY; Utils.showSnackbar(activity, R.string.install_orbot); } break; case Constants.PROXY_I2P: I2PAndroidHelper ih = new I2PAndroidHelper(activity.getApplicationContext()); if (!ih.isI2PAndroidInstalled()) { choice = Constants.NO_PROXY; ih.promptToInstall(activity); } break; case Constants.PROXY_MANUAL: break; } return choice; } }
package com.biotronisis.pettplant.plant.processor; import com.biotronisis.pettplant.communication.transfer.RequestStateResponse; import com.biotronisis.pettplant.model.ColorMode; import com.biotronisis.pettplant.model.Entrainment; public class Plant { private static final String TAG = "Plant_Class"; private PlantState state; public Plant() { state = new PlantState(); } public static boolean isValidState(RequestStateResponse response) { // Verify that the data of each element of the plant's state is in the correct range if (!Entrainment.Sequence.isValid(response.getEntrainSequence().getId())) { return false; } if (!Entrainment.State.isValid(response.getEntrainmentState().getId())) { return false; } if (!Entrainment.LoopCheckbox.isValid(response.getLoopCheckbox().getId())) { return false; } if (!ColorMode.Mode.isValid(response.getColorMode().getId())) { return false; } if (!ColorMode.State.isValid(response.getColorModeState().getId())) { return false; } if (!ColorMode.Speed.isValid(response.getColorModeSpeed())) { return false; } return true; } public PlantState getState() { return state; } public void setState(RequestStateResponse response) { // Plant state data has been received from the plant and verified to be in the correct range. // Copy the data from the response object to the plant object state.setEntrainSequence(response.getEntrainSequence()); state.setEntrainmentState(response.getEntrainmentState()); state.setLoopCheckbox(response.getLoopCheckbox()); state.setColorMode(response.getColorMode()); state.setColorModeState(response.getColorModeState()); state.setColorModeSpeed(response.getColorModeSpeed()); } }
package com.denizugur.ninegagsaver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.Shader; import android.net.Uri; import android.os.Environment; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.view.Display; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.afollestad.materialdialogs.Theme; import com.github.clans.fab.FloatingActionButton; import com.google.gson.Gson; import com.google.gson.JsonParser; import com.nononsenseapps.filepicker.FilePickerActivity; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import static com.denizugur.ninegagsaver.MainActivity.*; public class DisplayReceivedImage extends AppCompatActivity implements View.OnClickListener { String gagTitle = ""; Bitmap photo; Bitmap newBitmap = null; String gagURL = null; String photo_id = null; Boolean isCustom; private int PICK_IMAGE_REQUEST = 1; private int FILE_CODE = 0; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; try { android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(false); } } catch (NullPointerException e) { e.printStackTrace(); } Intent intent = getIntent(); gagTitle = intent.getStringExtra(GAG_TITLE); gagURL = intent.getStringExtra(GAG_URL); isCustom = getIntent().getBooleanExtra("isCustom", false); setContentView(R.layout.activity_display_recieved_image); FloatingActionButton save = (FloatingActionButton) findViewById(R.id.save); FloatingActionButton share = (FloatingActionButton) findViewById(R.id.share); FloatingActionButton changeTitle = (FloatingActionButton) findViewById(R.id.changeTitle); final ImageView mImageView = (ImageView) findViewById(R.id.imageViewPhoto); final String gagTitleUnEdited = gagTitle; changeTitle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new MaterialDialog.Builder(context) .title("Change Title") .theme(Theme.DARK) .cancelable(false) .inputType(InputType.TYPE_CLASS_TEXT) .alwaysCallInputCallback() .negativeText("Cancel") .callback(new MaterialDialog.ButtonCallback() { @Override public void onNegative(MaterialDialog dialog) { super.onNegative(dialog); gagTitle = gagTitleUnEdited; process(photo, mImageView); } }) .input("Title", gagTitle, new MaterialDialog.InputCallback() { @Override public void onInput(MaterialDialog dialog, CharSequence input) { if (input.length() == 0) { dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false); gagTitle = ""; mImageView.setImageBitmap(photo); } else { dialog.getActionButton(DialogAction.POSITIVE).setEnabled(true); gagTitle = input.toString(); process(photo, mImageView); } } }).show(); } }); save.setOnClickListener(this); share.setOnClickListener(this); if (isCustom) { Intent i = new Intent(Intent.ACTION_PICK);
package com.example.android.learnchinese; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; public class ColorsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.words_list); // list of words for colors final ArrayList<Word> colors = new ArrayList<Word>(); initColors(colors); // init list view WordAdapter adapter = new WordAdapter(this, colors); ListView listView = (ListView) findViewById(R.id.words_list); listView.setAdapter(adapter); } private void initColors(ArrayList<Word> colors) { String packageName = this.getPackageName(); colors.add(new Word(getString(R.string.white_color), "", "bái sè", R.raw.white)); colors.add(new Word(getString(R.string.black_color), "", "hēi sè", R.raw.black))); colors.add(new Word(getString(R.string.red_color), "", "hóng sè", R.raw.red))); colors.add(new Word(getString(R.string.yellow_color), "", "huáng sè", R.raw.yellow))); colors.add(new Word(getString(R.string.green_color), "", "lǜ sè", R.raw.green))); colors.add(new Word(getString(R.string.blue_color), "", "lán sè", R.raw.blue))); colors.add(new Word(getString(R.string.brown_color), "", "hé sè", R.raw.brown))); colors.add(new Word(getString(R.string.orange_color), "", "chéng sè", R.raw.orange))); colors.add(new Word(getString(R.string.grey_color), "", "huī sè", R.raw.grey))); colors.add(new Word(getString(R.string.pink_color), "", "fěn hóng sè", R.raw.pink))); colors.add(new Word(getString(R.string.purple_color), "", "zǐ sè", R.raw.purple))); } }
package com.lincanbin.carbonforum; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.design.widget.Snackbar; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import com.lincanbin.carbonforum.adapter.PostAdapter; import com.lincanbin.carbonforum.application.CarbonForumApplication; import com.lincanbin.carbonforum.config.APIAddress; import com.lincanbin.carbonforum.util.HttpUtil; import com.lincanbin.carbonforum.util.JSONUtil; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class NotificationsActivity extends AppCompatActivity{ /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notifications); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); ImageButton imageButton = (ImageButton) toolbar.findViewById(R.id.notifications_settings_button); imageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(NotificationsActivity.this, SettingsActivity.class); intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, SettingsActivity.NotificationPreferenceFragment.class.getName()); intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true); startActivity(intent); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return PlaceholderFragment.newInstance(position + 1); } @Override public int getCount() { // Show 2 total pages. return 2; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.notifications_mentioned_me); case 1: return getString(R.string.notifications_replied_to_me); } return null; } } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment{ /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "notifications_type"; private static View rootView; private static SwipeRefreshLayout mSwipeRefreshLayout; private static RecyclerView mRecyclerView; private static PostAdapter mAdapter; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final int type = getArguments().getInt(ARG_SECTION_NUMBER); rootView = inflater.inflate(R.layout.fragment_notifications, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_notifications_swipe_refresh_layout); mSwipeRefreshLayout.setColorSchemeResources( R.color.material_light_blue_700, R.color.material_red_700, R.color.material_orange_700, R.color.material_light_green_700 ); //RecyclerView mRecyclerView = (RecyclerView) rootView.findViewById(R.id.notifications_list); mRecyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { //TODO } }); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mAdapter = new PostAdapter(getActivity(), true); mAdapter.setData(new ArrayList<Map<String, Object>>()); mRecyclerView.setAdapter(mAdapter); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new GetNotificationsTask(type, false, mSwipeRefreshLayout, mRecyclerView, mAdapter, 1).execute(); } }); new GetNotificationsTask(type, true, mSwipeRefreshLayout, mRecyclerView, mAdapter, 1).execute(); return rootView; } public class GetNotificationsTask extends AsyncTask<Void, Void, JSONObject> { private int targetPage; private int type; private String keyName; private Boolean loadFromCache; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView mRecyclerView; private PostAdapter mAdapter; public GetNotificationsTask(int type, Boolean loadFromCache, SwipeRefreshLayout mSwipeRefreshLayout, RecyclerView mRecyclerView, PostAdapter mAdapter, int targetPage) { this.targetPage = targetPage; this.type = type; this.keyName = type == 1 ? "ReplyArray" : "MentionArray"; this.loadFromCache = loadFromCache; this.mSwipeRefreshLayout = mSwipeRefreshLayout; this.mRecyclerView = mRecyclerView; this.mAdapter = mAdapter; } @Override protected void onPreExecute() { super.onPreExecute(); if(!loadFromCache) { mSwipeRefreshLayout.post(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(true); } }); } } @Override protected void onPostExecute(JSONObject jsonObject) { super.onPostExecute(jsonObject); int status = 0; if(loadFromCache){ status = 1; } if(jsonObject != null && !loadFromCache){ try { status = jsonObject.getInt("Status"); SharedPreferences.Editor cacheEditor = CarbonForumApplication.cacheSharedPreferences.edit(); //cacheEditor.putString("notifications" + keyName + "Cache", jsonObject.toString(0)); cacheEditor.putString("notificationsMentionArrayCache", jsonObject.toString(0)); cacheEditor.putString("notificationsReplyArrayCache", jsonObject.toString(0)); cacheEditor.apply(); }catch(Exception e){ e.printStackTrace(); } } List<Map<String, Object>> list; list = JSONUtil.jsonObject2List(jsonObject, keyName); //FragmentGCNullPointer if(mRecyclerView != null && mSwipeRefreshLayout !=null && mAdapter != null && rootView != null && getActivity() != null) { mSwipeRefreshLayout.setRefreshing(false); Log.d("Status : ", keyName + String.valueOf(status)); if (status == 1) { if(list != null && !list.isEmpty()){ Log.d("Action : ", keyName + " SetData"); mAdapter.setData(list); mAdapter.notifyDataSetChanged(); }else{ Snackbar.make(rootView, R.string.empty_notification, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } } else { Snackbar.make(rootView, R.string.network_error, Snackbar.LENGTH_LONG).setAction("Action", null).show(); } } //Tab if(type == 1 && loadFromCache){ new GetNotificationsTask(type, false, mSwipeRefreshLayout, mRecyclerView, mAdapter, 1).execute(); } } @Override protected JSONObject doInBackground(Void... params) { if(loadFromCache){ return JSONUtil.jsonString2Object( CarbonForumApplication.cacheSharedPreferences. getString("notifications" + keyName + "Cache", "{\"Status\":1, \"" + keyName + "\":[]}") ); }else { return HttpUtil.postRequest(getActivity(), APIAddress.NOTIFICATIONS_URL, new HashMap<String, String>(), false, true); } } } } }
package de.bitshares_munich.smartcoinswallet; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnItemSelected; import butterknife.OnTextChanged; import de.bitshares_munich.Interfaces.IAccount; import de.bitshares_munich.Interfaces.IExchangeRate; import de.bitshares_munich.Interfaces.IRelativeHistory; import de.bitshares_munich.models.AccountAssets; import de.bitshares_munich.models.AccountDetails; import de.bitshares_munich.models.TransferResponse; import de.bitshares_munich.utils.Application; import de.bitshares_munich.utils.Crypt; import de.bitshares_munich.utils.Helper; import de.bitshares_munich.utils.IWebService; import de.bitshares_munich.utils.ServiceGenerator; import de.bitshares_munich.utils.TinyDB; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SendScreen extends BaseActivity implements IExchangeRate, IAccount, IRelativeHistory { Context context; Application application = new Application(); TinyDB tinyDB; ArrayList<AccountDetails> accountDetails; AccountAssets selectedAccountAsset; AccountAssets loyaltyAsset; AccountAssets backupAssets; boolean validReceiver = false; boolean validAmount = false; ProgressDialog progressDialog; Double exchangeRate, requiredAmount, backAssetRate; boolean alwaysDonate = false; String backupAsset,receiverID,callbackURL; @Bind(R.id.FirstChild) LinearLayout FirstChild; @Bind(R.id.SecChild) LinearLayout SecChild; @Bind(R.id.ThirdChild) LinearLayout ThirdChild; @Bind(R.id.llMemo) LinearLayout llMemo; @Bind(R.id.llLoyalty) LinearLayout llLoyalty; @Bind(R.id.llBackupAsset) LinearLayout llBackupAsset; @Bind(R.id.tvLoyaltyStatus) TextView tvLoyaltyStatus; @Bind(R.id.tvTotalStatus) TextView tvTotalStatus; @Bind(R.id.spAssets) Spinner spAssets; @Bind(R.id.tvLoyalty) TextView tvLoyalty; @Bind(R.id.tvBackupAsset) TextView tvBackupAsset; @Bind(R.id.webviewFrom) WebView webviewFrom; @Bind(R.id.webviewTo) WebView webviewTo; @Bind(R.id.etReceiverAccount) EditText etReceiverAccount; @Bind(R.id.tvErrorRecieverAccount) TextView tvErrorRecieverAccount; @Bind(R.id.tvAmountStatus) TextView tvAmountStatus; @Bind(R.id.cbAlwaysDonate) CheckBox cbAlwaysDonate; @Bind(R.id.etMemo) EditText etMemo; @Bind(R.id.etAmount) EditText etAmount; @Bind(R.id.etBackupAsset) EditText etBackupAsset; @Bind(R.id.spinnerFrom) Spinner spinnerFrom; @Bind(R.id.btnSend) LinearLayout btnSend; @Bind(R.id.etLoyalty) EditText etLoyalty; @Bind(R.id.tvBlockNumberHead_send_screen_activity) TextView tvBlockNumberHead; @Bind(R.id.tvAppVersion_send_screen_activity) TextView tvAppVersion; @Bind(R.id.ivSocketConnected_send_screen_activity) ImageView ivSocketConnected; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.send_screen); setBackButton(true); context = getApplicationContext(); ButterKnife.bind(this); application.registerExchangeRateCallback(this); application.registerCallback(this); application.registerRelativeHistoryCallback(this); tinyDB = new TinyDB(context); accountDetails = tinyDB.getListObject(getString(R.string.pref_wallet_accounts), AccountDetails.class); init(); Intent intent = getIntent(); Bundle res = intent.getExtras(); if (res != null) { if (res.containsKey("sResult") && res.containsKey("id")) { try { if (res.getInt("id") == 5) { onScanResult(res.getString("sResult")); } } catch (JSONException e) { e.printStackTrace(); } } } tvAppVersion.setText("v" + BuildConfig.VERSION_NAME + getString(R.string.beta)); updateBlockNumberHead(); } void init() { setCheckboxAvailabilty(); setSpinner(); } void screenTwo() { llLoyalty.setVisibility(View.GONE); tvLoyaltyStatus.setVisibility(View.GONE); // tvTotalStatus.setVisibility(View.GONE); } void screenThree() { llMemo.setVisibility(View.GONE); } @OnTextChanged(R.id.etReceiverAccount) void onTextChangedTo(CharSequence text) { if (etReceiverAccount.getText().length() > 0) { loadWebView(webviewTo, 34, Helper.md5(etReceiverAccount.getText().toString())); myLowerCaseTimer.cancel(); myAccountNameValidationTimer.cancel(); myLowerCaseTimer.start(); myAccountNameValidationTimer.start(); } } @OnTextChanged(R.id.etAmount) void onAmountChanged(CharSequence text) { updateAmountStatus(); } @OnItemSelected(R.id.spinnerFrom) void onItemSelected(int position) { populateAssetsSpinner(); } @OnItemSelected(R.id.spAssets) void onAssetsSelected(int position) { updateAmountStatus(); } @OnTextChanged(R.id.etLoyalty) void onLoyaltyChanged(CharSequence text) { if (text.toString().equals("")) { text = "0"; } else if (text.toString().equals(".")) { text = "0."; } Double loyaltyAmount = Double.parseDouble(text.toString()); Double loyaltyBalance = Double.parseDouble(loyaltyAsset.ammount) / Math.pow(10, Integer.parseInt(loyaltyAsset.precision)); if (loyaltyAmount > loyaltyBalance) { tvLoyaltyStatus.setText(String.format(getString(R.string.str_warning_only_available), loyaltyBalance.toString(), loyaltyAsset.symbol)); } else { String remainingBalance = String.format("%.4f", (loyaltyBalance - loyaltyAmount)); tvLoyaltyStatus.setText(String.format(getString(R.string.str_balance_available), remainingBalance, loyaltyAsset.symbol)); } if (exchangeRate != null) { Double remainingAmount = requiredAmount - (loyaltyAmount / exchangeRate); etAmount.setText(remainingAmount.toString()); updateTotalStatus(); } else { getExchangeRate(100); } } @OnClick(R.id.btnSend) public void setBtnSend(View view) { if (validateSend()) { progressDialog = new ProgressDialog(this); showDialog("", "Transferring Funds..."); if (Double.parseDouble(etAmount.getText().toString()) != 0) { String mainAmount = String.format("%.4f", Double.parseDouble(etAmount.getText().toString())); String mainAsset = spAssets.getSelectedItem().toString(); transferAmount(mainAmount, mainAsset, etReceiverAccount.getText().toString()); } if (!etLoyalty.getText().toString().equals("") && Double.parseDouble(etLoyalty.getText().toString()) != 0) { String loyaltyAmount = String.format("%.4f", Double.parseDouble(etLoyalty.getText().toString())); String loyaltyAsset = tvLoyalty.getText().toString(); transferAmount(loyaltyAmount, loyaltyAsset, etReceiverAccount.getText().toString()); } if (alwaysDonate || cbAlwaysDonate.isChecked()) { transferAmount("2", "BTS", "bitshares-munich"); } } } public void updateAmountStatus() { String selectedAccount = spinnerFrom.getSelectedItem().toString(); String selectedAsset = spAssets.getSelectedItem().toString(); for (int i = 0; i < accountDetails.size(); i++) { AccountDetails accountDetail = accountDetails.get(i); if (accountDetail.account_name.equals(selectedAccount)) { for (int j = 0; j < accountDetail.AccountAssets.size(); j++) { AccountAssets tempAccountAsset = accountDetail.AccountAssets.get(j); if (tempAccountAsset.symbol.toLowerCase().equals(selectedAsset.toLowerCase())) { selectedAccountAsset = accountDetail.AccountAssets.get(j); break; } } } } Double selectedBalance = Double.parseDouble(selectedAccountAsset.ammount) / Math.pow(10, Integer.parseInt(selectedAccountAsset.precision)); if (etAmount.getText().length() > 0) { String enteredAmountStr = etAmount.getText().toString(); if (enteredAmountStr.equals(".")) { enteredAmountStr = "0."; } Double enteredAmount = Double.parseDouble(enteredAmountStr); if (enteredAmount != 0) { String remainingBalance = "0"; if (enteredAmount > selectedBalance | enteredAmount < 0) { //etAmount.setText(selectedBalance.toString()); validAmount = false; tvAmountStatus.setText(String.format(getString(R.string.str_warning_only_available), selectedBalance.toString(), selectedAsset)); } else { validAmount = true; remainingBalance = String.format("%.4f", (selectedBalance - enteredAmount)); tvAmountStatus.setText(String.format(getString(R.string.str_balance_available), remainingBalance, selectedAsset)); } } else { if (!etLoyalty.getText().toString().equals("")) { validAmount = true; } tvAmountStatus.setText(String.format(getString(R.string.str_balance_available), selectedBalance.toString(), selectedAsset)); } } else { tvAmountStatus.setText(String.format(getString(R.string.str_balance_available), selectedBalance.toString(), selectedAsset)); } } private void loadWebView(WebView webView, int size, String encryptText) { String htmlShareAccountName = "<html><head><style>body,html { margin:0; padding:0; text-align:center;}</style><meta name=viewport content=width=" + size + ",user-scalable=no/></head><body><canvas width=" + size + " height=" + size + " data-jdenticon-hash=" + encryptText + "></canvas><script src=https://cdn.jsdelivr.net/jdenticon/1.3.2/jdenticon.min.js async></script></body></html>"; WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.loadData(htmlShareAccountName, "text/html", "UTF-8"); } CountDownTimer myLowerCaseTimer = new CountDownTimer(500, 500) { public void onTick(long millisUntilFinished) { } public void onFinish() { if (!etReceiverAccount.getText().toString().equals(etReceiverAccount.getText().toString().toLowerCase())) { etReceiverAccount.setText(etReceiverAccount.getText().toString().toLowerCase()); etReceiverAccount.setSelection(etReceiverAccount.getText().toString().length()); } } }; CountDownTimer myAccountNameValidationTimer = new CountDownTimer(1000, 1000) { public void onTick(long millisUntilFinished) { } public void onFinish() { createBitShareAN(false); } }; public void createBitShareAN(boolean focused) { if (!focused) { if (etReceiverAccount.getText().length() > 2) { tvErrorRecieverAccount.setText(""); tvErrorRecieverAccount.setVisibility(View.GONE); if (Application.webSocketG.isOpen()) { String socketText = getString(R.string.lookup_account_a) + "\"" + etReceiverAccount.getText().toString() + "\"" + ",50]],\"id\": 6}"; Application.webSocketG.send(socketText); } } else { Toast.makeText(getApplicationContext(), R.string.account_name_should_be_longer, Toast.LENGTH_SHORT).show(); } } } void setCheckboxAvailabilty() { if (Helper.fetchBoolianSharePref(this, getString(R.string.pref_always_donate))) { cbAlwaysDonate.setVisibility(View.GONE); alwaysDonate = true; } else { cbAlwaysDonate.setChecked(true); } } void setBackUpAsset() { backupAsset = Helper.fetchStringSharePref(this, getString(R.string.pref_backup_symbol)); if (backupAsset != null && backupAsset.isEmpty()) { /* if (backupAsset.isEmpty()) { backupAsset = "BTS"; }*/ llBackupAsset.setVisibility(View.VISIBLE); tvBackupAsset.setText(backupAsset); getBackupAsset(); //getExchangeRate(200); } } private void getBackupAsset() { String selectedAccount = spinnerFrom.getSelectedItem().toString(); for (int i = 0; i < accountDetails.size(); i++) { AccountDetails accountDetail = accountDetails.get(i); if (accountDetail.account_name.equals(selectedAccount)) { for (int j = 0; j < accountDetail.AccountAssets.size(); j++) { AccountAssets tempAccountAsset = accountDetail.AccountAssets.get(j); if (tempAccountAsset.symbol.toLowerCase().equals(backupAsset.toLowerCase())) { backupAssets = accountDetail.AccountAssets.get(j); break; } } } } } @OnClick(R.id.scanning) void OnScanning() { Intent intent = new Intent(context, qrcodeActivity.class); intent.putExtra("id", 0); startActivityForResult(intent, 90); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 90: if (resultCode == RESULT_OK) { Bundle res = data.getExtras(); try { onScanResult(res.getString("sResult")); } catch (JSONException e) { e.printStackTrace(); } } break; } } void onScanResult(String result) throws JSONException { JSONObject resJson = new JSONObject(result); resJson = new JSONObject(resJson.get("json").toString()); callbackURL = resJson.get("callback").toString(); if (callbackURL.substring(callbackURL.length() - 1) != "/"){ callbackURL = callbackURL + "/"; } etReceiverAccount.setText(resJson.get("to").toString()); validReceiver = true; spAssets.setSelection(getSpinnerIndex(spAssets, resJson.get("currency").toString())); spAssets.setClickable(false); if (resJson.get("memo") != null) { llMemo.setVisibility(View.GONE); etMemo.setText(resJson.get("memo").toString()); } else llMemo.setVisibility(View.VISIBLE); JSONArray lineItems = new JSONArray(resJson.get("line_items").toString()); Double totalAmount = 0.0; for (int i = 0; i < lineItems.length(); i++) { JSONObject lineItem = (JSONObject) lineItems.get(i); totalAmount += (Double.parseDouble(lineItem.get("quantity").toString()) * Double.parseDouble(lineItem.get("price").toString())); } requiredAmount = totalAmount; etAmount.setText(totalAmount.toString()); etAmount.setEnabled(false); // selectBTSAmount.setText(hash.get("currency")); String loyaltypoints = resJson.get("ruia").toString(); String selectedAccount = spinnerFrom.getSelectedItem().toString(); if (loyaltypoints != null) { for (int i = 0; i < accountDetails.size(); i++) { AccountDetails accountDetail = accountDetails.get(i); if (accountDetail.account_name.equals(selectedAccount)) { for (int j = 0; j < accountDetail.AccountAssets.size(); j++) { AccountAssets tempAccountAsset = accountDetail.AccountAssets.get(j); if (tempAccountAsset.id.equals(loyaltypoints)) { loyaltyAsset = accountDetail.AccountAssets.get(j); break; } } } } if (loyaltyAsset != null) { getExchangeRate(100); Double loyaltyBalance = Double.parseDouble(loyaltyAsset.ammount) / Math.pow(10, Integer.parseInt(loyaltyAsset.precision)); tvLoyalty.setText(loyaltyAsset.symbol); tvLoyaltyStatus.setText(String.format(getString(R.string.str_balance_available), loyaltyBalance.toString(), loyaltyAsset.symbol)); llLoyalty.setVisibility(View.VISIBLE); tvLoyaltyStatus.setVisibility(View.VISIBLE); } } else { llLoyalty.setVisibility(View.GONE); tvLoyaltyStatus.setVisibility(View.GONE); } } public void createSpinner(List<String> spinnerArray, Spinner spinner) { ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerArray); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(dataAdapter); } public void populateAccountsSpinner() { List<String> spinnerArray = new ArrayList<String>(); for (int i = 0; i < accountDetails.size(); i++) { AccountDetails accountDetail = accountDetails.get(i); spinnerArray.add(accountDetail.account_name); } createSpinner(spinnerArray, spinnerFrom); } public void populateAssetsSpinner() { String selectedAccount = spinnerFrom.getSelectedItem().toString(); List<String> spinnerArray = new ArrayList<String>(); for (int i = 0; i < accountDetails.size(); i++) { AccountDetails accountDetail = accountDetails.get(i); if (accountDetail.account_name.equals(selectedAccount)) { for (int j = 0; j < accountDetail.AccountAssets.size(); j++) { selectedAccountAsset = accountDetail.AccountAssets.get(j); spinnerArray.add(selectedAccountAsset.symbol); } } } createSpinner(spinnerArray, spAssets); } void setSpinner() { populateAccountsSpinner(); populateAssetsSpinner(); setBackUpAsset(); } public void getExchangeRate(int id) { //id 200 for exchange rate if (application.webSocketG.isOpen()) { int db_identifier = Helper.fetchIntSharePref(context,context.getString(R.string.sharePref_database)); String params = "{\"id\":7,\"method\":\"call\",\"params\":["+db_identifier+",\"get_limit_orders\",[\""+selectedAccountAsset.id+"\",\""+loyaltyAsset.id+"\",1]]}"; application.webSocketG.send(params); } } public boolean validateSend() { if (spinnerFrom.getSelectedItem().toString().equals("")) { return false; } else if (!validReceiver) { Toast.makeText(context, R.string.str_invalid_receiver, Toast.LENGTH_SHORT).show(); return false; } else if (!validAmount) { Toast.makeText(context, R.string.str_invalid_amount, Toast.LENGTH_SHORT).show(); return false; } return true; } public void transferAmount(String amount, String symbol, String toAccount) { String selectedAccount = spinnerFrom.getSelectedItem().toString(); String privateKey = ""; for (int i = 0; i < accountDetails.size(); i++) { AccountDetails accountDetail = accountDetails.get(i); if (accountDetail.account_name.equals(selectedAccount)) { try { privateKey = Crypt.getInstance().decrypt_string(accountDetail.wif_key); } catch (Exception e) { e.printStackTrace(); } } } HashMap hm = new HashMap(); hm.put("method", "transfer"); hm.put("wifkey", privateKey); hm.put("from_account", spinnerFrom.getSelectedItem().toString()); hm.put("to_account", toAccount); hm.put("amount", amount); hm.put("asset_symbol", symbol); hm.put("memo", etMemo.getText().toString()); ServiceGenerator sg = new ServiceGenerator(getString(R.string.transfer_server_url)); IWebService service = sg.getService(IWebService.class); final Call<TransferResponse> postingService = service.getTransferResponse(hm); postingService.enqueue(new Callback<TransferResponse>() { @Override public void onResponse(Response<TransferResponse> response) { if (response.isSuccess()) { TransferResponse resp = response.body(); if (resp.status.equals("success")) { if (!isFinishing()) { if (callbackURL != null) { getTrxBlock(); } Intent intent = new Intent(getApplicationContext(), TabActivity.class); startActivity(intent); finish(); } } else { Toast.makeText(context, R.string.str_transaction_failed, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(context, getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show(); } hideDialog(); } @Override public void onFailure(Throwable t) { hideDialog(); Toast.makeText(context, getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show(); } }); } private int getSpinnerIndex(Spinner spinner, String myString) { int index = 0; for (int i = 0; i < spinner.getCount(); i++) { if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)) { index = i; break; } } return index; } @Override public void callback_exchange_rate(JSONObject result) throws JSONException { if (result.length() > 0) { if (result.getInt("id") == 100) { JSONObject sell_price = (JSONObject) result.get("sell_price"); JSONObject base = (JSONObject) sell_price.get("quote"); String base_amount = base.get("amount").toString(); JSONObject quote = (JSONObject) sell_price.get("base"); String quote_amount = quote.get("amount").toString(); Double baseWithPrecision = Double.parseDouble(base_amount) / Math.pow(10, Double.parseDouble(selectedAccountAsset.precision)); Double quoteWithPrecision = Double.parseDouble(quote_amount) / Math.pow(10, Double.parseDouble(loyaltyAsset.precision)); exchangeRate = quoteWithPrecision / baseWithPrecision; runOnUiThread(new Runnable() { public void run() { updateTotalStatus(); } }); } else { runOnUiThread(new Runnable() { public void run() { Toast.makeText(context, R.string.str_trading_pair_not_exist, Toast.LENGTH_SHORT).show(); } }); } } } @Override public void checkAccount(JSONObject jsonObject) { try { JSONArray jsonArray = jsonObject.getJSONArray("result"); boolean found = false; for (int i = 0; i < jsonArray.length(); i++) { final String temp = jsonArray.getJSONArray(i).getString(0); if (temp.equals(etReceiverAccount.getText().toString())) { found = true; validReceiver = true; receiverID = jsonArray.getJSONArray(i).getString(1); } } if (!found) { runOnUiThread(new Runnable() { @Override public void run() { validReceiver = false; String acName = getString(R.string.account_name_not_exist); String format = String.format(acName, etReceiverAccount.getText().toString()); tvErrorRecieverAccount.setText(format); tvErrorRecieverAccount.setVisibility(View.VISIBLE); } }); } } catch (Exception e) { } } private void showDialog(String title, String msg) { if (progressDialog != null) { if (!progressDialog.isShowing()) { progressDialog.setTitle(title); progressDialog.setMessage(msg); progressDialog.show(); } } } private void hideDialog() { if (progressDialog != null) { if (progressDialog.isShowing()) { progressDialog.cancel(); } } } public void updateTotalStatus() { String selectedAmount = etAmount.getText().toString(); String loyaltyAmount = etLoyalty.getText().toString(); if (loyaltyAmount.equals("")) { loyaltyAmount = "0"; } Double totalAmount = Double.parseDouble(selectedAmount) + (Double.parseDouble(loyaltyAmount) / exchangeRate); tvTotalStatus.setText(String.format(getString(R.string.str_total_status), selectedAmount, selectedAccountAsset.symbol, loyaltyAmount, loyaltyAsset.symbol, totalAmount.toString(), selectedAccountAsset.symbol)); tvTotalStatus.setVisibility(View.VISIBLE); } public void getTrxBlock(){ if (application.webSocketG.isOpen()) { String selectedAccountId = ""; String selectedAccount = spinnerFrom.getSelectedItem().toString(); for (int i=0; i<accountDetails.size(); i++){ AccountDetails accountDetail = accountDetails.get(i); if (accountDetail.account_name.equals(selectedAccount)){ selectedAccountId = accountDetail.account_id; } } int historyIdentifier = Helper.fetchIntSharePref(context,context.getString(R.string.sharePref_history)); String params = "{\"id\":16,\"method\":\"call\",\"params\":["+historyIdentifier+",\"get_relative_account_history\",[\""+selectedAccountId+"\",0,10,0]]}"; application.webSocketG.send(params); } } @Override public void relativeHistoryCallback(JSONObject msg) { try { JSONArray jsonArray = (JSONArray) msg.get("result"); JSONObject jsonObject = (JSONObject) jsonArray.get(0); JSONArray opArray = (JSONArray) jsonObject.get("op"); JSONObject operation = (JSONObject) opArray.get(1); if (operation.get("to").toString().equals(receiverID)){ ServiceGenerator sg = new ServiceGenerator(callbackURL); IWebService service = sg.getService(IWebService.class); final Call<Void> postingService = service.sendCallback(callbackURL,jsonObject.get("block_num").toString(),jsonObject.get("trx_in_block").toString()); postingService.enqueue(new Callback<Void>() { @Override public void onResponse(Response<Void> response) { if (response.isSuccess()) { } else { // Toast.makeText(context, getString(R.string.txt_no_internet_connection), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Throwable t) { // if (progressDialog.isShowing()) // progressDialog.dismiss(); } }); } }catch (Exception e){ e.printStackTrace(); } } /// Updating Block Number and status private String prevBlockNumber = ""; private int counterBlockCheck = 0; private Boolean isBlockUpdated() { if ( Application.blockHead != prevBlockNumber ) { prevBlockNumber = Application.blockHead; counterBlockCheck = 0; return true; } else if ( counterBlockCheck++ >= 30 ) { return false; } return true; } private void updateBlockNumberHead() { final Handler handler = new Handler(); final Runnable updateTask = new Runnable() { @Override public void run() { if (Application.webSocketG != null) { if (Application.webSocketG.isOpen() && (isBlockUpdated())) { boolean paused = Application.webSocketG.isPaused(); ivSocketConnected.setImageResource(R.drawable.icon_connecting); tvBlockNumberHead.setText(Application.blockHead); } else { ivSocketConnected.setImageResource(R.drawable.icon_disconnecting); Application.webSocketG.close(); Application.webSocketConnection(); } } handler.postDelayed(this, 2000); } }; handler.postDelayed(updateTask, 2000); } @OnClick(R.id.OnClickSettings_send_screen_activity) void OnClickSettings(){ Intent intent = new Intent(this, SettingActivity.class); startActivity(intent); } }
package de.fau.cs.mad.fablab.android.cart; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.os.AsyncTask; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.github.brnunes.swipeablerecyclerview.SwipeableRecyclerViewTouchListener; import com.j256.ormlite.dao.RuntimeExceptionDao; import com.j256.ormlite.stmt.DeleteBuilder; import com.j256.ormlite.stmt.QueryBuilder; import com.sothree.slidinguppanel.SlidingUpPanelLayout; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import de.fau.cs.mad.fablab.android.R; import de.fau.cs.mad.fablab.android.db.DatabaseHelper; import de.fau.cs.mad.fablab.rest.core.Cart; import de.fau.cs.mad.fablab.rest.core.CartEntry; import de.fau.cs.mad.fablab.rest.core.CartStatusEnum; import de.fau.cs.mad.fablab.rest.core.Product; public enum CartSingleton { MYCART; private List<Boolean> isProductRemoved; private List<CartEntry> guiProducts; private RuntimeExceptionDao<CartEntry, Long> cartEntryDao; private RuntimeExceptionDao<Cart, String> cartDao; private RuntimeExceptionDao<Product, String> productDao; private RecyclerViewAdapter adapter; private Context context; private View view; private SlidingUpPanelLayout mLayout; private boolean slidingUp; private Cart cart; private List<CartEntry> products; CartSingleton(){ } public Cart getCart() { return cart; } // initialization of the db - getting all products that are in the cart // call this method on startup activity public void init(Context context){ cartDao = DatabaseHelper.getHelper(context).getCartDao(); cartEntryDao = DatabaseHelper.getHelper(context).getCartEntryDao(); productDao = DatabaseHelper.getHelper(context).getProductDao(); QueryBuilder<Cart, String> queryBuilder = cartDao.queryBuilder(); try { queryBuilder.where().eq("status", CartStatusEnum.SHOPPING).or().eq("status", CartStatusEnum.PENDING); cart = cartDao.queryForFirst(queryBuilder.prepare()); } catch (SQLException e) { e.printStackTrace(); } if(cart == null) { cart = new Cart(); cart.setCartCode(Long.toString(new Random().nextLong())); cartDao.create(cart); products = new ArrayList<>(); }else{ products = cartEntryDao.queryForEq("cart_id", cart.getCartCode()); } isProductRemoved = new ArrayList<>(); guiProducts = new ArrayList<>(); for(int i=0;i<products.size();i++){ isProductRemoved.add(false); guiProducts.add(products.get(i)); } } // Setting up the view for every context c including the sliding up panel public void setSlidingUpPanel(Context c, View v, boolean slidingUp){ this.context = c; this.view = v; this.slidingUp = slidingUp; // Set Layout and Recyclerview RecyclerView cart_rv = (RecyclerView) v.findViewById(R.id.cart_recycler_view); LinearLayoutManager llm = new LinearLayoutManager(context); cart_rv.setLayoutManager(llm); cart_rv.setHasFixedSize(true); // Add Entries to view adapter = new RecyclerViewAdapter(this.context, guiProducts); cart_rv.setAdapter(adapter); // Set up listener to be able to swipe to left/right to remove items SwipeableRecyclerViewTouchListener swipeTouchListener = new SwipeableRecyclerViewTouchListener(cart_rv, new SwipeableRecyclerViewTouchListener.SwipeListener() { @Override public boolean canSwipe(int position) { return true; } @Override public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { View card = recyclerView.getChildAt(position); LinearLayout ll = (LinearLayout) card.findViewById(R.id.cart_entry_undo); LinearLayout ll_before = (LinearLayout) card.findViewById(R.id.product_view); if(isProductRemoved.get(position) == true){ ll_before.setClickable(true); ll.setClickable(false); isProductRemoved.remove(position); guiProducts.remove(position); adapter.notifyItemRemoved(position); }else{ isProductRemoved.set(position, true); CartSingleton.MYCART.removeEntry(guiProducts.get(position)); ll_before.setClickable(false); ll.setClickable(true); RemoveCartEntryTimerTask myTask = new RemoveCartEntryTimerTask(card, position); Timer myTimer = new Timer(); myTimer.schedule(myTask, 0, 100); } } refresh(); adapter.notifyDataSetChanged(); updateVisibility(); } @Override public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { View card = recyclerView.getChildAt(position); LinearLayout ll = (LinearLayout) card.findViewById(R.id.cart_entry_undo); LinearLayout ll_before = (LinearLayout) card.findViewById(R.id.product_view); if(ll.getVisibility() == View.VISIBLE){ ll_before.setClickable(true); ll.setClickable(false); guiProducts.remove(position); isProductRemoved.remove(position); adapter.notifyItemRemoved(position); }else{ isProductRemoved.set(position, true); CartSingleton.MYCART.removeEntry(guiProducts.get(position)); ll_before.setClickable(false); ll.setClickable(true); RemoveCartEntryTimerTask myTask = new RemoveCartEntryTimerTask(card, position); Timer myTimer = new Timer(); myTimer.schedule(myTask, 0, 100); } } refresh(); adapter.notifyDataSetChanged(); updateVisibility(); } }); cart_rv.addOnItemTouchListener(swipeTouchListener); // Set up listener to show more than just one line of the product name cart_rv.addOnItemTouchListener(new RecyclerItemClickListener(context, cart_rv, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, final int position, MotionEvent e) { TextView product_title = (TextView) view.findViewById(R.id.cart_product_name); Spinner cart_product_quantity_spinner = (Spinner) view.findViewById(R.id.cart_product_quantity_spinner); Button undo = (Button) view.findViewById(R.id.cart_product_undo); ImageView undo_img = (ImageView) view.findViewById(R.id.cart_product_undo_img); LinearLayout ll = (LinearLayout) view.findViewById(R.id.cart_entry_undo); int x = (int)e.getRawX(); int y = (int)e.getRawY(); // show / hide full text title if(!inViewInBounds(cart_product_quantity_spinner, x, y) && ll.getVisibility() == View.GONE){ if(product_title.getLineCount() == 1){ product_title.setSingleLine(false); }else{ product_title.setSingleLine(true); } }else if(inViewInBounds(undo_img, x, y) && ll.getVisibility() == View.VISIBLE){ // recognize undo click undo.performClick(); } } // check the touch position for quantity change / card click @Override public boolean inViewInBounds(View view, int x, int y){ Rect outRect = new Rect(); int[] location = new int[2]; view.getDrawingRect(outRect); view.getLocationOnScreen(location); outRect.offset(location[0], location[1]); return outRect.contains(x, y); } @Override public void onItemLongClick(View view, final int position){ } })); // checkout button Button checkoutButton = (Button) v.findViewById(R.id.cart_button_checkout); checkoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (cart.getProducts().size() == 0) { Toast.makeText(context, R.string.cart_empty, Toast.LENGTH_LONG).show(); return; } Intent intent = new Intent(context, CheckoutActivity2.class); context.startActivity(intent); } }); // set total price refresh(); // Basket empty? -> show msg if slidinguppanel is not used if(guiProducts.size() == 0 && !slidingUp){ Toast.makeText(context, R.string.cart_empty, Toast.LENGTH_LONG).show(); } // Set up Sliding up Panel if(slidingUp) { mLayout = (SlidingUpPanelLayout) view.findViewById(R.id.sliding_layout); // only the top should be draggable mLayout.setDragView(view.findViewById(R.id.dragPart)); mLayout.setPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() { @Override public void onPanelSlide(View panel, float slideOffset) { TextView total_price_top = (TextView) view.findViewById(R.id.cart_total_price_preview); total_price_top.setAlpha(1 - slideOffset); int diff = (int) (view.getResources().getDimension(R.dimen.slidinguppanel_panel_height) - view.getResources().getDimension(R.dimen.slidinguppanel_panel_height_opened)); LinearLayout drag = (LinearLayout) view.findViewById(R.id.dragPart); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, (int) (view.getResources().getDimension(R.dimen.slidinguppanel_panel_height) - (diff*slideOffset))); layoutParams.setMargins((int) view.getResources().getDimension(R.dimen.slidinguppanel_drag_bg_stroke_margin),0,(int) view.getResources().getDimension(R.dimen.slidinguppanel_drag_bg_stroke_margin),0); drag.setLayoutParams(layoutParams); } @Override public void onPanelExpanded(View panel) { //Log.i("app", "onPanelExpanded"); } @Override public void onPanelCollapsed(View panel) { //Log.i("app", "onPanelCollapsed"); } @Override public void onPanelAnchored(View panel) { //Log.i("app", "onPanelAnchored"); } @Override public void onPanelHidden(View panel) { //Log.i("app", "onPanelHidden"); } }); updateVisibility(); } } // remove product from deleted list // re-add product to cart, to the db tables, respectively public void addRemovedProduct(int position){ if(guiProducts.size() != 0) { cartEntryDao.create(guiProducts.get(position)); adapter.notifyDataSetChanged(); refresh(); } } // Getter for RecyclerViewAdapter class to check whether a product has an active removed view or not public List<Boolean> getIsProductRemoved(){ return isProductRemoved; } // refresh TextView of the total price and #items in cart public void refresh(){ TextView total_price = (TextView) view.findViewById(R.id.cart_total_price); total_price.setText(CartSingleton.MYCART.totalPrice()); String base = view.getResources().getString(R.string.bold_start) + guiProducts.size() + view.getResources().getString(R.string.cart_article_label) + view.getResources().getString(R.string.cart_preview_delimiter) + CartSingleton.MYCART.totalPrice() + view.getResources().getString(R.string.bold_end); TextView total_price_top = (TextView) view.findViewById(R.id.cart_total_price_preview); total_price_top.setText(Html.fromHtml(base)); } // panel only visible if cart is not empty public void updateVisibility(){ if(this.slidingUp) { if (guiProducts.size() == 0) { mLayout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN); mLayout.setPanelHeight((int) (view.getResources().getDimension(R.dimen.zero) / view.getResources().getDisplayMetrics().density)); } else { mLayout.setPanelHeight((int) view.getResources().getDimension(R.dimen.slidinguppanel_panel_height)); } } } // returns all existing products of the cart // <-> don't necessarily need to be the same as guiProducts public List<CartEntry> getProducts(){ return products; } // update CartEntry in db table public void updateProducts(int position){ int pos = products.indexOf(guiProducts.get(position)); products.get(pos).setAmount(guiProducts.get(position).getAmount()); cartEntryDao.update(products.get(pos)); } // remove CartEntry from db table public void removeEntry(CartEntry entry){ products.remove(entry); DeleteBuilder db_entry = cartEntryDao.deleteBuilder(); try { db_entry.where().eq("id", entry.getId()); cartEntryDao.delete(db_entry.prepare()); }catch(SQLException e) { e.printStackTrace(); } } // remove all entries from GUI and db tables public void removeAllEntries() { DeleteBuilder db_cart = cartDao.deleteBuilder(); DeleteBuilder db_entries = cartEntryDao.deleteBuilder(); try { db_entries.where().eq("cart_id", cart.getCartCode()); cartEntryDao.delete(db_entries.prepare()); }catch(SQLException e) { e.printStackTrace(); } try { db_cart.where().eq("cart_id", cart.getCartCode()); cartDao.delete(db_cart.prepare()); }catch(SQLException e) { e.printStackTrace(); } guiProducts.clear(); isProductRemoved.clear(); products.clear(); } // add product to cart public void addProduct(Product product, double amount){ // update existing cart entry for(CartEntry temp : guiProducts){ if (temp.getProduct().getProductId().equals(product.getProductId())){ temp.setAmount(temp.getAmount() + amount); int pos = products.indexOf(temp); products.get(pos).setAmount(temp.getAmount()); cartEntryDao.update(products.get(pos)); return; } } // create new one CartEntry new_entry = new CartEntry(product, amount); new_entry.setCart(cart); new_entry.setProduct(product); cartEntryDao.create(new_entry); products.add(new_entry); guiProducts.add(new_entry); isProductRemoved.add(false); } // return total price public String totalPrice(){ double total = cart.getTotal(); return String.format( "%.2f", total ) + Html.fromHtml(view.getResources().getString(R.string.non_breaking_space)) + view.getResources().getString(R.string.currency); } // Timer Task to show a removed entry 5 sec before removing it permanently class RemoveCartEntryTimerTask extends TimerTask{ private View view; private int pos; // Parameter view represents the card // Parameter pos represents position in RecyclerView RemoveCartEntryTimerTask(View view, int pos){ this.view = view; this.pos = pos; } public void run(){ view.setAlpha(view.getAlpha()-0.02f); if(view.getAlpha() == 0){ isProductRemoved.remove(pos); guiProducts.remove(pos); adapter.notifyItemRemoved(pos); refresh(); updateVisibility(); this.cancel(); } } } }
package deadpixel.app.vapor.ui.fragments; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.ListFragment; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ListView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import java.util.ArrayList; import deadpixel.app.vapor.adapter.FilesListViewAdapter; import deadpixel.app.vapor.cloudapp.api.model.CloudAppItem; import deadpixel.app.vapor.database.FilesManager; import deadpixel.app.vapor.database.model.DatabaseItem; import deadpixel.app.vapor.libs.EaseOutQuint; import deadpixel.app.vapor.ui.ImageViewActivity; import deadpixel.app.vapor.ui.intefaces.FilesFragment; import deadpixel.app.vapor.utils.AppUtils; public class RecentFragment extends Fragment implements FilesFragment, AbsListView.OnScrollListener{ FilesListViewAdapter adapter; //A flag for when the fragment is in the process of getting more files after an onScroll event //Fragment optimistically assumes there is more files on startup up. False when a get from database returns 0 files public boolean moreFiles = true; boolean fullySynced; boolean userScrolled = false; final int AUTOLOAD_THRESHOLD = 4; public boolean mAutoLoad; ArrayList<DatabaseItem> items; View noFiles; View refreshingFiles; //View loadingMoreFiles; FrameLayout footerFrameLayout; FrameLayout headerFrameLayout; AnimationDrawable anim; public CloudAppItem.Type getType() { return mType; } public void setType(CloudAppItem.Type mType) { this.mType = mType; } CloudAppItem.Type mType = CloudAppItem.Type.ALL; private State mState; public RecentFragment() { } private enum State { NO_FILES, REFRESHING, NORMAL, LOADING_MORE } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); firstStart = AppUtils.mPref.getBoolean(AppUtils.APP_FIRST_START, true); if(firstStart && !isLoading) { isLoading = true; FilesManager.requestMoreFiles(CloudAppItem.Type.ALL); } footerFrameLayout = new FrameLayout(getActivity()); headerFrameLayout = new FrameLayout(getActivity()); AbsListView.LayoutParams paramsMatchParent = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); footerFrameLayout.setLayoutParams(paramsMatchParent); footerFrameLayout.setForegroundGravity(Gravity.CENTER); headerFrameLayout.setLayoutParams(paramsMatchParent); headerFrameLayout.setForegroundGravity(Gravity.CENTER); noFiles = getActivity().getLayoutInflater().inflate(R.layout.no_files, null); refreshingFiles = getActivity().getLayoutInflater().inflate(R.layout.refreshing, null); footerFrameLayout = (FrameLayout) getActivity().getLayoutInflater().inflate(R.layout.loading_more, null); anim = (AnimationDrawable) footerFrameLayout.findViewById(R.id.image).getBackground(); anim.start(); anim = (AnimationDrawable) refreshingFiles.findViewById(R.id.image).getBackground(); anim.start(); } private void setFooterVisibility(int i) { if(i == 0) { footerFrameLayout.setVisibility(View.GONE); } else if(i == 1) { footerFrameLayout.setVisibility(View.VISIBLE); } } private void resetFooter() { footerFrameLayout.setVisibility(View.VISIBLE); final View textContainer = footerFrameLayout.findViewById(R.id.load_more_text_container); final View btnContainer = footerFrameLayout.findViewById(R.id.load_more_button_container); final Button loadMoreButton = (Button) footerFrameLayout.findViewById(R.id.load_more_button); if(!fullySynced) { if (mAutoLoad) { textContainer.setVisibility(View.VISIBLE); btnContainer.setVisibility(View.GONE); } else { YoYo.with(Techniques.FadeOutDown).duration(250).withListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { textContainer.setVisibility(View.GONE); btnContainer.setVisibility(View.VISIBLE); YoYo.with(Techniques.FadeInUp).duration(250).withListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { btnContainer.setEnabled(false); } @Override public void onAnimationEnd(Animator animation) { btnContainer.setEnabled(true); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).playOn(btnContainer); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).playOn(textContainer); loadMoreButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { YoYo.with(Techniques.FadeOutDown).duration(250).interpolate(new EaseOutQuint()).withListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { textContainer.setVisibility(View.VISIBLE); YoYo.with(Techniques.FadeInUp).duration(250).interpolate(new EaseOutQuint()).playOn(textContainer); loadMoreFiles(); } @Override public void onAnimationEnd(Animator animation) { btnContainer.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }).playOn(btnContainer); } }); //addFooterView(loadingMoreFiles); } } else { setFooterVisibility(0); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setBackgroundResource(0); getListView().setDivider(null); getListView().setDividerHeight(0); getListView().setFastScrollEnabled(true); items = new ArrayList<DatabaseItem>(); //FilesManager.getFiles(CloudAppItem.Type.ALL); adapter = new FilesListViewAdapter(getActivity(),items); getListView().setOnScrollListener(this); getListView().setAdapter(null); getListView().addHeaderView(headerFrameLayout); getListView().addFooterView(footerFrameLayout); //addFooterView(loadingMoreFiles); resetFooter(); //The initial files get is handled by the parent activity of this fragment. //adds the refreshing view's View on app first load to tell users the app is doing work. if (AppUtils.mPref.getBoolean(AppUtils.APP_FIRST_START, true) || isLoading ) { updateState(State.REFRESHING); } else { //Get all items in the database for this fragment. new GetAllItemsTask().execute(); updateState(State.NORMAL); } setListAdapter(adapter); getListView().setSelector(android.R.color.transparent); } protected void addHeaderView(View v) { headerFrameLayout.removeAllViews(); headerFrameLayout.addView(v); } protected void removeHeaderViews() { headerFrameLayout.removeAllViews(); } @Override public void datebaseUpdateEvent(ArrayList<DatabaseItem> items) { //Gets all items added when runs first even though all items would be in the parameter. if(mState == State.REFRESHING) { new GetAllItemsTask().execute(); } else { //Appends items to list when users scrolls to the bottom. this.addItemsToAdapter(sortListByType(getType(), items)); } } @Override public void errorEvent() { updateState(State.NORMAL); new GetAllItemsTask().execute(); isLoading = false; resetFooter(); } @Override public void refresh() { updateState(State.REFRESHING); //isLoading =true; FilesManager.refreshFiles(); } protected void addItemsToAdapter(ArrayList<DatabaseItem> items) { //Loading is done list can be scrolled isLoading = false; fullySynced = AppUtils.mPref.getBoolean(AppUtils.FULLY_SYNCED, false); //If item size is zero, there's not more files. if(items.size() == 0) { // If the adapter has no files at this point, the user might not have any files. if(getListAdapter().getCount() == 0 && fullySynced) { updateState(State.NO_FILES); } else { updateState(State.NORMAL); resetFooter(); } } else { updateState(State.NORMAL); final ArrayAdapter adapter = (ArrayAdapter) getListAdapter(); adapter.addAll(items); notifyChangeInAdapter(); resetFooter(); } } public FilesListViewAdapter getAdapter() { return adapter; } protected ArrayList<DatabaseItem> sortListByType(CloudAppItem.Type type, ArrayList<DatabaseItem> items) { ArrayList<DatabaseItem> typedList = new ArrayList<DatabaseItem>(); if(type == CloudAppItem.Type.ALL) { typedList = items; } else { for (DatabaseItem i : items) { if (i.getItemType() == type) { typedList.add(i); } } } return typedList; } protected void notifyChangeInAdapter() { if(getListAdapter() != null) { final ArrayAdapter adapter = (ArrayAdapter) getListAdapter(); adapter.notifyDataSetChanged(); } } protected void clearAdapter() { if(getListAdapter() != null) { final ArrayAdapter adapter = (ArrayAdapter) getListAdapter(); adapter.clear(); notifyChangeInAdapter(); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case SCROLL_STATE_TOUCH_SCROLL: userScrolled = true; break; case SCROLL_STATE_IDLE: userScrolled = false; break; case SCROLL_STATE_FLING: userScrolled = true; break; default: userScrolled = false; break; } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if((firstVisibleItem + visibleItemCount) >= (totalItemCount - AUTOLOAD_THRESHOLD) && !isLoading && visibleItemCount != 0 && mState != State.NO_FILES && mState != State.REFRESHING && !fullySynced && userScrolled) { if(mAutoLoad) { loadMoreFiles(); } } } public class GetAllItemsTask extends AsyncTask<Void, Void, ArrayList<DatabaseItem>> { @Override protected ArrayList<DatabaseItem> doInBackground(Void... params) { return FilesManager.getFiles(getType()); } @Override protected void onPostExecute(ArrayList<DatabaseItem> databaseItems) { addItemsToAdapter(databaseItems); } } private void loadMoreFiles() { isLoading = true; updateState(State.LOADING_MORE); FilesManager.requestMoreFiles(CloudAppItem.Type.ALL); } @Override public void onListItemClick(final ListView l, final View v, int position, long id) { if(l.getAdapter().getCount() != 0) { DatabaseItem dbItem = (DatabaseItem) l.getAdapter().getItem(position); String name = dbItem.getName(); switch (dbItem.getItemType()) { case IMAGE: Intent intent = new Intent(getActivity(), ImageViewActivity.class); intent.putExtra(EXTRA_NAME, name); startActivity(intent); break; default: Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(dbItem.getContentUrl())); startActivity(i); } } } protected void updateState(State state) { mState = state; switch(mState) { case NO_FILES: if(getListView() != null) { addHeaderView(noFiles); footerFrameLayout.setVisibility(View.GONE); } break; case REFRESHING: if(getListView() != null) { addHeaderView(refreshingFiles); if (getListView().getAdapter() != null) { clearAdapter(); } footerFrameLayout.setVisibility(View.GONE); } isLoading = true; break; case NORMAL: removeHeaderViews(); break; case LOADING_MORE: break; default: break; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); currentFragment = this; } @Override public void onDetach() { super.onDetach(); } }
package net.squanchy.tweets.service; import android.text.Html; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.URLSpan; import com.google.auto.value.AutoValue; import com.twitter.sdk.android.core.models.HashtagEntity; import com.twitter.sdk.android.core.models.MediaEntity; import com.twitter.sdk.android.core.models.MentionEntity; import com.twitter.sdk.android.core.models.Tweet; import com.twitter.sdk.android.core.models.UrlEntity; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.squanchy.support.lang.Lists; import net.squanchy.support.lang.Optional; import net.squanchy.tweets.domain.view.TweetViewModel; import net.squanchy.tweets.domain.view.User; public class TweetModelConverter { private static final String MEDIA_TYPE_PHOTO = "photo"; private static final String BASE_TWITTER_URL = "https://twitter.com/"; private static final String MENTION_URL_TEMPLATE = BASE_TWITTER_URL + "%s"; private static final String QUERY_URL_TEMPLATE = BASE_TWITTER_URL + "search?q=%s"; TweetViewModel toViewModel(Tweet tweet) { User user = User.create(tweet.user.name, tweet.user.screenName, tweet.user.profileImageUrlHttps); Range displayTextRange = Range.from(tweet.displayTextRange, tweet.text.length()); List<HashtagEntity> hashtags = onlyHashtagsInRange(tweet.entities.hashtags, displayTextRange); List<MentionEntity> mentions = onlyMentionsInRange(tweet.entities.userMentions, displayTextRange); List<UrlEntity> urls = onlyUrlsInRange(tweet.entities.urls, displayTextRange); List<String> photoUrls = onlyPhotoUrls(tweet.entities.media); String displayableText = displayableTextFor(tweet, displayTextRange); return TweetViewModel.builder() .id(tweet.id) .text(displayableText) .spannedText(applySpans(displayableText, displayTextRange.start(), hashtags, mentions, urls)) .createdAt(tweet.createdAt) .user(user) .photoUrl(photoUrlMaybeFrom(photoUrls)) .build(); } private String displayableTextFor(Tweet tweet, Range displayTextRange) { Integer beginIndex = displayTextRange.start(); Integer endIndex = displayTextRange.end(); return tweet.text.substring(beginIndex, endIndex); } private List<HashtagEntity> onlyHashtagsInRange(List<HashtagEntity> entities, Range displayTextRange) { return Lists.filter(entities, entity -> displayTextRange.contains(entity.getStart(), entity.getEnd())); } private List<MentionEntity> onlyMentionsInRange(List<MentionEntity> entities, Range displayTextRange) { return Lists.filter(entities, entity -> displayTextRange.contains(entity.getStart(), entity.getEnd())); } private List<UrlEntity> onlyUrlsInRange(List<UrlEntity> entities, Range displayTextRange) { return Lists.filter(entities, entity -> displayTextRange.contains(entity.getStart(), entity.getEnd())); } private List<String> onlyPhotoUrls(List<MediaEntity> media) { List<MediaEntity> photos = Lists.filter(media, mediaEntity -> MEDIA_TYPE_PHOTO.equals(mediaEntity.type)); return Lists.map(photos, mediaEntity -> mediaEntity.mediaUrlHttps); } private Spanned applySpans(String text, int startIndex, List<HashtagEntity> hashtags, List<MentionEntity> mentions, List<UrlEntity> urls) { SpannableStringBuilder builder = new SpannableStringBuilder(text); for (HashtagEntity hashtag : hashtags) { hashtag = offsetStart(hashtag, startIndex); builder.setSpan(createUrlSpanFor(hashtag), hashtag.getStart(), hashtag.getEnd(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } for (MentionEntity mention : mentions) { mention = offsetStart(mention, startIndex); builder.setSpan(createUrlSpanFor(mention), mention.getStart(), mention.getEnd(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } for (UrlEntity url : urls) { url = offsetStart(url, startIndex); builder.setSpan(createUrlSpanFor(url), url.getStart(), url.getEnd(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } unescapeEntities(builder); return builder; } private HashtagEntity offsetStart(HashtagEntity hashtag, int startIndex) { return new HashtagEntity( hashtag.text, hashtag.getStart() - startIndex, hashtag.getEnd() - startIndex ); } private URLSpan createUrlSpanFor(HashtagEntity hashtag) { return new URLSpan(String.format(QUERY_URL_TEMPLATE, hashtag.text)); } private MentionEntity offsetStart(MentionEntity mention, int startIndex) { return new MentionEntity( mention.id, mention.idStr, mention.name, mention.screenName, mention.getStart() - startIndex, mention.getEnd() - startIndex ); } private URLSpan createUrlSpanFor(MentionEntity mention) { return new URLSpan(String.format(MENTION_URL_TEMPLATE, mention.screenName)); } private UrlEntity offsetStart(UrlEntity url, int startIndex) { return new UrlEntity( url.url, url.expandedUrl, url.displayUrl, url.getStart() - startIndex, url.getEnd() - startIndex ); } private URLSpan createUrlSpanFor(UrlEntity url) { return new URLSpan(url.url); } private void unescapeEntities(SpannableStringBuilder builder) { String string = builder.toString(); Pattern pattern = Pattern.compile("&\\w+;"); Matcher matcher = pattern.matcher(string); while (matcher.find()) { MatchResult matchResult = matcher.toMatchResult(); Spanned unescapedEntity = Html.fromHtml(matchResult.group()); builder.replace(matchResult.start(), matchResult.end(), unescapedEntity); } } private Optional<String> photoUrlMaybeFrom(List<String> urls) { if (urls.isEmpty()) { return Optional.absent(); } return Optional.of(urls.get(0)); } @AutoValue abstract static class Range { static Range from(List<Integer> positions, int textLength) { if (positions.size() != 2) { return new AutoValue_TweetModelConverter_Range(0, textLength - 1); } return new AutoValue_TweetModelConverter_Range(positions.get(0), positions.get(1)); } abstract int start(); abstract int end(); boolean contains(int start, int end) { return start() <= start && end <= end(); } } }
package org.stepic.droid.ui.adapters; import android.support.v7.widget.AppCompatCheckBox; import android.support.v7.widget.AppCompatRadioButton; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.TextView; import org.jetbrains.annotations.NotNull; import org.stepic.droid.R; import org.stepic.droid.model.TableChoiceAnswer; import org.stepic.droid.ui.listeners.CheckedChangeListenerWithPosition; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class TableChoiceAdapter extends RecyclerView.Adapter<TableChoiceAdapter.GenericViewHolder> implements CheckedChangeListenerWithPosition { private static final int DESCRIPTION_TYPE = 0; private static final int CHECKBOX_TYPE = 1; private static final int RADIO_BUTTON_TYPE = 2; private static final int ROW_HEADER_TYPE = 3; private static final int COLUMN_HEADER_TYPE = 4; private final List<String> columns; private final List<String> rows; private final String description; private final boolean isCheckbox; private final List<TableChoiceAnswer> answers; @Override public int getItemViewType(int position) { if (position == 0) { return DESCRIPTION_TYPE; } else if (position <= rows.size()) { return ROW_HEADER_TYPE; } else if (position % (rows.size() + 1) == 0) { return COLUMN_HEADER_TYPE; } else if (isCheckbox) { return CHECKBOX_TYPE; } else { return RADIO_BUTTON_TYPE; } } public TableChoiceAdapter(List<String> rows, List<String> columns, String description, boolean isCheckbox, List<TableChoiceAnswer> answers) { this.columns = columns; this.rows = rows; this.description = description; this.isCheckbox = isCheckbox; this.answers = answers; int i = 0; } @Override public GenericViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == RADIO_BUTTON_TYPE) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_table_quiz_radio_button_cell, parent, false); return new RadioButtonCellViewHolder(v, this); } else if (viewType == CHECKBOX_TYPE) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_table_quiz_checkbox_cell, parent, false); return new CheckboxCellViewHolder(v, this); } else if (viewType == DESCRIPTION_TYPE || viewType == ROW_HEADER_TYPE || viewType == COLUMN_HEADER_TYPE) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_table_quiz_text_cell, parent, false); return new DescriptionViewHolder(v); } else { throw new IllegalStateException("viewType with index " + viewType + " is not supported in table quiz"); } } @Override public void onBindViewHolder(GenericViewHolder holder, int position) { int itemViewType = getItemViewType(position); if (itemViewType == DESCRIPTION_TYPE) { holder.setData(description); } else if (itemViewType == ROW_HEADER_TYPE) { String headerText = rows.get(position - 1); holder.setData(headerText); } else if (itemViewType == COLUMN_HEADER_TYPE) { int columnPosition = getColumnPosition(position); // -1 is description cell at top left cell String headerText = columns.get(columnPosition); holder.setData(headerText); } else { List<TableChoiceAnswer.Companion.Cell> oneRowAnswers = getOneRowAnswersFromPosition(position); int columnPosition = getColumnPosition(position); TableChoiceAnswer.Companion.Cell cell = oneRowAnswers.get(columnPosition); holder.setData(cell.getAnswer()); } } private int getColumnPosition(int position) { return position / (rows.size() + 1) - 1; } private List<TableChoiceAnswer.Companion.Cell> getOneRowAnswersFromPosition(int position) { int rowPosition = (position - 1) % (rows.size() + 1); TableChoiceAnswer tableChoiceAnswer = answers.get(rowPosition); return tableChoiceAnswer.getColumns(); } @Override public int getItemCount() { return rows.size() + columns.size() + 1 + rows.size() * columns.size(); } @Override public void onCheckedChanged(CompoundButton view, boolean isChecked, int position) { List<TableChoiceAnswer.Companion.Cell> oneRowAnswers = getOneRowAnswersFromPosition(position); int columnPosition = getColumnPosition(position); int multiplier = rows.size() + 1; int remainder = position % multiplier; List<Integer> changed = new ArrayList<>(); if (!isCheckbox && isChecked) { //radio button, check something -> uncheck others int i = 1; for (TableChoiceAnswer.Companion.Cell eachCellInRow : oneRowAnswers) { if (eachCellInRow.getAnswer()) { //if something is checked int currentAdapterPosition = multiplier * i + remainder; eachCellInRow.setAnswer(false); if (currentAdapterPosition != position) { changed.add(currentAdapterPosition); } } i++; } } // change checked state TableChoiceAnswer.Companion.Cell cell = oneRowAnswers.get(columnPosition); cell.setAnswer(isChecked); if (!changed.isEmpty()) { for (Integer changedPosition : changed) { notifyItemChanged(changedPosition); // In the perfect world there is only one for radiobutton } } } static abstract class GenericViewHolder extends RecyclerView.ViewHolder { public GenericViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } public abstract void setData(@NotNull String text); public abstract void setData(@NotNull Boolean needCheckModel); } static class DescriptionViewHolder extends GenericViewHolder { @BindView(R.id.cell_text) TextView textView; public DescriptionViewHolder(View itemView) { super(itemView); } @Override public void setData(@NotNull String text) { textView.setText(text); } @Override public void setData(@NotNull Boolean needCheck) { throw new IllegalStateException("description view can't be without text, check position"); } } static abstract class CompoundButtonViewHolder extends GenericViewHolder { public CompoundButtonViewHolder(View itemView, final CheckedChangeListenerWithPosition checkedChangeListenerWithPosition) { super(itemView); getCheckableView().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView.isPressed()) { checkedChangeListenerWithPosition.onCheckedChanged(buttonView, isChecked, getAdapterPosition()); } } }); } @Override public final void setData(@NotNull String text) { throw new IllegalStateException("text is not allowed in table view quiz"); } @Override public final void setData(@NotNull Boolean needCheckModel) { getCheckableView().setChecked(needCheckModel); } abstract CompoundButton getCheckableView(); } static class CheckboxCellViewHolder extends CompoundButtonViewHolder { @BindView(R.id.checkbox_cell) AppCompatCheckBox checkBox; public CheckboxCellViewHolder(View itemView, CheckedChangeListenerWithPosition checkedChangeListenerWithPosition) { super(itemView, checkedChangeListenerWithPosition); } @Override CompoundButton getCheckableView() { return checkBox; } } static class RadioButtonCellViewHolder extends CompoundButtonViewHolder { @BindView(R.id.radio_button_cell) AppCompatRadioButton radioButton; public RadioButtonCellViewHolder(View itemView, final CheckedChangeListenerWithPosition checkedChangeListenerWithPosition) { super(itemView, checkedChangeListenerWithPosition); } @Override CompoundButton getCheckableView() { return radioButton; } } }
package org.wikipedia.page.leadimages; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.PointF; import android.location.Location; import android.support.annotation.ColorInt; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.text.Html; import android.text.TextUtils; import android.util.TypedValue; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.R; import org.wikipedia.analytics.GalleryFunnel; import org.wikipedia.page.Page; import org.wikipedia.page.PageTitle; import org.wikipedia.WikipediaApp; import org.wikipedia.bridge.CommunicationBridge; import org.wikipedia.page.PageFragment; import org.wikipedia.page.gallery.GalleryActivity; import org.wikipedia.savedpages.DeleteSavedPageTask; import org.wikipedia.savedpages.SavePageTask; import org.wikipedia.savedpages.SavedPage; import org.wikipedia.util.DimenUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.ShareUtil; import org.wikipedia.util.UriUtil; import org.wikipedia.views.ArticleHeaderView; import org.wikipedia.views.ArticleMenuBarView; import org.wikipedia.views.ObservableWebView; import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx; public class LeadImagesHandler { /** * Minimum screen height for enabling lead images. If the screen is smaller than * this height, lead images will not be displayed, and will be substituted with just * the page title. */ private static final int MIN_SCREEN_HEIGHT_DP = 480; /** * Maximum height of the page title text. If the text overflows this size, then the * font size of the title will be automatically reduced to fit. */ private static final int TITLE_MAX_HEIGHT_DP = 256; /** * Minimum font size of the page title. Will not be reduced any further than this. */ private static final int TITLE_MIN_TEXT_SIZE_SP = 12; /** * Amount by which the page title font will be reduced, for each step of the * reduction process. */ private static final int TITLE_TEXT_SIZE_DECREMENT_SP = 4; public interface OnLeadImageLayoutListener { void onLayoutComplete(int sequence); } @NonNull private final PageFragment parentFragment; @NonNull private final CommunicationBridge bridge; @NonNull private final ObservableWebView webView; @NonNull private final ArticleHeaderView articleHeaderView; private View image; private int displayHeightDp; private float faceYOffsetNormalized; private float displayDensity; public LeadImagesHandler(@NonNull final PageFragment parentFragment, @NonNull CommunicationBridge bridge, @NonNull ObservableWebView webView, @NonNull ArticleHeaderView articleHeaderView) { this.articleHeaderView = articleHeaderView; this.articleHeaderView.setMenuBarCallback(new MenuBarCallback()); this.parentFragment = parentFragment; this.bridge = bridge; this.webView = webView; image = articleHeaderView.getImage(); initDisplayDimensions(); initWebView(); initArticleHeaderView(); // hide ourselves by default hide(); } /** * Completely hide the lead image view. Useful in case of network errors, etc. * The only way to "show" the lead image view is by calling the beginLayout function. */ public void hide() { articleHeaderView.hide(); } @Nullable public Bitmap getLeadImageBitmap() { return isLeadImageEnabled() ? articleHeaderView.copyImage() : null; } public boolean isLeadImageEnabled() { String thumbUrl = getLeadImageUrl(); if (!WikipediaApp.getInstance().isImageDownloadEnabled() || displayHeightDp < MIN_SCREEN_HEIGHT_DP) { // disable the lead image completely return false; } else { // Enable only if the image is not a GIF, since GIF images are usually mathematical // diagrams or animations that won't look good as a lead image. // TODO: retrieve the MIME type of the lead image, instead of relying on file name. return thumbUrl != null && !thumbUrl.endsWith(".gif"); } } public void updateBookmark(boolean bookmarkSaved) { articleHeaderView.updateBookmark(bookmarkSaved); } public void updateNavigate(@Nullable Location geo) { articleHeaderView.updateNavigate(geo != null); } /** * Returns the normalized (0.0 to 1.0) vertical focus position of the lead image. * A value of 0.0 represents the top of the image, and 1.0 represents the bottom. * The "focus position" is currently defined by automatic face detection, but may be * defined by other factors in the future. * * @return Normalized vertical focus position. */ public float getLeadImageFocusY() { return faceYOffsetNormalized; } /** * Triggers a chain of events that will lay out the lead image, page title, and other * elements, at the end of which the WebView contents may begin to be composed. * These events (performed asynchronously) are in the following order: * - Dynamically resize the page title TextView and, if necessary, adjust its font size * based on the length of our page title. * - Dynamically resize the lead image container view and restyle it, if necessary, depending * on whether the page contains a lead image, and whether our screen resolution is high * enough to warrant a lead image. * - Send a "padding" event to the WebView so that any subsequent content that's added to it * will be correctly offset to account for the lead image view (or lack of it) * - Make the lead image view visible. * - Fire a callback to the provided Listener indicating that the rest of the WebView content * can now be loaded. * - Fetch and display the WikiData description for this page, if available. * <p/> * Realistically, the whole process will happen very quickly, and almost unnoticeably to the * user. But it still needs to be asynchronous because we're dynamically laying out views, and * because the padding "event" that we send to the WebView must come before any other content * is sent to it, so that the effect doesn't look jarring to the user. * * @param listener Listener that will receive an event when the layout is completed. */ public void beginLayout(OnLeadImageLayoutListener listener, int sequence) { if (getPage() == null) { return; } initDisplayDimensions(); // set the page title text, and honor any HTML formatting in the title loadLeadImage(); articleHeaderView.setTitle(Html.fromHtml(getPage().getDisplayTitle())); articleHeaderView.setLocale(getPage().getTitle().getSite().getLanguageCode()); articleHeaderView.setPronunciation(getPage().getTitlePronunciationUrl()); // Set the subtitle, too, so text measurements are accurate. layoutWikiDataDescription(getTitle().getDescription()); // kick off the (asynchronous) laying out of the page title text layoutPageTitle((int) (getDimension(R.dimen.titleTextSize) / displayDensity), listener, sequence); } /** * Intermediate step in the layout process: * Recursive function that will dynamically size down the page title TextView if the page title * is too long. Since it's assumed that the overall lead image view is hidden at this stage, * this process will be invisible to the user, and will not appear jarring. Once the optimal * font size is reached, the next step in the layout process is triggered. * * @param fontSizeSp Font size to be tested. * @param listener Listener that will receive an event when the layout is completed. */ private void layoutPageTitle(final int fontSizeSp, final OnLeadImageLayoutListener listener, final int sequence) { if (!isFragmentAdded()) { return; } // set the font size of the title articleHeaderView.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp); // if we're still not being shown (if the fragment is still being created), // then retry after a delay. if (articleHeaderView.getTextHeight() == 0) { final int postDelay = 50; articleHeaderView.postDelayed(new Runnable() { @Override public void run() { layoutPageTitle(fontSizeSp, listener, sequence); } }, postDelay); } else { // give it a chance to redraw, and then see if it fits articleHeaderView.post(new Runnable() { @Override public void run() { if (!isFragmentAdded()) { return; } if (((int) (articleHeaderView.getTextHeight() / displayDensity) > TITLE_MAX_HEIGHT_DP) && (fontSizeSp > TITLE_MIN_TEXT_SIZE_SP)) { int newSize = fontSizeSp - TITLE_TEXT_SIZE_DECREMENT_SP; if (newSize < TITLE_MIN_TEXT_SIZE_SP) { newSize = TITLE_MIN_TEXT_SIZE_SP; } layoutPageTitle(newSize, listener, sequence); } else { // we're done! layoutViews(listener, sequence); } } }); } } /** * The final step in the layout process: * Apply sizing and styling to our page title and lead image views, based on how large our * page title ended up, and whether we should display the lead image. * * @param listener Listener that will receive an event when the layout is completed. */ private void layoutViews(OnLeadImageLayoutListener listener, int sequence) { if (!isFragmentAdded()) { return; } if (isMainPage()) { articleHeaderView.hide(); } else { if (!isLeadImageEnabled()) { articleHeaderView.showText(); } else { articleHeaderView.showTextImage(); } } // tell our listener that it's ok to start loading the rest of the WebView content listener.onLayoutComplete(sequence); } private void updatePadding() { int padding; if (isMainPage()) { padding = Math.round(getContentTopOffsetPx(getActivity()) / displayDensity); } else { padding = Math.round(articleHeaderView.getHeight() / displayDensity); } setWebViewPaddingTop(padding); } private void setWebViewPaddingTop(int padding) { JSONObject payload = new JSONObject(); try { payload.put("paddingTop", padding); } catch (JSONException e) { throw new RuntimeException(e); } bridge.sendMessage("setPaddingTop", payload); } /** * Final step in the WikiData description process: lay out the description, and animate it * into place, along with the page title. * * @param description WikiData description to be shown. */ private void layoutWikiDataDescription(@Nullable final String description) { if (TextUtils.isEmpty(description)) { articleHeaderView.setSubtitle(null); } else { int titleLineCount = articleHeaderView.getLineCount(); articleHeaderView.setSubtitle(description); // Only show the description if it's two lines or less. if ((articleHeaderView.getLineCount() - titleLineCount) > 2) { articleHeaderView.setSubtitle(null); } } } /** * Determines and sets displayDensity and displayHeightDp for the lead images layout. */ private void initDisplayDimensions() { // preload the display density, since it will be used in a lot of places displayDensity = DimenUtil.getDensityScalar(); int displayHeightPx = DimenUtil.getDisplayHeightPx(); displayHeightDp = (int) (displayHeightPx / displayDensity); } private void loadLeadImage() { loadLeadImage(getLeadImageUrl()); } private void loadLeadImage(@Nullable String url) { if (!isMainPage() && !TextUtils.isEmpty(url) && isLeadImageEnabled()) { String fullUrl = WikipediaApp.getInstance().getNetworkProtocol() + ":" + url; articleHeaderView.setImageYScalar(0); articleHeaderView.loadImage(fullUrl); } else { articleHeaderView.loadImage(null); } } @Nullable private String getLeadImageUrl() { return getPage() == null ? null : getPage().getPageProperties().getLeadImageUrl(); } @Nullable private Location getGeo() { return getPage() == null ? null : getPage().getPageProperties().getGeo(); } private void startKenBurnsAnimation() { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.lead_image_zoom); image.startAnimation(anim); } private void initArticleHeaderView() { articleHeaderView.setOnImageLoadListener(new ImageLoadListener()); articleHeaderView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override @SuppressWarnings("checkstyle:parameternumber") public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { updatePadding(); } }); } private void initWebView() { webView.addOnScrollChangeListener(articleHeaderView); webView.addOnClickListener(new ObservableWebView.OnClickListener() { @Override public boolean onClick(float x, float y) { // if the click event is within the area of the lead image, then the user // must have wanted to click on the lead image! if (getPage() != null && isLeadImageEnabled() && y < (articleHeaderView.getHeight() - webView.getScrollY())) { String imageName = getPage().getPageProperties().getLeadImageName(); if (imageName != null) { PageTitle imageTitle = new PageTitle("File:" + imageName, getTitle().getSite()); GalleryActivity.showGallery(getActivity(), parentFragment.getTitleOriginal(), imageTitle, GalleryFunnel.SOURCE_LEAD_IMAGE); } return true; } return false; } }); } private boolean isMainPage() { return getPage() != null && getPage().isMainPage(); } private PageTitle getTitle() { return parentFragment.getTitle(); } @Nullable private Page getPage() { return parentFragment.getPage(); } private boolean isFragmentAdded() { return parentFragment.isAdded(); } private float getDimension(@DimenRes int id) { return getResources().getDimension(id); } private Resources getResources() { return getActivity().getResources(); } private FragmentActivity getActivity() { return parentFragment.getActivity(); } private class MenuBarCallback extends ArticleMenuBarView.DefaultCallback { @Override public void onBookmarkClick(boolean bookmarkSaved) { if (getPage() == null) { return; } if (bookmarkSaved) { saveBookmark(); } else { deleteBookmark(); } } @Override public void onShareClick() { if (getPage() != null) { ShareUtil.shareText(getActivity(), getPage().getTitle()); } } @Override public void onNavigateClick() { openGeoIntent(); } private void saveBookmark() { WikipediaApp.getInstance().getFunnelManager().getSavedPagesFunnel(getTitle().getSite()).logSaveNew(); FeedbackUtil.showMessage(getActivity(), R.string.snackbar_saving_page); new SavePageTask(WikipediaApp.getInstance(), getTitle(), getPage()) { @Override public void onFinish(Boolean success) { if (parentFragment.isAdded() && getTitle() != null) { parentFragment.setPageSaved(!success); FeedbackUtil.showMessage(getActivity(), getActivity().getString(success ? R.string.snackbar_saved_page_format : R.string.snackbar_saved_page_missing_images, getTitle().getDisplayText())); } } }.execute(); } private void deleteBookmark() { new DeleteSavedPageTask(getActivity(), new SavedPage(getTitle())) { @Override public void onFinish(Boolean success) { WikipediaApp.getInstance().getFunnelManager().getSavedPagesFunnel(getTitle().getSite()).logDelete(); if (parentFragment.isAdded()) { parentFragment.setPageSaved(!success); if (success) { FeedbackUtil.showMessage(getActivity(), R.string.snackbar_saved_page_deleted); } } } }.execute(); } private void openGeoIntent() { if (getGeo() != null) { UriUtil.sendGeoIntent(getActivity(), getGeo(), getTitle().getDisplayText()); } } } private class ImageLoadListener implements ImageViewWithFace.OnImageLoadListener { @Override public void onImageLoaded(Bitmap bitmap, @Nullable final PointF faceLocation, @ColorInt final int mainColor) { final int bmpHeight = bitmap.getHeight(); articleHeaderView.post(new Runnable() { @Override public void run() { if (isFragmentAdded()) { detectFace(bmpHeight, faceLocation); articleHeaderView.setMenuBarColor(mainColor); } } }); } @Override public void onImageFailed() { articleHeaderView.resetMenuBarColor(); } private void detectFace(int bmpHeight, @Nullable PointF faceLocation) { faceYOffsetNormalized = faceYScalar(bmpHeight, faceLocation); float scalar = constrainScalar(faceYOffsetNormalized); articleHeaderView.setImageYScalar(scalar); // fade in the new image! articleHeaderView.crossFadeImage(); startKenBurnsAnimation(); } private float constrainScalar(float scalar) { scalar = Math.max(0, scalar); scalar = Math.min(scalar, 1); return scalar; } private float faceYScalar(int bmpHeight, @Nullable PointF faceLocation) { final float defaultOffsetScalar = .25f; float scalar = defaultOffsetScalar; if (faceLocation != null) { scalar = faceLocation.y / bmpHeight; // TODO: if it is desirable to offset to the nose, replace this arbitrary hardcoded // value with a proportion. FaceDetector.eyesDistance() presumably provides // the interpupillary distance in pixels. We can multiply this measurement by // the proportion of the length of the nose to the IPD. scalar += getDimension(R.dimen.face_detection_nose_y_offset) / bmpHeight; } return scalar; } } }
package net.i2p.router.web; import java.io.File; import java.io.IOException; import java.io.Writer; import net.i2p.router.RouterContext; /** * Refactored from summarynoframe.jsp to save ~100KB * */ public class SummaryBarRenderer { private RouterContext _context; private SummaryHelper _helper; public SummaryBarRenderer(RouterContext context, SummaryHelper helper) { _context = context; _helper = helper; } public void renderSummaryHTML(Writer out) throws IOException { StringBuilder buf = new StringBuilder(8*1024); buf.append("<a href=\"index.jsp\" target=\"_top\"><img src=\"/themes/console/images/i2plogo.png\" alt=\"") .append(_("I2P Router Console")) .append("\" title=\"") .append(_("I2P Router Console")) .append("\"></a><hr>"); File lpath = new File(_context.getBaseDir(), "docs/toolbar.html"); // you better have target="_top" for the links in there... if (lpath.exists()) { ContentHelper linkhelper = new ContentHelper(); linkhelper.setPage(lpath.getAbsolutePath()); linkhelper.setMaxLines("100"); buf.append(linkhelper.getContent()); } else { buf.append("<h3><a href=\"/configclients.jsp\" target=\"_top\" title=\"") .append(_("Configure startup of clients and webapps (services); manually start dormant services")) .append("\">") .append(_("I2P Services")) .append("</a></h3>\n" + "<hr><table>" + "<tr><td><a href=\"susidns/index.jsp\" target=\"_blank\" title=\"") .append(_("Manage your I2P hosts file here (I2P domain name resolution)")) .append("\">") .append(_("Addressbook")) .append("</a>\n" + "<a href=\"i2psnark/\" target=\"_blank\" title=\"") .append(_("Built-in anonymous BitTorrent Client")) .append("\">") .append(_("Torrents")) .append("</a>\n" + "<a href=\"susimail/susimail\" target=\"blank\" title=\"") .append(_("Anonymous webmail client")) .append("\">") .append(_("Webmail")) .append("</a>\n" + "<a href=\"http://127.0.0.1:7658/\" target=\"_blank\" title=\"") .append(_("Anonymous resident webserver")) .append("\">") .append(_("Webserver")) .append("</a></td></tr></table>\n" + "<hr><h3><a href=\"config.jsp\" target=\"_top\" title=\"") .append(_("Configure I2P Router")) .append("\">") .append(_("I2P Internals")) .append("</a></h3><hr>\n" + "<table><tr><td>\n" + "<a href=\"tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels")) .append("</a>\n" + "<a href=\"peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a>\n" + "<a href=\"profiles.jsp\" target=\"_top\" title=\"") .append(_("Show recent peer performance profiles")) .append("\">") .append(_("Profiles")) .append("</a>\n" + "<a href=\"netdb.jsp\" target=\"_top\" title=\"") .append(_("Show list of all known I2P routers")) .append("\">") .append(_("NetDB")) .append("</a>\n" + "<a href=\"logs.jsp\" target=\"_top\" title=\"") .append(_("Health Report")) .append("\">") .append(_("Logs")) .append("</a>\n" + "<a href=\"jobs.jsp\" target=\"_top\" title=\"") .append(_("Show the router's workload, and how it's performing")) .append("\">") .append(_("Jobs")) .append("</a>\n" + "<a href=\"graphs.jsp\" target=\"_top\" title=\"") .append(_("Graph router performance")) .append("\">") .append(_("Graphs")) .append("</a>\n" + "<a href=\"oldstats.jsp\" target=\"_top\" title=\"") .append(_("Textual router performance statistics")) .append("\">") .append(_("Stats")) .append("</a></td></tr></table>\n"); out.write(buf.toString()); buf.setLength(0); } buf.append("<hr><h3><a href=\"help.jsp\" target=\"_top\" title=\"") .append(_("I2P Router Help")) .append("\">") .append(_("General")) .append("</a></h3><hr>" + "<h4><a title=\"") .append(_("Your unique I2P router identity is")) .append(' ') .append(_helper.getIdent()) .append(", ") .append(_("never reveal it to anyone")) .append("\" href=\"netdb.jsp?r=.\" target=\"_top\">") .append(_("Local Identity")) .append("</a></h4><hr>\n" + "<table><tr><td align=\"left\">" + "<b>") .append(_("Version")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getVersion()) .append("</td></tr>\n" + "<tr title=\"") .append(_("How long we've been running for this session")) .append("\">" + "<td align=\"left\"><b>") .append(_("Uptime")) .append(":</b></td>" + "<td align=\"right\">") .append(_helper.getUptime()) .append("</td></tr></table>\n" + "<hr><h4><a href=\"config.jsp#help\" target=\"_top\" title=\"") .append(_("Help with configuring your firewall and router for optimal I2P performance")) .append("\">") .append(_helper.getReachability()) .append("</a></h4><hr>\n"); if (_helper.updateAvailable() || _helper.unsignedUpdateAvailable()) { // display all the time so we display the final failure message buf.append("<br>").append(UpdateHandler.getStatus()); if ("true".equals(System.getProperty("net.i2p.router.web.UpdateHandler.updateInProgress"))) { // nothing } else if( // isDone() is always false for now, see UpdateHandler // ((!update.isDone()) && _helper.getAction() == null && _helper.getUpdateNonce() == null && ConfigRestartBean.getRestartTimeRemaining() > 12*60*1000) { long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.UpdateHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.UpdateHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.UpdateHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"updateNonce\" value=\"").append(nonce).append("\" >\n"); if (_helper.updateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"signed\" >") .append(_("Download")) .append(' ') .append(_helper.getUpdateVersion()) .append(' ') .append(_("Update")) .append("</button>\n"); } if (_helper.unsignedUpdateAvailable()) { buf.append("<button type=\"submit\" name=\"updateAction\" value=\"Unsigned\" >") .append(_("Download Unsigned")) .append("<br>") .append(_("Update")) .append(' ') .append(_helper.getUnsignedUpdateVersion()) .append("</button>\n"); } buf.append("</form>\n"); } } buf.append("<p>") .append(ConfigRestartBean.renderStatus(_helper.getRequestURI(), _helper.getAction(), _helper.getConsoleNonce())) .append("</p><hr><h3><a href=\"peers.jsp\" target=\"_top\" title=\"") .append(_("Show all current peer connections")) .append("\">") .append(_("Peers")) .append("</a></h3><hr>\n" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Active")) .append(":</b></td><td align=\"right\">") .append(_helper.getActivePeers()) .append('/') .append(_helper.getActiveProfiles()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Fast")) .append(":</b></td><td align=\"right\">") .append(_helper.getFastPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("High capacity")) .append(":</b></td><td align=\"right\">") .append(_helper.getHighCapacityPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Integrated")) .append(":</b></td><td align=\"right\">") .append(_helper.getWellIntegratedPeers()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Known")) .append(":</b></td><td align=\"right\">") .append(_helper.getAllPeers()) .append("</td></tr>\n" + "</table><hr>\n"); out.write(buf.toString()); buf.setLength(0); boolean anotherLine = false; if (_helper.showFirewallWarning()) { buf.append("<h4><a href=\"config.jsp\" target=\"_top\" title=\"") .append(_("Help with firewall configuration")) .append("\">") .append(_("Check NAT/firewall")) .append("</a></h4>"); anotherLine = true; } boolean reseedInProgress = Boolean.valueOf(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress")).booleanValue(); // If showing the reseed link is allowed if (_helper.allowReseed()) { if (reseedInProgress) { // While reseed occurring, show status message instead buf.append("<i>").append(System.getProperty("net.i2p.router.web.ReseedHandler.statusMessage","")).append("</i><br>"); } else { // While no reseed occurring, show reseed link long nonce = _context.random().nextLong(); String prev = System.getProperty("net.i2p.router.web.ReseedHandler.nonce"); if (prev != null) System.setProperty("net.i2p.router.web.ReseedHandler.noncePrev", prev); System.setProperty("net.i2p.router.web.ReseedHandler.nonce", nonce+""); String uri = _helper.getRequestURI(); buf.append("<form action=\"").append(uri).append("\" method=\"GET\">\n"); buf.append("<input type=\"hidden\" name=\"reseedNonce\" value=\"").append(nonce).append("\" >\n"); buf.append("<button type=\"submit\" value=\"Reseed\" >").append(_("Reseed")).append("</button></form>\n"); } anotherLine = true; } // If a new reseed ain't running, and the last reseed had errors, show error message if (!reseedInProgress) { String reseedErrorMessage = System.getProperty("net.i2p.router.web.ReseedHandler.errorMessage",""); if (reseedErrorMessage.length() > 0) { buf.append("<i>").append(reseedErrorMessage).append("</i><br>"); anotherLine = true; } } if (anotherLine) buf.append("<hr>"); buf.append("<h3><a href=\"config.jsp\" title=\"") .append(_("Configure router bandwidth allocation")) .append("\" target=\"_top\">") .append(_("Bandwidth in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>1s:</b></td><td align=\"right\">") .append(_helper.getInboundSecondKBps()) .append('/') .append(_helper.getOutboundSecondKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>5m:</b></td><td align=\"right\">") .append(_helper.getInboundFiveMinuteKBps()) .append('/') .append(_helper.getOutboundFiveMinuteKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Total")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundLifetimeKBps()) .append('/') .append(_helper.getOutboundLifetimeKBps()) .append("K/s</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Used")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTransferred()) .append('/') .append(_helper.getOutboundTransferred()) .append("</td></tr></table>\n" + "<hr><h3><a href=\"tunnels.jsp\" target=\"_top\" title=\"") .append(_("View existing tunnels and tunnel build status")) .append("\">") .append(_("Tunnels in/out")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Exploratory")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundTunnels()) .append('/') .append(_helper.getOutboundTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Client")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundClientTunnels()) .append('/') .append(_helper.getOutboundClientTunnels()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Participating")) .append(":</b></td><td align=\"right\">") .append(_helper.getParticipatingTunnels()) .append("</td></tr>\n" + "</table><hr><h3><a href=\"/jobs.jsp\" target=\"_top\" title=\"") .append(_("What's in the router's job queue?")) .append("\">") .append(_("Congestion")) .append("</a></h3><hr>" + "<table>\n" + "<tr><td align=\"left\"><b>") .append(_("Job lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getJobLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Message delay")) .append(":</b></td><td align=\"right\">") .append(_helper.getMessageDelay()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Tunnel lag")) .append(":</b></td><td align=\"right\">") .append(_helper.getTunnelLag()) .append("</td></tr>\n" + "<tr><td align=\"left\"><b>") .append(_("Backlog")) .append(":</b></td><td align=\"right\">") .append(_helper.getInboundBacklog()) .append("</td></tr>\n" + "</table><hr><h4>") .append(_helper.getTunnelStatus()) .append("</h4><hr>\n") .append(_helper.getDestinations()); out.write(buf.toString()); } /** translate a string */ private String _(String s) { return Messages.getString(s, _context); } }
package com.ardverk.dht.io; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.TimeUnit; import org.ardverk.collection.Iterators; import org.ardverk.concurrent.AsyncFuture; import org.ardverk.lang.Arguments; import com.ardverk.dht.config.StoreConfig; import com.ardverk.dht.entity.DefaultStoreEntity; import com.ardverk.dht.entity.StoreEntity; import com.ardverk.dht.message.MessageFactory; import com.ardverk.dht.message.ResponseMessage; import com.ardverk.dht.message.StoreRequest; import com.ardverk.dht.message.StoreResponse; import com.ardverk.dht.routing.Contact; import com.ardverk.dht.storage.ValueTuple; public class StoreResponseHandler extends AbstractResponseHandler<StoreEntity> { private final ProcessCounter counter; private final List<StoreResponse> responses = new ArrayList<StoreResponse>(); private final Iterator<Contact> contacts; private final int k; private final ValueTuple tuple; private final StoreConfig config; private long startTime = -1L; public StoreResponseHandler( MessageDispatcher messageDispatcher, Contact[] contacts, int k, ValueTuple tuple, StoreConfig config) { super(messageDispatcher); this.contacts = Iterators.fromArray(contacts); this.k = k; this.tuple = Arguments.notNull(tuple, "tuple"); this.config = Arguments.notNull(config, "config"); counter = new ProcessCounter(config.getS()); } @Override protected void go(AsyncFuture<StoreEntity> future) throws Exception { process(0); } private synchronized void process(int pop) throws IOException { try { preProcess(pop); while (counter.hasNext() && counter.getCount() < k) { if (!contacts.hasNext()) { break; } Contact contact = contacts.next(); store(contact); counter.increment(); } } finally { postProcess(); } } private synchronized void preProcess(int pop) { if (startTime == -1L) { startTime = System.currentTimeMillis(); } while (0 < pop counter.decrement(); } } private synchronized void postProcess() { if (counter.getProcesses() == 0) { long time = System.currentTimeMillis() - startTime; StoreResponse[] values = responses.toArray(new StoreResponse[0]); if (values.length == 0) { setException(new StoreException(tuple, time, TimeUnit.MILLISECONDS)); } else { setValue(new DefaultStoreEntity(values, time, TimeUnit.MILLISECONDS)); } } } private synchronized void store(Contact dst) throws IOException { MessageFactory factory = messageDispatcher.getMessageFactory(); StoreRequest request = factory.createStoreRequest(dst, tuple); long defaultTimeout = config.getStoreTimeoutInMillis(); long adaptiveTimeout = config.getAdaptiveTimeout( dst, defaultTimeout, TimeUnit.MILLISECONDS); send(dst, request, adaptiveTimeout, TimeUnit.MILLISECONDS); } @Override protected synchronized void processResponse(RequestEntity entity, ResponseMessage response, long time, TimeUnit unit) throws IOException { StoreResponse message = (StoreResponse)response; try { responses.add(message); } finally { process(1); } } @Override protected synchronized void processTimeout(RequestEntity entity, long time, TimeUnit unit) throws IOException { process(1); } }
package es.sandwatch.trim; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Main project class. * * @author Ismael Alonso * @version 1.0.0 */ public class Trim{ /** * Triggers the analysis. * * @param spec the ApiSpecification object containing all API and model information. * @return the report object. */ public static Report run(ApiSpecification spec){ Trim trim = new Trim(spec); return trim.run(); } private ApiSpecification spec; private HttpClient client; /** * Constructor. * * @param spec the ApiSpecification object containing all API and model information. */ private Trim(ApiSpecification spec){ this.spec = spec; } /** * Runs the analysis. * * @return the report object. */ private Report run(){ //Add all generic headers to all endpoints for (Endpoint endpoint:spec.getEndpoints()){ for (String header:spec.getHeaders().keySet()){ endpoint.addHeader(header, spec.getHeaders().get(header)); } } //Create the http client and the report objects client = HttpClientBuilder.create().build(); Report report = new Report(); //Execute the requests to endpoints for (Endpoint endpoint:spec.getEndpoints()){ RequestResult result = getEndpointData(endpoint); Report.EndpointReport endpointReport = report.addEndpointReport(endpoint, result); //If successful if (result.is2xx()){ //Parse the response and create the usage map and the field list Set<String> keys = getJsonAttributeSet(result.getResponse()); if (keys == null){ endpointReport.setResponseFormatError(); } else { //Create and populate the field list List<Field> fields = new ArrayList<>(); getFieldsOf(endpoint.getModel(), fields); for (Field field:fields){ //Extract the serialized name of the field, annotation overrides field name AttributeName annotation = field.getAnnotation(AttributeName.class); String attributeName; if (annotation == null){ attributeName = field.getName(); } else{ attributeName = annotation.value(); } //Determine if it exists in the API response if (keys.contains(attributeName)){ endpointReport.addAttributeReport(attributeName, true); keys.remove(attributeName); } } //The rest of the fields in the keys set are not used in the model for (String key:keys){ endpointReport.addAttributeReport(key, false); } } } } return report; } /** * Hits an endpoint and returns the result. * * @param endpoint the endpoint to hit. * @return a bundle containing request code and result */ private RequestResult getEndpointData(Endpoint endpoint){ //Create the request and add all the headers HttpGet request = new HttpGet(endpoint.getUrl()); for (String header:endpoint.getHeaders().keySet()){ request.addHeader(header, endpoint.getHeaders().get(header)); } RequestResult result = null; BufferedReader reader = null; try{ //Execute the request and create the reader HttpResponse response = client.execute(request); reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); //Fetch the result StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null){ stringBuilder.append(line); } //Create the result bundle result = new RequestResult(response.getStatusLine().getStatusCode(), stringBuilder.toString()); } catch (IOException iox){ iox.printStackTrace(); } finally{ if (reader != null){ try{ reader.close(); } catch (IOException iox){ iox.printStackTrace(); } } } //If there is no result, something went south if (result == null){ result = new RequestResult(); } return result; } /** * Turns a string returned by an API endpoint into a Set of attributes. * * @param src the source string. * @return the parsed set of attributes or null if src couldn't be interpreted. */ private Set<String> getJsonAttributeSet(String src){ Set<String> fieldSet = new HashSet<>(); try{ JSONObject object = new JSONObject(src); Iterator<String> keys = object.keys(); while (keys.hasNext()){ fieldSet.add(keys.next()); } } catch (JSONException jx){ jx.printStackTrace(); return null; } return fieldSet; } /** * Gathers all the fields declared and inherited by a class until the immediate child of Object. * * @param targetClass the class from which the fields are to be extracted. * @param targetList the list where the fields are to be gathered. */ private void getFieldsOf(Class<?> targetClass, List<Field> targetList){ if (!targetClass.equals(Object.class)){ targetList.addAll(Arrays.asList(targetClass.getDeclaredFields())); getFieldsOf(targetClass.getSuperclass(), targetList); } } /** * Class containing the relevant information about the result of an HTTP request. * * @author Ismael Alonso * @version 1.0.0 */ class RequestResult{ private int statusCode; private String response; /** * Constructor. Call if the request failed. */ private RequestResult(){ this(-1, "Request failed"); } /** * Constructor. Call if the request got through to the server. * * @param statusCode the status code of the request. * @param response the response to the request. */ private RequestResult(int statusCode, String response){ this.statusCode = statusCode; this.response = response; } /** * Tells whether the request failed before it was sent. * * @return true if the request failed, false otherwise. */ boolean requestFailed(){ return statusCode == -1; } /** * Tells whether the request yielded a 2xx status code. * * @return true if the request yielded a 2xx status code, false otherwise. */ boolean is2xx(){ return statusCode >= 200 && statusCode < 300; } /** * Tells whether the request yielded a 3xx status code. * * @return true if the request yielded a 3xx status code, false otherwise. */ boolean is3xx(){ return statusCode >= 300 && statusCode < 400; } /** * Tells whether the request yielded a 4xx status code. * * @return true if the request yielded a 4xx status code, false otherwise. */ boolean is4xx(){ return statusCode >= 400 && statusCode < 500; } /** * Tells whether the request yielded a 5xx status code. * * @return true if the request yielded a 5xx status code, false otherwise. */ boolean is5xx(){ return statusCode >= 500 && statusCode < 600; } /** * Status code getter. * * @return the status code. */ int getStatusCode(){ return statusCode; } /** * Response getter. * * @return the response */ String getResponse(){ return response; } @Override public String toString() { return "Status code: " + statusCode + ", response: " + response; } } /** * Interface used to listen to progress updates from Trim. * * @author Ismael Alonso * @version 1.0.0 */ public interface ProgressListener{ /** * Called when the report about an individual endpoint has been completed. * * @param endpoint the endpoint whose report has been complete. * @param completed the number of endpoints whose reports have been completed. */ void onEndpointReportComplete(Endpoint endpoint, int completed); } }
package it.unibz.inf.ontop.docker; import it.unibz.inf.ontop.injection.OntopSQLOWLAPIConfiguration; import it.unibz.inf.ontop.owlapi.OntopOWLFactory; import it.unibz.inf.ontop.owlapi.OntopOWLReasoner; import it.unibz.inf.ontop.owlapi.connection.OWLConnection; import it.unibz.inf.ontop.owlapi.connection.OWLStatement; import it.unibz.inf.ontop.owlapi.resultset.OWLBindingSet; import it.unibz.inf.ontop.owlapi.resultset.TupleOWLResultSet; import org.junit.Ignore; import org.junit.Test; import org.semanticweb.owlapi.io.ToStringRenderer; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.MessageDigest; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /*** * Class to test if functions on Strings and Numerics in SPARQL are working properly. */ public abstract class AbstractBindTestWithFunctions { protected static Logger log = LoggerFactory.getLogger(AbstractBindTestWithFunctions.class); private final OntopOWLReasoner reasoner; private final OWLConnection conn; protected AbstractBindTestWithFunctions(OntopOWLReasoner reasoner) { this.reasoner = reasoner; this.conn = reasoner.getConnection(); } protected static OntopOWLReasoner createReasoner(String owlFile, String obdaFile, String propertiesFile) throws OWLOntologyCreationException { owlFile = AbstractBindTestWithFunctions.class.getResource(owlFile).toString(); obdaFile = AbstractBindTestWithFunctions.class.getResource(obdaFile).toString(); propertiesFile = AbstractBindTestWithFunctions.class.getResource(propertiesFile).toString(); OntopOWLFactory factory = OntopOWLFactory.defaultFactory(); OntopSQLOWLAPIConfiguration config = OntopSQLOWLAPIConfiguration.defaultBuilder() .nativeOntopMappingFile(obdaFile) .ontologyFile(owlFile) .propertyFile(propertiesFile) .enableTestMode() .build(); return factory.createReasoner(config); } public OntopOWLReasoner getReasoner() { return reasoner; } public OWLConnection getConnection() { return conn; } private void runTests(String query) throws Exception { try (OWLStatement st = conn.createStatement()) { int i = 0; try (TupleOWLResultSet rs = st.executeSelectQuery(query)) { while (rs.hasNext()) { final OWLBindingSet bindingSet = rs.next(); OWLObject ind1 = bindingSet.getOWLObject("w"); log.debug(ind1.toString()); i++; } assertTrue(i > 0); } } } @Test public void testAndBind() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND((CONTAINS(?title,\"Semantic\") && CONTAINS(?title,\"Web\")) AS ?w)\n" + "}\n" + "ORDER BY ?w"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testAndBindDistinct() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT DISTINCT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND((CONTAINS(?title,\"Semantic\") && CONTAINS(?title,\"Web\")) AS ?w)\n" + "}\n" + "ORDER BY ?w"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testOrBind() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT DISTINCT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND((CONTAINS(?title,\"Semantic\") || CONTAINS(?title,\"Book\")) AS ?w)\n" + "}\n" + "ORDER BY ?w"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } /* * Tests for numeric functions */ @Test public void testCeil() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (CEIL(?discount) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getCeilExpectedValues()); } protected List<String> getCeilExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"1\"^^xsd:decimal"); expectedValues.add("\"1\"^^xsd:decimal"); expectedValues.add("\"1\"^^xsd:decimal"); expectedValues.add("\"1\"^^xsd:decimal"); return expectedValues; } @Test public void testFloor() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (FLOOR(?discount) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getFloorExpectedValues()); } protected List<String> getFloorExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); return expectedValues; } @Test public void testRound() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (CONCAT(STR(ROUND(?discount)),', ',STR(ROUND(?p))) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getRoundExpectedValues()); } protected List<String> getRoundExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.0, 43.0\"^^xsd:string"); expectedValues.add("\"0.0, 23.0\"^^xsd:string"); expectedValues.add("\"0.0, 34.0\"^^xsd:string"); expectedValues.add("\"0.0, 10.0\"^^xsd:string"); return expectedValues; } @Test public void testAbs() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (ABS((?p - ?discount*?p) - ?p) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getAbsExpectedValues()); } protected List<String> getAbsExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"8.5\"^^xsd:decimal"); expectedValues.add("\"5.75\"^^xsd:decimal"); expectedValues.add("\"6.7\"^^xsd:decimal"); expectedValues.add("\"1.5\"^^xsd:decimal"); return expectedValues; } /* * Tests for hash functions. H2 supports only SHA256 algorithm. */ @Test public void testHashSHA256() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount.\n" + " ?x dc:title ?title .\n" + " FILTER (STRSTARTS(?title, \"The S\"))\n" + " BIND (SHA256(str(?title)) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest("The Semantic Web".getBytes("UTF-8")); StringBuilder hexString = new StringBuilder(); for (byte b : hash) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } expectedValues.add(String.format("\"%s\"^^xsd:string",hexString.toString())); } catch(Exception ex){ throw new RuntimeException(ex); } checkReturnedValues(queryBind, expectedValues); } @Ignore @Test public void testHashMd5() throws Exception { } @Ignore @Test public void testHashSHA1() throws Exception { } @Ignore @Test public void testHashSHA384() throws Exception { } @Ignore @Test public void testHashSHA512() throws Exception { } /* * Tests for functions on strings. */ @Test public void testStrLen() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRLEN(?title) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"15\"^^xsd:integer"); expectedValues.add("\"16\"^^xsd:integer"); expectedValues.add("\"20\"^^xsd:integer"); expectedValues.add("\"44\"^^xsd:integer"); checkReturnedValues(queryBind, expectedValues); } //test substring with 2 parameters @Test public void testSubstr2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (SUBSTR(?title, 3) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"ARQL Tutorial\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly expectedValues.add("\"e Semantic Web\"@en"); expectedValues.add("\"ime and Punishment\"@en"); expectedValues.add("\"e Logic Book: Introduction, Second Edition\"@en"); checkReturnedValues(queryBind, expectedValues); } //test substring with 3 parameters @Test public void testSubstr3() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (SUBSTR(?title, 3, 6) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"ARQL T\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly expectedValues.add("\"e Sema\"@en"); expectedValues.add("\"ime an\"@en"); expectedValues.add("\"e Logi\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testURIEncoding() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " FILTER (STRSTARTS(?title,\"The\"))\n" + " BIND (ENCODE_FOR_URI(?title) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The%20Semantic%20Web\"^^xsd:string"); expectedValues.add("\"The%20Logic%20Book%3A%20Introduction%2C%20Second%20Edition\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrEnds() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(?title AS ?w)\n" + " FILTER(STRENDS(?title,\"b\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrStarts() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(?title AS ?w)\n" + " FILTER(STRSTARTS(?title,\"The\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); expectedValues.add("\"The Logic Book: Introduction, Second Edition\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStrSubstring() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(SUBSTR(?title,1,STRLEN(?title)) AS ?w)\n" + " FILTER(STRSTARTS(?title,\"The\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly expectedValues.add("\"The Logic Book: Introduction, Second Edition\"@en"); // ROMAN (23 Dec 2015): now the language tag is handled correctly checkReturnedValues(queryBind, expectedValues); } @Test public void testContainsBind() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(CONTAINS(?title,\"Semantic\") AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testContainsFilter() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND(?title AS ?w)\n" + " FILTER(CONTAINS(?title,\"Semantic\"))\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"The Semantic Web\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testBindWithUcase() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (UCASE(?title) AS ?v)\n" + " BIND (CONCAT(?title, \" \", ?v) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"SPARQL Tutorial SPARQL TUTORIAL\"^^xsd:string"); expectedValues.add("\"The Semantic Web THE SEMANTIC WEB\"^^xsd:string"); expectedValues.add("\"Crime and Punishment CRIME AND PUNISHMENT\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduction, Second Edition " + "The Logic Book: Introduction, Second Edition\"".toUpperCase()+"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testBindWithLcase() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (LCASE(?title) AS ?v)\n" + " BIND (CONCAT(?title, \" \", ?v) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"SPARQL Tutorial sparql tutorial\"^^xsd:string"); expectedValues.add("\"The Semantic Web the semantic web\"^^xsd:string"); expectedValues.add("\"Crime and Punishment crime and punishment\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduction, Second Edition " + "The Logic Book: Introduction, Second Edition\"".toLowerCase()+"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testBindWithBefore1() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRBEFORE(?title,\"ti\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithBefore1ExpectedValues()); } protected List<String> getBindWithBefore1ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\"The Seman\"@en"); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduc\"@en"); return expectedValues; } @Test public void testBindWithBefore2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRBEFORE(?title,\"\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithBefore2ExpectedValues()); } protected List<String> getBindWithBefore2ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"\"@en"); expectedValues.add("\"\"@en"); expectedValues.add("\"\"@en"); expectedValues.add("\"\"@en"); return expectedValues; } @Test public void testBindWithAfter1() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRAFTER(?title,\"The\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithAfter1ExpectedValues()); } protected List<String> getBindWithAfter1ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\" Semantic Web\"@en"); expectedValues.add("\"\"^^xsd:string"); expectedValues.add("\" Logic Book: Introduction, Second Edition\"@en"); return expectedValues; } @Test public void testBindWithAfter2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " BIND (STRAFTER(?title,\"\") AS ?w)\n" + "}"; checkReturnedValues(queryBind, getBindWithAfter2ExpectedValues()); } protected List<String> getBindWithAfter2ExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"SPARQL Tutorial\"@en"); expectedValues.add("\"The Semantic Web\"@en"); expectedValues.add("\"Crime and Punishment\"@en"); expectedValues.add("\"The Logic Book: Introduction, Second Edition\"@en"); return expectedValues; } /* * Tests for functions on date and time */ @Test public void testMonth() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (MONTH(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getMonthExpectedValues()); } protected List<String> getMonthExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"6\"^^xsd:integer"); expectedValues.add("\"12\"^^xsd:integer"); expectedValues.add("\"9\"^^xsd:integer"); expectedValues.add("\"11\"^^xsd:integer"); return expectedValues; } @Test public void testYear() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (YEAR(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getYearExpectedValues()); } protected List<String> getYearExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"2014\"^^xsd:integer"); expectedValues.add("\"2011\"^^xsd:integer"); expectedValues.add("\"2015\"^^xsd:integer"); expectedValues.add("\"1967\"^^xsd:integer"); return expectedValues; } @Test public void testDay() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (DAY(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getDayExpectedValues()); } protected List<String> getDayExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"5\"^^xsd:integer"); expectedValues.add("\"8\"^^xsd:integer"); expectedValues.add("\"21\"^^xsd:integer"); expectedValues.add("\"5\"^^xsd:integer"); return expectedValues; } @Test public void testMinutes() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (MINUTES(?year) AS ?w)\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"47\"^^xsd:integer"); expectedValues.add("\"30\"^^xsd:integer"); expectedValues.add("\"23\"^^xsd:integer"); expectedValues.add("\"50\"^^xsd:integer"); checkReturnedValues(queryBind, expectedValues); } @Test public void testHours() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (HOURS(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getHoursExpectedValues()); } protected List<String> getHoursExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"18\"^^xsd:integer"); expectedValues.add("\"12\"^^xsd:integer"); expectedValues.add("\"9\"^^xsd:integer"); expectedValues.add("\"7\"^^xsd:integer"); return expectedValues; } @Test public void testSeconds() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (SECONDS(?year) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getSecondsExpectedValues()); } protected List<String> getSecondsExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"52\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); expectedValues.add("\"6\"^^xsd:decimal"); expectedValues.add("\"0\"^^xsd:decimal"); return expectedValues; } @Test public void testNow() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " BIND (NOW() AS ?w)\n" + "}"; runTests(queryBind); } @Test public void testUuid() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (UUID() AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + "}"; runTests(queryBind); } @Test public void testStrUuid() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (STRUUID() AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + "}"; runTests(queryBind); } @Test public void testRand() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (RAND() AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + "}"; runTests(queryBind); } @Test public void testDivide() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title ?w WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " BIND ((?p / 2) AS ?w)\n" + "}"; checkReturnedValues(queryBind, getDivideExpectedValues()); } protected List<String> getDivideExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"21.250000\"^^xsd:decimal"); expectedValues.add("\"11.500000\"^^xsd:decimal"); expectedValues.add("\"16.750000\"^^xsd:decimal"); expectedValues.add("\"5.000000\"^^xsd:decimal"); return expectedValues; } @Test public void testTZ() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?title (TZ(?year) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + "}"; checkReturnedValues(queryBind, getTZExpectedValues()); } protected List<String> getTZExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"08:00\"^^xsd:string"); expectedValues.add("\"01:00\"^^xsd:string"); expectedValues.add("\"00:00\"^^xsd:string"); expectedValues.add("\"01:00\"^^xsd:string"); return expectedValues; } @Test public void testBound() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (BOUND(?title) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " OPTIONAL{ \n" + " ?x dc:title ?title .\n" + " FILTER (STRSTARTS(?title, \"T\"))\n" + " } \n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } /** * Currently equalities between lang strings are treated as RDFTermEqual. * * Therefore != is always false or null (which corresponds to false under 2VL) * * THIS COULD CHANGE IN THE FUTURE as we could extend the SPARQL spec * (TODO: see how other systems behave) */ @Test public void testRDFTermEqual1() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \",?title2) AS ?w) WHERE \n" + "{ \n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?y ns:discount ?discount2 .\n" + " ?y dc:title ?title2 .\n" + " FILTER (?discount = ?discount2 && ?title != ?title2)\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); checkReturnedValues(queryBind, expectedValues); } @Test public void testRDFTermEqual2() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \",?title2) AS ?w) WHERE \n" + "{ \n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?y ns:discount ?discount2 .\n" + " ?y dc:title ?title2 .\n" + " FILTER (?discount = ?discount2 && str(?title) != str(?title2))\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment | SPARQL Tutorial\"^^xsd:string"); expectedValues.add("\"SPARQL Tutorial | Crime and Punishment\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testSameTerm() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \",?title2) AS ?w) WHERE \n" + "{ \n" + " ?x ns:discount ?discount .\n" + " ?x dc:title ?title .\n" + " ?y ns:discount ?discount2 .\n" + " ?y dc:title ?title2 .\n" + " FILTER(sameTerm(?discount, ?discount2) && !sameTerm(?title, ?title2))\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment | SPARQL Tutorial\"^^xsd:string"); expectedValues.add("\"SPARQL Tutorial | Crime and Punishment\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testIsIRI() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (isIRI(?title) AS ?w) WHERE \n" + "{ ?x ns:price ?price .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " ?x dc:title ?title .\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testIsBlank() throws Exception { //no example data } @Test public void testIsLiteral() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (isLiteral(?discount) AS ?w) WHERE \n" + "{ ?x ns:price ?price .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " ?x dc:title ?title .\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testIsNumeric() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (isNumeric(?discount) AS ?w) WHERE \n" + "{ ?x ns:price ?price .\n" + " ?x ns:discount ?discount .\n" + " ?x ns:pubYear ?year .\n" + " ?x dc:title ?title .\n" + "}"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testStr() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (str(?year) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " } ORDER BY ?year "; checkReturnedValues(queryBind, getStrExpectedValues()); } protected List<String> getStrExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"1970-11-05T07:50:00.000000\"^^xsd:string"); expectedValues.add("\"2011-12-08T12:30:00.000000\"^^xsd:string"); expectedValues.add("\"2014-06-05T18:47:52.000000\"^^xsd:string"); expectedValues.add("\"2015-09-21T09:23:06.000000\"^^xsd:string"); return expectedValues; } @Test public void testLang() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (lang(?title) AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " } "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"en\"^^xsd:string"); expectedValues.add("\"en\"^^xsd:string"); expectedValues.add("\"en\"^^xsd:string"); expectedValues.add("\"en\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } //In SPARQL 1.0, the DATATYPE function was not defined for literals with a language tag @Test public void testDatatype() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (?discount AS ?w) WHERE \n" + "{ ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " FILTER ( datatype(?discount) = xsd:decimal)\n" + " } "; checkReturnedValues(queryBind, getDatatypeExpectedValues()); } protected List<String> getDatatypeExpectedValues() { List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.20\"^^xsd:decimal"); expectedValues.add("\"0.25\"^^xsd:decimal"); expectedValues.add("\"0.20\"^^xsd:decimal"); expectedValues.add("\"0.15\"^^xsd:decimal"); return expectedValues; } @Test public void testConcat() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (CONCAT(?title,\" | \", ?description) AS ?w) WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x dc:description ?description .\n" + " ?x ns:pubYear ?year .\n" + " ?x ns:discount ?discount .\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment | good\"^^xsd:string"); expectedValues.add("\"SPARQL Tutorial | good\"^^xsd:string"); expectedValues.add("\"The Logic Book: Introduction, Second Edition | good\"^^xsd:string"); expectedValues.add("\"The Semantic Web | bad\"^^xsd:string"); checkReturnedValues(queryBind, expectedValues); } @Test public void testLangMatches() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (BOUND(?title) AS ?w) WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " OPTIONAL{\n" + " ?x dc:title ?title .\n" + " FILTER(langMatches( lang(?title), \"EN\" )) \n" + " } } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testREGEX() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT (BOUND(?title) AS ?w) WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x ns:discount ?discount .\n" + " OPTIONAL{\n" + " ?x dc:title ?title .\n" + " FILTER(REGEX( ?title, \"Semantic\" )) \n" + " } } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"false\"^^xsd:boolean"); expectedValues.add("\"true\"^^xsd:boolean"); checkReturnedValues(queryBind, expectedValues); } @Test public void testREPLACE() throws Exception { String queryBind = "PREFIX dc: <http://purl.org/dc/elements/1.1/>\n" + "PREFIX ns: <http://example.org/ns + "SELECT ?w WHERE \n" + "{ \n" + " ?x ns:price ?p .\n" + " ?x dc:title ?title .\n" + " ?x dc:description ?description .\n" + " ?x ns:pubYear ?year .\n" + " BIND(REPLACE(?title, \"Second\", \"First\") AS ?w) .\n" + " } ORDER BY ?title"; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"Crime and Punishment\"@en"); expectedValues.add("\"SPARQL Tutorial\"@en"); expectedValues.add("\"The Logic Book: Introduction, First Edition\"@en"); expectedValues.add("\"The Semantic Web\"@en"); checkReturnedValues(queryBind, expectedValues); } @Test public void testConstantFloatDivide() throws Exception { String queryBind = "SELECT (\"0.5\"^^xsd:float / \"1.0\"^^xsd:float AS ?w) {} "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.5\"^^xsd:float"); checkReturnedValues(queryBind, expectedValues); } @Test public void testConstantFloatIntegerDivide() throws Exception { String queryBind = "SELECT (\"0.5\"^^xsd:float / \"1\"^^xsd:integer AS ?w) {} "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.5\"^^xsd:float"); checkReturnedValues(queryBind, expectedValues); } @Test public void testConstantFloatDecimalDivide() throws Exception { String queryBind = "SELECT (\"0.5\"^^xsd:float / \"1.0\"^^xsd:decimal AS ?w) {} "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.5\"^^xsd:float"); checkReturnedValues(queryBind, expectedValues); } @Test public void testConstantFloatDoubleDivide() throws Exception { String queryBind = "SELECT (\"1.0\"^^xsd:float / \"2.0\"^^xsd:double AS ?w) {} "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.5\"^^xsd:double"); checkReturnedValues(queryBind, expectedValues); } @Test public void testConstantDoubleDoubleDivide() throws Exception { String queryBind = "SELECT (\"1.0\"^^xsd:double / \"2.0\"^^xsd:double AS ?w) {} "; List<String> expectedValues = new ArrayList<>(); expectedValues.add("\"0.5\"^^xsd:double"); checkReturnedValues(queryBind, expectedValues); } private void checkReturnedValues(String query, List<String> expectedValues) throws Exception { try (OWLConnection conn = reasoner.getConnection(); OWLStatement st = conn.createStatement()) { int i = 0; List<String> returnedValues = new ArrayList<>(); try (TupleOWLResultSet rs = st.executeSelectQuery(query)) { while (rs.hasNext()) { final OWLBindingSet bindingSet = rs.next(); OWLObject ind1 = bindingSet.getOWLObject("w"); // log.debug(ind1.toString()); if (ind1 != null) { String value = ToStringRenderer.getInstance().getRendering(ind1); returnedValues.add(value); log.debug(value); } else { returnedValues.add(null); } i++; } } assertEquals(String.format("%s instead of \n %s", returnedValues.toString(), expectedValues.toString()), returnedValues, expectedValues); assertEquals(String.format("Wrong size: %d (expected %d)", i, expectedValues.size()), expectedValues.size(), i); } } }
package net.sf.milkfish.systrace.core.cache; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.net.URI; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.SortedMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Pattern; import net.sf.commonstringutil.StringUtil; import net.sf.milkfish.systrace.core.event.impl.SystraceEvent; import net.sf.milkfish.systrace.core.service.impl.SystraceService; import net.sf.milkfish.systrace.core.state.SystraceStrings; import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; import org.eclipse.linuxtools.tmf.core.event.ITmfEventField; import org.eclipse.linuxtools.tmf.core.event.TmfEventField; import org.eclipse.linuxtools.tmf.core.event.TmfEventType; import org.eclipse.linuxtools.tmf.core.timestamp.ITmfTimestamp; import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestamp; import org.eclipse.linuxtools.tmf.core.trace.TmfLongLocation; import com.google.common.cache.CacheLoader; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.TreeBasedTable; public class TraceLoader extends CacheLoader<Integer, ImmutableMap<Long, ITmfEvent>>{ private FileChannel _fileChannel; /* * RankTables is used to store which rank of data store in which page * A rank represents the order the a record in the trace * * BiMap<rank start of data, page number> */ private BiMap<Long, Integer> _rankTable; /* * PageTable is used to store the begin / start position of paged file * Default per MB size is a page. * * TreeBasedTable<page index, start position, end position> */ private TreeBasedTable<Integer, Long, Long> _pageTable; private long _currentRank; public TraceLoader(FileChannel fileChannel, TreeBasedTable<Integer, Long, Long> pageTable, BiMap<Long, Integer> rankTable) { super(); this._fileChannel = fileChannel; this._pageTable = pageTable; this._rankTable = rankTable; } @Override public ImmutableMap<Long, ITmfEvent> load(Integer pageNum) throws Exception { Builder<Long, ITmfEvent> builder = ImmutableMap.<Long, ITmfEvent>builder(); ConcurrentMap<Long, ITmfEvent> dataMap = Maps.<Long, ITmfEvent>newConcurrentMap(); /* Set the current rank map to the page number * This would be the position of the TMF event instance */ this._currentRank = pageNum == 0 ? -1 : _rankTable.inverse().get(pageNum-1); SortedMap<Long, Long> map = _pageTable.row(pageNum); long positionStart = map.firstKey(); long positionEnd = map.get(positionStart); long bufferSize = positionEnd - positionStart; MappedByteBuffer mmb = _fileChannel.map(FileChannel.MapMode.READ_ONLY, positionStart, bufferSize); byte[] buffer = new byte[(int) bufferSize]; mmb.get(buffer); BufferedReader in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer))); String line; /* Another way is to use regular expression, but seems slower * Pattern pt_sched_switch = Pattern.compile("(?i).*sched_switch.*", Pattern.CASE_INSENSITIVE); */ for (line = in.readLine(); line != null; line = in.readLine()) { //boolean isFind = pt_sched_switch.matcher(line).find(); boolean isFind = SystraceService.isLineMatch(line); if(isFind){ this._currentRank ++; /* RH. Fix me * Should have better way to do it */ if(StringUtil.countText(line, SystraceStrings.SCHED_SWITCH) > 0){ ITmfEvent event = handleSchedleSwitchEvent(line); dataMap.put(this._currentRank, event); continue; }else if(StringUtil.countText(line, SystraceStrings.SCHED_WAKEUP) > 0 || StringUtil.countText(line, SystraceStrings.SCHED_WAKEUP_NEW) > 0){ ITmfEvent event = handleSchedleWakeupEvent(line); dataMap.put(this._currentRank, event); continue; }else if(StringUtil.countText(line, SystraceStrings.SOFTIRQ_RAISE) > 0 || StringUtil.countText(line, SystraceStrings.SOFTIRQ_ENTRY) > 0 || StringUtil.countText(line, SystraceStrings.SOFTIRQ_EXIT) > 0){ ITmfEvent event = handleSoftIrqEvent(line); dataMap.put(this._currentRank, event); continue; }else if(StringUtil.countText(line, SystraceStrings.IRQ_HANDLER_ENTRY) > 0 || StringUtil.countText(line, SystraceStrings.IRQ_HANDLER_EXIT) > 0){ ITmfEvent event = handleIrqEvent(line); dataMap.put(this._currentRank, event); continue; }else if(StringUtil.countText(line, SystraceStrings.SCHED_PROCESS_FORK) > 0){ ITmfEvent event = handleSchedleProcessForkEvent(line); dataMap.put(this._currentRank, event); continue; }else if(StringUtil.countText(line, SystraceStrings.SCHED_PROCESS_EXIT) > 0 || StringUtil.countText(line, SystraceStrings.SCHED_PROCESS_FREE) > 0){ ITmfEvent event = handleSchedleProcessFreeEvent(line); dataMap.put(this._currentRank, event); continue; }else if(StringUtil.countText(line, "trace_event_clock_sync") > 0){ /* * The dummy event is the last event of the trace * The type is trace_event_clock_sync, just ignore it, ex * * dummy-0000 [000] 0.0: 0: trace_event_clock_sync: parent_ts=0.0\n"; * * When trace iterate to this, return null to lead to escape the trace parse * Here we do nothing */ continue; }else{ ITmfEvent event = handleUndefinedEvent(line); dataMap.put(this._currentRank, event); continue; } }else{ System.out.println("line ignore "+ line); } }//for in.close(); return builder.putAll(dataMap).build(); } /* Inner class to store header of line */ private final class Head{ public short cpuId = 0; public long timeStamp = 0L; public String title = "undefine"; public String suffStr = "undefine"; public Head(final short cpuId, final long timeStamp, final String title, final String suffStr){ this.cpuId = cpuId; this.timeStamp = timeStamp; this.title = title; this.suffStr = suffStr; } } private final Head parseHead(String line){ @SuppressWarnings("resource") Scanner scan = new Scanner(line); short cpuId = 0; long timeStamp = 0L; String title = "undefine"; String suffStr = "undefine"; while(scan.hasNext()){ String sn = scan.next(); /* Expect to read [00.] */ if(StringUtil.countText(sn, "[0") > 0){ /* Get CPU id, Ex. [000] */ sn = StringUtil.remove(sn, "["); sn = StringUtil.remove(sn, "]"); cpuId = Short.parseShort(sn); /* Get Timestamp, Ex. 50260.647833: */ sn = scan.next(); sn = StringUtil.remove(sn, ":"); sn = StringUtil.remove(sn, "."); timeStamp =Long.parseLong(sn); /* Get Event Type Ex. sched_wakeup: */ sn = scan.next(); title = StringUtil.remove(sn, ":").trim().intern(); /* Content of the event depends */ @SuppressWarnings("unchecked") List<String> list = StringUtil.splitAsList(line, sn); suffStr = list.get(1).trim(); break; } }//while return new Head(cpuId, timeStamp, title, suffStr); } private final ITmfEvent handleSchedleProcessFreeEvent(String line){ Head head = parseHead(line); String suffStr = head.suffStr; suffStr = StringUtil.replace(suffStr, "comm" , "||"); suffStr = StringUtil.replace(suffStr, "pid" , "||"); suffStr = StringUtil.replace(suffStr, "prio" , "||"); @SuppressWarnings("unchecked") List<String> rlist = StringUtil.splitAsList(suffStr, "||="); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); /* Put the value in a field * The field is required by SystraceStateProvider.eventHandle()*/ final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); /* The comm is optional, could be safe removed */ final TmfEventField tmfEventField_COMM = new TmfEventField(SystraceStrings.COMM, rlist.get(1).trim(), null); //$NON-NLS-1$ eventList.add(tmfEventField_COMM); final TmfEventField tmfEventField_TID = new TmfEventField(SystraceStrings.TID, Long.parseLong(rlist.get(2).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_TID); /* The prio is optional, could be safe removed */ final TmfEventField tmfEventField_PRIO = new TmfEventField(SystraceStrings.PRIO, Long.parseLong(rlist.get(3).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_PRIO); /* the field must be in an array */ final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, suffStr, head.cpuId, head.title); return event; } private final ITmfEvent handleSchedleProcessForkEvent(String line){ Head head = parseHead(line); String suffStr = head.suffStr; /* The order of replacement is tricky */ suffStr = StringUtil.replace(suffStr, "child_comm" , "||"); suffStr = StringUtil.replace(suffStr, "child_pid" , "||"); suffStr = StringUtil.replace(suffStr, "comm" , "||"); suffStr = StringUtil.replace(suffStr, "pid" , "||"); @SuppressWarnings("unchecked") List<String> rlist = StringUtil.splitAsList(suffStr, "||="); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); /* Put the value in a field * The field is required by SystraceStateProvider.eventHandle()*/ final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); /* The comm is optional, could be safe removed */ final TmfEventField tmfEventField_COMM = new TmfEventField(SystraceStrings.COMM, rlist.get(1).trim(), null); //$NON-NLS-1$ eventList.add(tmfEventField_COMM); final TmfEventField tmfEventField_PARENT_TID = new TmfEventField(SystraceStrings.PARENT_TID, Long.parseLong(rlist.get(2).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_PARENT_TID); final TmfEventField tmfEventField_CHILD_COMM = new TmfEventField(SystraceStrings.CHILD_COMM, rlist.get(3).trim(), null); //$NON-NLS-1$ eventList.add(tmfEventField_CHILD_COMM); final TmfEventField tmfEventField_CHILD_TID = new TmfEventField(SystraceStrings.CHILD_TID, Long.parseLong(rlist.get(4).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_CHILD_TID); final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, suffStr, head.cpuId, head.title); return event; } private final ITmfEvent handleIrqEvent(String line){ Head head = parseHead(line); String suffStr = head.suffStr; suffStr = StringUtil.replace(suffStr, "irq" , "||"); suffStr = StringUtil.replace(suffStr, "name" , "||"); suffStr = StringUtil.replace(suffStr, "ret" , "||"); @SuppressWarnings("unchecked") List<String> rlist = StringUtil.splitAsList(suffStr, "||="); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); /* Put the value in a field * The field is required by SystraceStateProvider.eventHandle()*/ final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); final TmfEventField tmfEventField_IRQ = new TmfEventField(SystraceStrings.IRQ, Long.parseLong(rlist.get(1).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_IRQ); /* The name is optional, could be safe removed */ final TmfEventField tmfEventField_NAME = new TmfEventField(SystraceStrings.IRQ_NAME, rlist.get(2).trim(), null); //$NON-NLS-1$ eventList.add(tmfEventField_NAME); final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, suffStr, head.cpuId, head.title); return event; } private final ITmfEvent handleSoftIrqEvent(String line){ Head head = parseHead(line); String suffStr = head.suffStr; suffStr = StringUtil.remove(suffStr, "["); suffStr = StringUtil.remove(suffStr, "]"); suffStr = StringUtil.replace(suffStr, "vec" , "||"); suffStr = StringUtil.replace(suffStr, "action" , "||"); @SuppressWarnings("unchecked") List<String> rlist = StringUtil.splitAsList(suffStr, "||="); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); /* Put the value in a field * The field is required by SystraceStateProvider.eventHandle()*/ final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); final TmfEventField tmfEventField_VEC = new TmfEventField(SystraceStrings.VEC, Long.parseLong(rlist.get(1).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_VEC); /* The action field is optional, could be safe remove */ final TmfEventField tmfEventField_ACTION = new TmfEventField(SystraceStrings.ACTION, rlist.get(2).trim(), null); //$NON-NLS-1$ eventList.add(tmfEventField_ACTION); final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, suffStr, head.cpuId, head.title); return event; } private final ITmfEvent handleUndefinedEvent(String line){ Head head = parseHead(line); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); // put the value in a field final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, line, head.cpuId, head.title); return event; } private final ITmfEvent handleSchedleWakeupEvent(String line){ Head head = parseHead(line); String suffStr = head.suffStr; suffStr = StringUtil.replace(suffStr, "comm" , "||"); suffStr = StringUtil.replace(suffStr, "pid" , "||"); suffStr = StringUtil.replace(suffStr, "prio" , "||"); suffStr = StringUtil.replace(suffStr, "success", "||"); suffStr = StringUtil.replace(suffStr, "target_cpu" , "||"); @SuppressWarnings("unchecked") List<String> rlist = StringUtil.splitAsList(suffStr, "||="); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); /* Put the value in a field * The field is required by SystraceStateProvider.eventHandle()*/ final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); final TmfEventField tmfEventField_TID = new TmfEventField(SystraceStrings.TID, Long.parseLong(rlist.get(2).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_TID); final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, suffStr, head.cpuId, head.title); return event; } private ITmfEvent handleSchedleSwitchEvent(String line){ Head head = parseHead(line); String suffStr = head.suffStr; suffStr = StringUtil.replace(suffStr, "==>", ""); suffStr = StringUtil.replace(suffStr, "prev_comm" , "||"); suffStr = StringUtil.replace(suffStr, "prev_pid" , "||"); suffStr = StringUtil.replace(suffStr, "prev_prio" , "||"); suffStr = StringUtil.replace(suffStr, "prev_state", "||"); suffStr = StringUtil.replace(suffStr, "next_comm" , "||"); suffStr = StringUtil.replace(suffStr, "next_pid" , "||"); suffStr = StringUtil.replace(suffStr, "next_prio" , "||"); @SuppressWarnings("unchecked") List<String> rlist = StringUtil.splitAsList(suffStr, "||="); TmfTimestamp ts = new TmfTimestamp(head.timeStamp,ITmfTimestamp.NANOSECOND_SCALE); Random rnd = new Random(); long payload = Long.valueOf(rnd.nextInt(10)); final List<TmfEventField> eventList = Lists.<TmfEventField>newArrayList(); /* Put the value in a field * The field is required by SystraceStateProvider.eventHandle()*/ final TmfEventField tmfEventField = new TmfEventField("value", payload, null); //$NON-NLS-1$ eventList.add(tmfEventField); final TmfEventField tmfEventField_PREV_TID = new TmfEventField(SystraceStrings.PREV_TID, Long.parseLong(rlist.get(2).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_PREV_TID); final TmfEventField tmfEventField_PREV_STATE = new TmfEventField(SystraceStrings.PREV_STATE, payload, null); //$NON-NLS-1$ eventList.add(tmfEventField_PREV_STATE); final TmfEventField tmfEventField_NEXT_COMM = new TmfEventField(SystraceStrings.NEXT_COMM, rlist.get(5).trim(), null); //$NON-NLS-1$ eventList.add(tmfEventField_NEXT_COMM); final TmfEventField tmfEventField_NEXT_TID = new TmfEventField(SystraceStrings.NEXT_TID, Long.parseLong(rlist.get(6).trim()), null); //$NON-NLS-1$ eventList.add(tmfEventField_NEXT_TID); final TmfEventField[] fields = eventList.toArray(new TmfEventField[eventList.size()]); final TmfEventField content = new TmfEventField(ITmfEventField.ROOT_FIELD_ID, null, fields); SystraceEvent event = new SystraceEvent(null, _currentRank, ts, String.valueOf(this._currentRank),new TmfEventType(head.title, head.title, null), content, suffStr, head.cpuId, head.title); return event; } }
package com.mattunderscore.trees.common.matchers; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.mattunderscore.trees.base.ImmutableNode; import com.mattunderscore.trees.selection.NodeMatcher; import com.mattunderscore.trees.tree.Node; import org.junit.Test; /** * Unit tests for NegatingMatcher. * @author Matt Champion on 20/12/14 */ public final class NegatingMatcherTest { @Test public void notMatches() { final Node<String> node = new ImmutableNode<String>("a", new Object[0]) {}; final NodeMatcher<String> matcher = new NegatingMatcher<>(new EqualityMatcher<String>("a")); assertFalse(matcher.matches(node)); } @Test public void matches() { final Node<String> node = new ImmutableNode<String>("a", new Object[0]) {}; final NodeMatcher<String> matcher = new NegatingMatcher<>(new EqualityMatcher<String>("b")); assertTrue(matcher.matches(node)); } @Test public void testEquals() { final NodeMatcher matcher0 = new NegatingMatcher<>(new TypeMatcher(String.class)); final NodeMatcher matcher1 = new NegatingMatcher<>(new TypeMatcher(String.class)); assertTrue(matcher0.equals(matcher1)); assertTrue(matcher1.equals(matcher0)); assertEquals(matcher0.hashCode(), matcher1.hashCode()); } @Test public void testNotEquals0() { final NodeMatcher matcher0 = new NegatingMatcher<>(new TypeMatcher(String.class)); final NodeMatcher matcher1 = new NegatingMatcher<>(new TypeMatcher(Integer.class)); assertFalse(matcher0.equals(matcher1)); } @Test public void testNotEquals1() { final NodeMatcher matcher0 = new NegatingMatcher<>(new TypeMatcher(String.class)); assertFalse(matcher0.equals(null)); } @Test public void testNotEquals2() { final NodeMatcher matcher0 = new NegatingMatcher<>(new TypeMatcher(String.class)); assertFalse(matcher0.equals(new Object())); } }
package cz.habarta.typescript.generator.emitter; import cz.habarta.typescript.generator.*; import cz.habarta.typescript.generator.compiler.EnumKind; import cz.habarta.typescript.generator.compiler.EnumMemberModel; import cz.habarta.typescript.generator.util.Utils; import java.io.*; import java.text.*; import java.util.*; public class Emitter { private final Settings settings; private Writer writer; private boolean forceExportKeyword; private int indent; public Emitter(Settings settings) { this.settings = settings; } public void emit(TsModel model, Writer output, String outputName, boolean closeOutput, boolean forceExportKeyword, int initialIndentationLevel) { this.writer = output; this.forceExportKeyword = forceExportKeyword; this.indent = initialIndentationLevel; if (outputName != null) { System.out.println("Writing declarations to: " + outputName); } emitFileComment(); emitReferences(); emitImports(); emitModule(model); if (closeOutput) { close(); } } private void emitFileComment() { if (!settings.noFileComment) { final String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); writeIndentedLine("// Generated using typescript-generator version " + TypeScriptGenerator.Version + " on " + timestamp + "."); } } private void emitReferences() { if (settings.referencedFiles != null && !settings.referencedFiles.isEmpty()) { writeNewLine(); for (String reference : settings.referencedFiles) { writeIndentedLine("/// <reference path=" + quote(reference) + " />"); } } } private void emitImports() { if (settings.importDeclarations != null && !settings.importDeclarations.isEmpty()) { writeNewLine(); for (String importDeclaration : settings.importDeclarations) { writeIndentedLine(importDeclaration + ";"); } } } private void emitModule(TsModel model) { if (settings.outputKind == TypeScriptOutputKind.ambientModule) { writeNewLine(); writeIndentedLine("declare module " + quote(settings.module) + " {"); indent++; emitNamespace(model); indent writeNewLine(); writeIndentedLine("}"); } else { emitNamespace(model); } } private void emitNamespace(TsModel model) { if (settings.namespace != null) { writeNewLine(); String prefix = ""; if (settings.outputFileType == TypeScriptFileType.declarationFile && settings.outputKind == TypeScriptOutputKind.global) { prefix = "declare "; } if (settings.outputKind == TypeScriptOutputKind.module) { prefix = "export "; } writeIndentedLine(prefix + "namespace " + settings.namespace + " {"); indent++; final boolean exportElements = settings.outputFileType == TypeScriptFileType.implementationFile; emitElements(model, exportElements, false); indent writeNewLine(); writeIndentedLine("}"); } else { final boolean exportElements = settings.outputKind == TypeScriptOutputKind.module; final boolean declareElements = settings.outputKind == TypeScriptOutputKind.global; emitElements(model, exportElements, declareElements); } } private void emitElements(TsModel model, boolean exportKeyword, boolean declareKeyword) { exportKeyword = exportKeyword || forceExportKeyword; emitInterfaces(model, exportKeyword); emitTypeAliases(model, exportKeyword); emitNumberEnums(model, exportKeyword, declareKeyword); for (EmitterExtension emitterExtension : settings.extensions) { emitterExtension.emitElements(new EmitterExtension.Writer() { @Override public void writeIndentedLine(String line) { Emitter.this.writeIndentedLine(line); } }, settings, exportKeyword, model); } } private void emitInterfaces(TsModel model, boolean exportKeyword) { final List<TsBeanModel> beans = new ArrayList<>(model.getBeans()); if (settings.sortDeclarations || settings.sortTypeDeclarations) { Collections.sort(beans); } for (TsBeanModel bean : beans) { writeNewLine(); emitComments(bean.getComments()); final List<TsType> parents = bean.getParentAndInterfaces(); final String extendsClause = parents.isEmpty() ? "" : " extends " + Utils.join(parents, ", "); writeIndentedLine(exportKeyword, "interface " + bean.getName() + extendsClause + " {"); indent++; final List<TsPropertyModel> properties = bean.getProperties(); if (settings.sortDeclarations) { Collections.sort(properties); } for (TsPropertyModel property : properties) { emitProperty(property); } indent writeIndentedLine("}"); } } private void emitProperty(TsPropertyModel property) { emitComments(property.getComments()); final TsType tsType = property.getTsType(); final String questionMark = settings.declarePropertiesAsOptional || (tsType instanceof TsType.OptionalType) ? "?" : ""; writeIndentedLine(toPropertyName(property.getName()) + questionMark + ": " + tsType.format(settings) + ";"); } private String toPropertyName(String name) { return isValidIdentifierName(name) ? name : quote(name); } // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#2.2.2 // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-names-and-keywords private static boolean isValidIdentifierName(String name) { if (name == null || name.isEmpty()) { return false; } final char start = name.charAt(0); if (!Character.isUnicodeIdentifierStart(start) && start != '$' && start != '_') { return false; } for (char c : name.substring(1).toCharArray()) { if (!Character.isUnicodeIdentifierPart(c) && c != '$' && c != '_' && c != '\u200C' && c != '\u200D') { return false; } } return true; } private void emitTypeAliases(TsModel model, boolean exportKeyword) { final ArrayList<TsAliasModel> aliases = new ArrayList<>(model.getTypeAliases()); if (settings.sortDeclarations || settings.sortTypeDeclarations) { Collections.sort(aliases); } for (TsAliasModel alias : aliases) { writeNewLine(); emitComments(alias.getComments()); writeIndentedLine(exportKeyword, "type " + alias.getName() + " = " + alias.getDefinition().format(settings) + ";"); } } private void emitNumberEnums(TsModel model, boolean exportKeyword, boolean declareKeyword) { final ArrayList<TsEnumModel<?>> enums = settings.mapEnum == EnumMapping.asNumberBasedEnum && !settings.areDefaultStringEnumsOverriddenByExtension() ? new ArrayList<>(model.getEnums()) : new ArrayList<TsEnumModel<?>>(model.getEnums(EnumKind.NumberBased)); if (settings.sortDeclarations || settings.sortTypeDeclarations) { Collections.sort(enums); } for (TsEnumModel<?> enumModel : enums) { writeNewLine(); emitComments(enumModel.getComments()); writeIndentedLine(exportKeyword, (declareKeyword ? "declare " : "") + "const enum " + enumModel.getName() + " {"); indent++; for (EnumMemberModel<?> member : enumModel.getMembers()) { emitComments(member.getComments()); final String initializer = enumModel.getKind() == EnumKind.NumberBased ? " = " + member.getEnumValue() : ""; writeIndentedLine(member.getPropertyName() + initializer + ","); } indent writeIndentedLine("}"); } } private void emitComments(List<String> comments) { if (comments != null) { writeIndentedLine("/**"); for (String comment : comments) { writeIndentedLine(" * " + comment); } writeIndentedLine(" */"); } } private void writeIndentedLine(boolean exportKeyword, String line) { writeIndentedLine((exportKeyword ? "export " : "") + line); } private void writeIndentedLine(String line) { try { if (!line.isEmpty()) { for (int i = 0; i < indent; i++) { writer.write(settings.indentString); } } writer.write(line); writeNewLine(); } catch (IOException e) { throw new RuntimeException(e); } } private void writeNewLine() { try { writer.write(settings.newline); writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } } private String quote(String value) { return settings.quotes + value + settings.quotes; } private void close() { try { writer.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
package com.intellij.uiDesigner.propertyInspector.properties; import com.intellij.openapi.util.Comparing; import com.intellij.uiDesigner.UIDesignerBundle; import com.intellij.uiDesigner.XmlWriter; import com.intellij.uiDesigner.lw.FontDescriptor; import com.intellij.uiDesigner.propertyInspector.IntrospectedProperty; import com.intellij.uiDesigner.propertyInspector.PropertyEditor; import com.intellij.uiDesigner.propertyInspector.PropertyRenderer; import com.intellij.uiDesigner.propertyInspector.editors.FontEditor; import com.intellij.uiDesigner.propertyInspector.renderers.FontRenderer; import com.intellij.uiDesigner.radComponents.RadComponent; import com.intellij.uiDesigner.snapShooter.SnapshotContext; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.lang.reflect.Method; /** * @author yole */ public class IntroFontProperty extends IntrospectedProperty<FontDescriptor> { private FontRenderer myFontRenderer = new FontRenderer(); private FontEditor myFontEditor; @NonNls private static final String CLIENT_PROPERTY_KEY_PREFIX = "IntroFontProperty_"; public IntroFontProperty(final String name, final Method readMethod, final Method writeMethod, final boolean storeAsClient) { super(name, readMethod, writeMethod, storeAsClient); } public void write(@NotNull FontDescriptor value, XmlWriter writer) { writer.writeFontDescriptor(value); } @NotNull public PropertyRenderer<FontDescriptor> getRenderer() { return myFontRenderer; } @Nullable public PropertyEditor<FontDescriptor> getEditor() { if (myFontEditor == null) { myFontEditor = new FontEditor(getName()); } return myFontEditor; } @Override public FontDescriptor getValue(final RadComponent component) { final FontDescriptor fontDescriptor = (FontDescriptor) component.getDelegee().getClientProperty(CLIENT_PROPERTY_KEY_PREFIX + getName()); if (fontDescriptor == null) { return new FontDescriptor(null, -1, -1); } return fontDescriptor; } @Override protected void setValueImpl(final RadComponent component, final FontDescriptor value) throws Exception { component.getDelegee().putClientProperty(CLIENT_PROPERTY_KEY_PREFIX + getName(), value); if (value != null) { if (!component.isLoadingProperties()) { invokeSetter(component, getDefaultValue(component.getDelegee())); } Font defaultFont = (Font) invokeGetter(component); final Font resolvedFont = value.getResolvedFont(defaultFont); invokeSetter(component, resolvedFont); } } public static String descriptorToString(final FontDescriptor value) { if (value == null) { return ""; } if (value.getSwingFont() != null) { return value.getSwingFont(); } StringBuilder builder = new StringBuilder(); if (value.getFontName() != null) { builder.append(value.getFontName()); } if (value.getFontSize() >= 0) { builder.append(' ').append(value.getFontSize()).append(" pt"); } if (value.getFontStyle() >= 0) { if (value.getFontStyle() == 0) { builder.append(' ').append(UIDesignerBundle.message("font.chooser.regular")); } else { if ((value.getFontStyle() & Font.BOLD) != 0) { builder.append(' ').append(UIDesignerBundle.message("font.chooser.bold")); } if ((value.getFontStyle() & Font.ITALIC) != 0) { builder.append(" ").append(UIDesignerBundle.message("font.chooser.italic")); } } } String result = builder.toString().trim(); if (result.length() > 0) { return result; } return UIDesignerBundle.message("font.default"); } @Override public void importSnapshotValue(final SnapshotContext context, final JComponent component, final RadComponent radComponent) { try { if (component.getParent() != null) { Font componentFont = (Font) myReadMethod.invoke(component, EMPTY_OBJECT_ARRAY); Font parentFont = (Font) myReadMethod.invoke(component.getParent(), EMPTY_OBJECT_ARRAY); if (!Comparing.equal(componentFont, parentFont)) { String fontName = componentFont.getName().equals(parentFont.getName()) ? null : componentFont.getName(); int fontStyle = componentFont.getStyle() == parentFont.getStyle() ? -1 : componentFont.getStyle(); int fontSize = componentFont.getSize() == parentFont.getSize() ? -1 : componentFont.getSize(); setValue(radComponent, new FontDescriptor(fontName, fontStyle, fontSize)); } } } catch (Exception e) { // ignore } } }
package com.khartec.waltz.service.permission; import com.khartec.waltz.model.EntityKind; import com.khartec.waltz.model.EntityReference; import com.khartec.waltz.model.involvement.Involvement; import com.khartec.waltz.model.permission_group.Permission; import com.khartec.waltz.model.person.Person; import com.khartec.waltz.service.involvement.InvolvementService; import com.khartec.waltz.service.person.PersonService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static java.util.Objects.isNull; @Service public class PermissionGroupService { private static final Logger LOG = LoggerFactory.getLogger(PermissionGroupService.class); private final InvolvementService involvementService; private final PersonService personService; private final PermissionGroupDao permissionGroupDao; @Autowired public PermissionGroupService(InvolvementService involvementService, PersonService personService, PermissionGroupDao permissionGroupDao) { this.involvementService = involvementService; this.personService = personService; this.permissionGroupDao = permissionGroupDao; } public List<Permission> findPermissions(EntityReference parentEntityRef, String username) { Person person = personService.getPersonByUserId(username); if (isNull(person)){ return Collections.emptyList(); } List<Involvement> involvements = involvementService.findByEmployeeId(person.employeeId()) .stream() .filter(involvement -> involvement.entityReference().equals(parentEntityRef)) .collect(Collectors.toList()); if (involvements.isEmpty()) { return Collections.emptyList(); } return permissionGroupDao.getDefaultPermissions(); } public boolean hasPermission(EntityReference entityReference, EntityKind attestedEntityKind, String username) { return findPermissions(entityReference, username) .stream() .anyMatch(permission -> permission.qualifierKind().equals(attestedEntityKind)); } }
package com.codex.hackerrank; import java.util.Scanner; import java.util.TreeMap; public class PickingNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (int t = 0; t < n; t++) { int x = scanner.nextInt(); if (map.containsKey(x)) { map.put(x, map.get(x) + 1); } else { map.put(x, 1); } } Integer[] keys = (Integer[]) map.keySet().toArray(); int max = map.get(keys[0]); int currentMax = max; for (int i = 1; i < keys.length; i++) { if (Math.abs(keys[i] - keys[i + 1]) == 1) { currentMax += map.get(keys[i + 1]); } else { currentMax = map.get(keys[i]); } max = max(currentMax, max); } System.out.println(map); System.out.println(max); scanner.close(); } private static int max(int a, int b) { return a > b ? a : b; } }
package com.exedio.cope.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class Properties { private final java.util.Properties properties; private final String source; private final ArrayList fields = new ArrayList(); public Properties(final java.util.Properties properties, final String source) { this.properties = properties; this.source = source; // TODO check, that no other property key do occur } public final String getSource() { return source; } public final List getFields() { return Collections.unmodifiableList(fields); } public abstract class Field { private final String key; private final boolean specified; Field(final String key) { this.key = key; this.specified = properties.containsKey(key); if(key==null) throw new NullPointerException("key must not be null."); if(key.length()==0) throw new RuntimeException("key must not be empty."); fields.add(this); } public final String getKey() { return key; } public abstract Object getDefaultValue(); public abstract Object getValue(); public final boolean isSpecified() { return specified; } public boolean hasHiddenValue() { return false; } } public final class BooleanField extends Field { private final boolean defaultValue; private final boolean value; public BooleanField(final String key, final boolean defaultValue) { super(key); this.defaultValue = defaultValue; final String s = properties.getProperty(key); if(s==null) this.value = defaultValue; else { if(s.equals("true")) this.value = true; else if(s.equals("false")) this.value = false; else throw new RuntimeException("property "+key+" in "+source+" has invalid value, expected >true< or >false<, but got >"+s+"<."); } } public Object getDefaultValue() { return Boolean.valueOf(defaultValue); } public Object getValue() { return Boolean.valueOf(value); } public boolean getBooleanValue() { return value; } } public final class IntField extends Field { private final int defaultValue; private final int value; public IntField(final String key, final int defaultValue, final int minimumValue) { super(key); this.defaultValue = defaultValue; if(defaultValue<minimumValue) throw new RuntimeException(key+defaultValue+','+minimumValue); final String s = properties.getProperty(key); if(s==null) value = defaultValue; else { try { value = Integer.parseInt(s); } catch(NumberFormatException e) { throw new RuntimeException( "property " + key + " in " + source + " has invalid value, " + "expected an integer greater or equal " + minimumValue + ", but got >" + s + "<.", e); } if(value<minimumValue) throw new RuntimeException( "property " + key + " in " + source + " has invalid value, " + "expected an integer greater or equal " + minimumValue + ", but got " + value + '.'); } } public Object getDefaultValue() { return Integer.valueOf(defaultValue); } public Object getValue() { return Integer.valueOf(value); } public int getIntValue() { return value; } } public final class StringField extends Field { private final String defaultValue; private final boolean hideValue; private final String value; /** * Creates a mandatory string field. */ public StringField(final String key) { this(key, null, false); } public StringField(final String key, final String defaultValue) { this(key, defaultValue, false); if(defaultValue==null) throw new NullPointerException("defaultValue must not be null."); } /** * Creates a mandatory string field. */ public StringField(final String key, final boolean hideValue) { this(key, null, hideValue); } private StringField(final String key, final String defaultValue, final boolean hideValue) { super(key); this.defaultValue = defaultValue; this.hideValue = hideValue; assert !(defaultValue!=null && hideValue); final String s = properties.getProperty(key); if(s==null) { if(defaultValue==null) throw new RuntimeException("property " + key + " in " + source + " not set and not default value specified."); else this.value = defaultValue; } else this.value = s; } public Object getDefaultValue() { return defaultValue; } public Object getValue() { return value; } public String getStringValue() { return value; } public boolean hasHiddenValue() { return hideValue; } } public final class FileField extends Field { private final File value; public FileField(final String key) { super(key); final String valueString = properties.getProperty(key); this.value = (valueString==null) ? null : new File(valueString); } public Object getDefaultValue() { return null; } public Object getValue() { return value; } public File getFileValue() { return value; } public boolean hasHiddenValue() { return false; } } public final class MapField extends Field { private final java.util.Properties value; public MapField(final String key) { super(key); final String prefix = key + '.'; final int prefixLength = prefix.length(); value = new java.util.Properties(); for(Iterator i = properties.keySet().iterator(); i.hasNext(); ) { final String currentKey = (String)i.next(); if(currentKey.startsWith(prefix)) value.put(currentKey.substring(prefixLength), properties.getProperty(currentKey)); } } public Object getDefaultValue() { return null; } public Object getValue() { return value; } public java.util.Properties getMapValue() { return value; } public String getValue(final String key) { return value.getProperty(key); } } public final void ensureValidity() { ensureValidity(null); } public final void ensureValidity(final String[] prefixes) { final HashSet allowedValues = new HashSet(); final ArrayList allowedPrefixes = new ArrayList(); for(Iterator i = fields.iterator(); i.hasNext(); ) { final Field field = (Field)i.next(); if(field instanceof MapField) allowedPrefixes.add(field.key+'.'); else allowedValues.add(field.key); } if(prefixes!=null) allowedPrefixes.addAll(Arrays.asList(prefixes)); for(Iterator i = properties.keySet().iterator(); i.hasNext(); ) { final String key = (String)i.next(); if(!allowedValues.contains(key)) { boolean error = true; for(Iterator j = allowedPrefixes.iterator(); j.hasNext(); ) { if(key.startsWith((String)j.next())) { error = false; break; } } if(error) throw new RuntimeException("property "+key+" in "+source+" is not allowed."); } } } public final void ensureEquality(final Properties other) { final Iterator j = other.fields.iterator(); for(Iterator i = fields.iterator(); i.hasNext()&&j.hasNext(); ) { final Field thisField = (Field)i.next(); final Field otherField = (Field)j.next(); final boolean thisHideValue = thisField.hasHiddenValue(); final boolean otherHideValue = otherField.hasHiddenValue(); if(!thisField.key.equals(otherField.key)) throw new RuntimeException("inconsistent fields"); if(thisHideValue!=otherHideValue) throw new RuntimeException("inconsistent fields with hide value"); final Object thisValue = thisField.getValue(); final Object otherValue = otherField.getValue(); if((thisValue!=null && !thisValue.equals(otherValue)) || (thisValue==null && otherValue!=null)) throw new RuntimeException( "inconsistent initialization for " + thisField.key + " between " + source + " and " + other.source + (thisHideValue ? "." : "," + " expected " + thisValue + " but got " + otherValue + '.')); } } public static final java.util.Properties loadProperties(final File file) { final java.util.Properties result = new java.util.Properties(); FileInputStream stream = null; try { stream = new FileInputStream(file); result.load(stream); return result; } catch(IOException e) { throw new RuntimeException("property file "+file.getAbsolutePath()+" not found.", e); } finally { if(stream!=null) { try { stream.close(); } catch(IOException e) {} } } } }
package org.displaytag.util; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** * Object representing an URI (the href parameter of an &lt;a> tag). Provides methods to insert new parameters. It * doesn't support multiple parameter values * @author Fabrizio Giustina * @version $Revision$ ($Author$) */ public class Href implements Cloneable, Serializable { /** * D1597A17A6. */ private static final long serialVersionUID = 899149338534L; /** * Base url for the href. */ private String url; /** * Url parameters. */ private Map parameters; /** * Anchor (to be added at the end of URL). */ private String anchor; /** * Construct a new Href parsing a URL. Parameters are stripped from the base url and saved in the parameters map. * @param baseUrl String */ public Href(String baseUrl) { this.parameters = new HashMap(); int anchorposition; String noAnchorUrl; // extract anchor from url if ((anchorposition = baseUrl.indexOf(" { noAnchorUrl = baseUrl.substring(0, anchorposition); this.anchor = baseUrl.substring(anchorposition + 1); } else { noAnchorUrl = baseUrl; } if (noAnchorUrl.indexOf("?") == -1) { // simple url, no parameters this.url = noAnchorUrl; return; } // the Url already has parameters, put them in the parameter Map StringTokenizer tokenizer = new StringTokenizer(noAnchorUrl, "?"); // base url (before "?") this.url = tokenizer.nextToken(); if (!tokenizer.hasMoreTokens()) { return; } // process parameters StringTokenizer paramTokenizer = new StringTokenizer(tokenizer.nextToken(), "&"); // split parameters (key=value) while (paramTokenizer.hasMoreTokens()) { // split key and value ... String[] keyValue = StringUtils.split(paramTokenizer.nextToken(), "="); // encode name/value to prevent css String escapedKey = StringEscapeUtils.escapeHtml(keyValue[0]); String escapedValue = keyValue.length > 1 ? StringEscapeUtils.escapeHtml(keyValue[1]) : TagConstants.EMPTY_STRING; if (!this.parameters.containsKey(escapedKey)) { // ... and add it to the map this.parameters.put(escapedKey, escapedValue); } else { // additional value for an existing parameter Object previousValue = this.parameters.get(escapedKey); if (previousValue != null && previousValue.getClass().isArray()) { Object[] previousArray = (Object[]) previousValue; Object[] newArray = new Object[previousArray.length + 1]; int j; for (j = 0; j < previousArray.length; j++) { newArray[j] = previousArray[j]; } newArray[j] = escapedValue; this.parameters.put(escapedKey, newArray); } else { this.parameters.put(escapedKey, new Object[]{previousValue, escapedValue}); } } } } /** * Constructor for Href. * @param href Href */ public Href(Href href) { this.url = href.url; this.anchor = href.anchor; // getParameterMap() returns a copy this.parameters = href.getParameterMap(); } /** * Adds a parameter to the href. * @param name String * @param value Object * @return this Href instance, useful for concatenation. */ public Href addParameter(String name, Object value) { this.parameters.put(name, value); return this; } /** * Adds an int parameter to the href. * @param name String * @param value int * @return this Href instance, useful for concatenation. */ public Href addParameter(String name, int value) { this.parameters.put(name, new Integer(value)); return this; } /** * Getter for the map containing link parameters. The returned map is always a copy and not the original instance. * @return parameter Map (copy) */ public Map getParameterMap() { Map copyMap = new HashMap(this.parameters.size()); copyMap.putAll(this.parameters); return copyMap; } /** * Adds all the parameters contained in the map to the Href. The value in the given Map will be escaped before * added. Any parameter already present in the href object is removed. * @param parametersMap Map containing parameters */ public void setParameterMap(Map parametersMap) { // create a new HashMap this.parameters = new HashMap(parametersMap.size()); // copy the parameters addParameterMap(parametersMap); } /** * Adds all the parameters contained in the map to the Href. The value in the given Map will be escaped before * added. Parameters in the original href are kept and not overridden. * @param parametersMap Map containing parameters */ public void addParameterMap(Map parametersMap) { // handle nulls if (parametersMap == null) { return; } // copy value, escaping html Iterator mapIterator = parametersMap.entrySet().iterator(); while (mapIterator.hasNext()) { Map.Entry entry = (Map.Entry) mapIterator.next(); String key = StringEscapeUtils.escapeHtml((String) entry.getKey()); // don't overwrite parameters if (!this.parameters.containsKey(key)) { Object value = entry.getValue(); if (value != null) { if (value.getClass().isArray()) { String[] values = (String[]) value; for (int i = 0; i < values.length; i++) { values[i] = StringEscapeUtils.escapeHtml(values[i]); } } else { value = StringEscapeUtils.escapeHtml(value.toString()); } } this.parameters.put(key, value); } } } /** * Getter for the base url (without parameters). * @return String */ public String getBaseUrl() { return this.url; } /** * Returns the URI anchor. * @return anchor or <code>null</code> if no anchor has been set. */ public String getAnchor() { return this.anchor; } /** * Setter for the URI anchor. * @param name string to be used as anchor name (without #). */ public void setAnchor(String name) { this.anchor = name; } /** * toString: output the full url with parameters. * @return String */ public String toString() { StringBuffer buffer = new StringBuffer(30); buffer.append(this.url); if (this.parameters.size() > 0) { buffer.append('?'); Set parameterSet = this.parameters.entrySet(); Iterator iterator = parameterSet.iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Object key = entry.getKey(); Object value = entry.getValue(); if (value == null) { buffer.append(key).append('='); // no value } else if (value.getClass().isArray()) { Object[] values = (Object[]) value; for (int i = 0; i < values.length; i++) { if (i > 0) { buffer.append(TagConstants.AMPERSAND); } buffer.append(key).append('=').append(values[i]); } } else { buffer.append(key).append('=').append(value); } if (iterator.hasNext()) { buffer.append(TagConstants.AMPERSAND); } } } if (this.anchor != null) { buffer.append(" buffer.append(this.anchor); } return buffer.toString(); } /** * @see java.lang.Object#clone() */ public Object clone() { Href href = null; try { href = (Href) super.clone(); } catch (CloneNotSupportedException e) { // should never happen } href.parameters = new HashMap(this.parameters); return href; } /** * @see java.lang.Object#equals(Object) */ public boolean equals(Object object) { if (!(object instanceof Href)) { return false; } Href rhs = (Href) object; return new EqualsBuilder().append(this.parameters, rhs.parameters).append(this.url, rhs.url).append( this.anchor, rhs.anchor).isEquals(); } /** * @see java.lang.Object#hashCode() */ public int hashCode() { return new HashCodeBuilder(1313733113, -431360889) .append(this.parameters) .append(this.url) .append(this.anchor) .toHashCode(); } }
package sample.regexp; import org.openjdk.jmh.runner.RunnerException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) throws RunnerException { test("123"); test("123abc"); } private static void test(String text) { Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(text); System.out.println("[text=" + text + "]"); if (matcher.matches()) { System.out.println("matches = true"); System.out.println("start = " + matcher.start()); System.out.println("end = " + matcher.end()); System.out.println("group = " + matcher.group()); } else { System.out.println("matches = false"); } } }
package org.xtreemfs.mrc; import java.io.IOException; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import org.xtreemfs.common.statusserver.StatusServerHelper; import org.xtreemfs.common.statusserver.StatusServerModule; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.pbrpc.generatedinterfaces.DIR.ServiceType; import org.xtreemfs.pbrpc.generatedinterfaces.MRCServiceConstants; import com.sun.net.httpserver.HttpExchange; /** * Serves a simple HTML status page with MRC stats. */ public class StatusPage extends StatusServerModule { public enum Vars { LASTRQDATE("<!-- $LASTRQDATE -->"), TOTALNUMRQ("<!-- $TOTALNUMRQ -->"), RQSTATS("<!-- $RQSTATS -->"), VOLUMES( "<!-- $VOLUMES -->"), UUID("<!-- $UUID -->"), AVAILPROCS("<!-- $AVAILPROCS -->"), BPSTATS( "<!-- $BPSTATS -->"), PORT("<!-- $PORT -->"), DIRURL("<!-- $DIRURL -->"), DEBUG("<!-- $DEBUG -->"), NUMCON( "<!-- $NUMCON -->"), PINKYQ("<!-- $PINKYQ -->"), PROCQ("<!-- $PROCQ -->"), GLOBALTIME( "<!-- $GLOBALTIME -->"), GLOBALRESYNC("<!-- $GLOBALRESYNC -->"), LOCALTIME("<!-- $LOCALTIME -->"), LOCALRESYNC( "<!-- $LOCALRESYNC -->"), MEMSTAT("<!-- $MEMSTAT -->"), UUIDCACHE("<!-- $UUIDCACHE -->"), DISKFREE( "<!-- $DISKFREE -->"), PROTOVERSION("<!-- $PROTOVERSION -->"), VERSION("<!-- $VERSION -->"), DBVERSION( "<!-- $DBVERSION -->"); private String template; Vars(String template) { this.template = template; } public String toString() { return template; } } private final String statusPageTemplate; private MRCRequestDispatcher master; /** * opNames contains a mapping from numerical operation ids to their textual representation. * It is used by the static method {@link #getOpName} and has therefore to be statically initialized. */ private static final Map<Integer, String> opNames; static { opNames = new HashMap<Integer, String>(); for (Field field : MRCServiceConstants.class.getDeclaredFields()) { if (field.getName().startsWith("PROC_ID")) try { opNames.put(field.getInt(null), field.getName().substring("PROC_ID_".length()).toLowerCase()); } catch (IllegalArgumentException e) { Logging.logError(Logging.LEVEL_ERROR, null, e); } catch (IllegalAccessException e) { Logging.logError(Logging.LEVEL_ERROR, null, e); } } } public StatusPage() { StringBuffer sb = StatusServerHelper.readTemplate("org/xtreemfs/mrc/templates/status.html"); if (sb == null) { statusPageTemplate = "<h1>Template was not found, unable to show status page!</h1>"; } else { statusPageTemplate = sb.toString(); } } @Override public void initialize(ServiceType service, Object serviceRequestDispatcher) { assert (service == ServiceType.SERVICE_TYPE_MRC); master = (MRCRequestDispatcher) serviceRequestDispatcher; } @Override public String getDisplayName() { return "MRC Status Page"; } @Override public String getUriPath() { return "/"; } @Override public void handle(HttpExchange httpExchange) throws IOException { Map<Vars, String> vars = master.getStatusInformation(); String tmp = statusPageTemplate; for (Vars key : vars.keySet()) { tmp = tmp.replace(key.toString(), vars.get(key)); } sendResponse(httpExchange, tmp); httpExchange.close(); } @Override public boolean isAvailableForService(ServiceType service) { return service == ServiceType.SERVICE_TYPE_MRC; } @Override public void shutdown() { } /** * Returns the textual representation of an operation defined in {@link MRCServiceConstants}. * * @param opId * numeric if of an operation. * @return The textual representation of the operation or null if the opId does not exist. */ public static String getOpName(int opId) { String name = opNames.get(opId); return name == null ? null : name; } }
package main.algorithm.leetcode.util; import main.algorithm.leetcode.structure.ListNode; /** * Title : main.algorithm.leetcode.util <br> * Description : * * * @author chile * @version 1.0 * @date 2019/8/21 13:14 */ public class LCUtil { public static ListNode createList5() { return createListWith(5); } public static ListNode createListWith(int capacity) { ListNode head = new ListNode(1); ListNode cursorNode = head; for (int i = 2; i <= capacity; i++) { cursorNode.next = new ListNode(i); cursorNode = cursorNode.next; } return head; } public static void outputList(ListNode head) { if (head == null) { return; } ListNode originHead = head; do { System.out.print(head.val); System.out.print(" "); head = head.next; } while (head != null); head = originHead; System.out.println(); } public static void main(String[] args) { ListNode head = LCUtil.createListWith(5); outputList(head); outputList(head); } }
package org.ned.client.view; import com.sun.lwuit.*; import com.sun.lwuit.events.ActionEvent; import com.sun.lwuit.events.ActionListener; import com.sun.lwuit.events.DataChangedListener; import com.sun.lwuit.layouts.BorderLayout; import com.sun.lwuit.layouts.BoxLayout; import java.io.*; import java.util.Timer; import java.util.TimerTask; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.media.*; import javax.microedition.media.control.FramePositioningControl; import javax.microedition.media.control.VolumeControl; import org.ned.client.IContent; import org.ned.client.NedMidlet; import org.ned.client.NedResources; import org.ned.client.command.BackVideoCommand; public class VideoPlayerView extends NedFormBase implements PlayerListener, ActionListener, Runnable { private static final int INIT_VOLUME_LEVEL = 80; private static final Image playIcon = NedMidlet.getRes().getImage( "Play" ); private static final Image pauseIcon = NedMidlet.getRes().getImage( "Pause" ); private static final Image ffIcon = NedMidlet.getRes().getImage( "FF" ); private static final Image rewIcon = NedMidlet.getRes().getImage( "Rew" ); private static final Image fullIcon = NedMidlet.getRes().getImage( "Fullscreen" ); private static final Image exitIcon = NedMidlet.getRes().getImage( "BackIcon" ); private static int currentVolume = -1; private VolumeControl volume = null; private MediaComponent mediaComponent; private Player player; private FramePositioningControl frame = null; private String videoFile; private KeyListetener mKeyListener; private Container controlUI = null; private Slider progress = null; private boolean ignoreEvent = false; private boolean isPortrait; private Button rewindButton; private Button playButton; private Button fastForwardButton; private Button fullScreenButton; private Button backButton; private UpdateProgessbarTimerTask updateProgressBar; private static Command playCommand = new Command( "Play" ); private static Command fastForwardCommand = new Command( "FF" ); private static Command rewindCommanf = new Command( "Rew" ); private static Command fullScreenCommand = new Command( "Full" ); private static Command exitPlayerCommand = new Command( "Exit" ); private IContent mContent; public VideoPlayerView( IContent content ) { mContent = content; videoFile = mContent.getMediaFile(); setLayout( new BorderLayout() ); setNedTitle( mContent.getText() ); isPortrait = Display.getInstance().isPortrait(); mKeyListener = new KeyListetener(); addGameKeyListener( Display.GAME_UP, mKeyListener ); addGameKeyListener( Display.GAME_DOWN, mKeyListener ); addGameKeyListener( Display.GAME_FIRE, mKeyListener ); addCommandListener( this ); addPointerReleasedListener( new ActionListener() { public void actionPerformed( ActionEvent evt ) { if ( player != null && mediaComponent != null && mediaComponent. isFullScreen() ) { showControlPanel(); } } } ); initControlUI(); updateProgressBar = new UpdateProgessbarTimerTask(); } public void prepareToPlay() { start(); } private void showControlPanel() { if ( controlUI != null && contains( controlUI ) ) { removeComponent( controlUI ); controlUI = null; } initControlUI(); mediaComponent.setFullScreen( false ); addComponent( BorderLayout.SOUTH, controlUI ); removeGameKeyListener( Display.GAME_FIRE, mKeyListener ); controlUI.requestFocus(); repaint(); updateProgressBar(); updateProgressBar.startTimer(); } private synchronized void updateProgressBar() { if ( player != null ) { long time = player.getMediaTime(); long duration = player.getDuration(); if ( time != Player.TIME_UNKNOWN && duration != Player.TIME_UNKNOWN && duration > 0 ) { progress.setProgress( (int)(100 * time / duration) ); int seconds = (int)((time / 1000000) % 60); int minutes = (int)((time / 60000000) % 60); String secondsStr = (seconds < 10 ? "0" : "") + seconds; String minutesStr = (minutes < 10 ? "0" : "") + minutes; progress.setText( minutesStr + ":" + secondsStr ); } } } /** * Reads the content from the specified HTTP URL and returns InputStream * where the contents are read. * * @return InputStream * @throws IOException */ private InputStream urlToStream( String url ) throws IOException { // Open connection to the http url... HttpConnection connection = null; DataInputStream dataIn = null; ByteArrayOutputStream byteout = null; try { connection = (HttpConnection)Connector.open( url ); dataIn = connection.openDataInputStream(); byte[] buffer = new byte[1000]; int read = -1; // Read the content from url. byteout = new ByteArrayOutputStream(); while ( (read = dataIn.read( buffer )) >= 0 ) { byteout.write( buffer, 0, read ); } } catch ( IOException ex ) { if ( dataIn != null ) { dataIn.close(); } if ( connection != null ) { connection.close(); } throw ex; } // Fill InputStream to return with content read from the URL. ByteArrayInputStream byteIn = new ByteArrayInputStream( byteout. toByteArray() ); return byteIn; } public synchronized void actionPerformed( ActionEvent evt ) { Object source = evt.getSource(); if ( source == BackVideoCommand.getInstance().getCommand() ) { BackVideoCommand.getInstance().execute( mContent.getParentId() ); } else if ( source == fastForwardCommand || source == rewindCommanf ) { if ( frame != null ) { frame.skip( 25 * (source == fastForwardCommand ? 1 : -1) );//fast forward or rew updateProgressBar(); } else { NotSupportedMediaContolAction(); } } else if ( source == playCommand ) { pause(); } else if ( source == fullScreenCommand ) { evt.consume(); removeComponent( controlUI ); ignoreEvent = true; addGameKeyListener( Display.GAME_FIRE, mKeyListener ); mediaComponent.setFullScreen( true ); repaint(); updateProgressBar.cancelTimer(); } else if ( source == exitPlayerCommand ) { updateProgressBar.cancelTimer(); BackVideoCommand.getInstance().execute( mContent.getParentId() ); } } public void pause() { if ( player != null ) { if ( player.getState() == Player.STARTED ) { try { long mt = player.getMediaTime(); player.stop(); player.setMediaTime( mt ); } catch ( MediaException ex ) { ex.printStackTrace(); } catch ( IllegalStateException ex ) { ex.printStackTrace(); } } else if ( player.getState() == Player.PREFETCHED ) { try { player.start(); } catch ( MediaException ex ) { start(); } catch ( IllegalStateException isex ) { start(); } } } } public void stopPlayer() { try { if ( player != null && player.getState() != Player.CLOSED ) { if ( player.getState() == Player.STARTED ) { player.stop(); } if ( player.getState() == Player.PREFETCHED ) { player.deallocate(); } if ( player.getState() == Player.REALIZED || player.getState() == Player.UNREALIZED ) { player.close(); } player = null; } } catch ( Exception ex ) { ex.printStackTrace(); } } public void start() { Thread t = new Thread( this ); t.setPriority( Thread.MIN_PRIORITY ); t.start(); } public void playerUpdate( final Player p, final String event, final Object eventData ) { // queue a call to updateEvent in the user interface event queue Display display = Display.getInstance(); display.callSerially( new Runnable() { public void run() { playerUpdate2( p, event, eventData ); } } ); } public synchronized void playerUpdate2( Player p, String event, Object eventData ) { if ( p.getState() == Player.CLOSED ) { return; } if ( event.equals( PlayerListener.END_OF_MEDIA ) ) { playButton.setIcon( playIcon ); playButton.repaint(); showControlPanel(); } else if ( event.equals( PlayerListener.STARTED ) ) { addGameKeyListener( Display.GAME_FIRE, mKeyListener ); playButton.setIcon( pauseIcon ); playButton.repaint(); } else if ( event.equals( PlayerListener.STOPPED ) ) { playButton.setIcon( playIcon ); playButton.repaint(); showControlPanel(); } } public void run() { init(); } void init() { try { if ( mediaComponent != null ) { mediaComponent.setVisible( false ); removeComponent( mediaComponent ); } boolean fromHttp = videoFile.startsWith( "http: if ( fromHttp ) { InputStream is = urlToStream( videoFile ); player = Manager.createPlayer( is, "video/3gpp" ); } else { player = Manager.createPlayer( videoFile ); } player.realize(); player.prefetch(); mediaComponent = new MediaComponent( player ); mediaComponent.setPreferredH( getContentPane().getHeight() - 3 * Font.getDefaultFont().getHeight() ); mediaComponent.getStyle().setMargin( 0, 0, 0, 0 ); mediaComponent.setFullScreen( true ); mediaComponent.setVisible( true ); addComponent( BorderLayout.CENTER, mediaComponent ); player.addPlayerListener( this ); Control[] cs = player.getControls(); for ( int i = 0; i < cs.length; i++ ) { if ( cs[i] instanceof VolumeControl ) { volume = (VolumeControl)cs[i]; volume.setLevel( currentVolume == -1 ? INIT_VOLUME_LEVEL : currentVolume ); } else if ( cs[i] instanceof FramePositioningControl ) { frame = (FramePositioningControl)cs[i]; } } player.start(); repaint(); progress.setProgress( 0 ); } catch ( IOException ex ) { ex.printStackTrace(); } catch ( MediaException ex ) { GeneralAlert.show( NedResources.UNSUPPORTED_MEDIA_FORMAT, GeneralAlert.WARNING ); } } private void initControlUI() { if ( controlUI == null ) { controlUI = new Container( new BoxLayout( (BoxLayout.Y_AXIS) ) ); Container controlUIButton = new Container( new BoxLayout( (BoxLayout.X_AXIS) ) ); int prefH = Font.getDefaultFont().getHeight(); rewindButton = new Button( rewindCommanf ); rewindButton.setIcon( rewIcon ); rewindButton.setText( "" ); int prefW = (Display.getInstance().getDisplayWidth() - 10 * rewindButton.getStyle().getMargin( Component.LEFT )) / 5; rewindButton.setPreferredW( prefW ); rewindButton.setAlignment( Component.CENTER ); rewindButton.setPreferredH( 2 * prefH ); playButton = new Button( playCommand ); playButton.setIcon( (player != null && player.getState() == Player.STARTED) ? pauseIcon : playIcon ); playButton.setText( "" ); playButton.setPreferredW( prefW ); playButton.setPreferredH( 2 * prefH ); playButton.setAlignment( Component.CENTER ); fastForwardButton = new Button( fastForwardCommand ); fastForwardButton.setIcon( ffIcon ); fastForwardButton.setText( "" ); fastForwardButton.setPreferredW( prefW ); fastForwardButton.setPreferredH( 2 * prefH ); fastForwardButton.setAlignment( Component.CENTER ); fullScreenButton = new Button( fullScreenCommand ); fullScreenButton.setIcon( fullIcon ); fullScreenButton.setText( "" ); fullScreenButton.setPreferredW( prefW ); fullScreenButton.setPreferredH( 2 * prefH ); fullScreenButton.setAlignment( Component.CENTER ); backButton = new Button( exitPlayerCommand ); backButton.setIcon( exitIcon ); backButton.setText( "" ); backButton.setPreferredW( prefW ); backButton.setPreferredH( 2 * prefH ); backButton.setAlignment( Component.CENTER ); progress = new Slider(); progress.setThumbImage( pauseIcon.subImage( 7, 0, 8, pauseIcon. getHeight(), false ) ); progress.setMinValue( 0 ); progress.setMaxValue( 100 ); progress.setFocusable( true ); progress.setIncrements( 1 ); progress.setEditable( true ); progress.setPreferredH( Font.getDefaultFont().getHeight() ); progress.addDataChangedListener( new RewFFVideo() ); controlUIButton.addComponent( rewindButton ); controlUIButton.addComponent( playButton ); controlUIButton.addComponent( fastForwardButton ); controlUIButton.addComponent( fullScreenButton ); controlUIButton.addComponent( backButton ); controlUI.addComponent( progress ); controlUI.addComponent( controlUIButton ); controlUI.setPreferredH( 3 * prefH ); } } protected void sizeChanged( int w, int h ) { boolean isPortraitNow = Display.getInstance().isPortrait(); if ( isPortrait != isPortraitNow ) { if ( contains( controlUI ) ) { removeComponent( controlUI ); } controlUI = null; initControlUI(); isPortrait = isPortraitNow; if ( mediaComponent != null ) { removeComponent( mediaComponent ); if ( isPortraitNow ) { mediaComponent.setPreferredH( getContentPane().getHeight() - 3 * Font.getDefaultFont().getHeight() ); } else { mediaComponent.setPreferredH( 100 ); } addComponent( BorderLayout.CENTER, mediaComponent ); } addComponent( BorderLayout.SOUTH, controlUI ); controlUI.requestFocus(); repaint(); } } private class UpdateProgessbarTimerTask { private static final long SEC = 1000; private Timer timer; private TimerTask task; public void startTimer() { cancelTimer(); timer = new Timer(); task = new TimerTask() { public void run() { try { updateProgressBar(); } catch ( Exception ex ) { } } }; timer.schedule( task, SEC, SEC ); } public void cancelTimer() { if ( task != null ) { task.cancel(); task = null; } if ( timer != null ) { timer.cancel(); timer = null; } } protected void finalize() throws Throwable { cancelTimer(); } } private class KeyListetener implements ActionListener { public void actionPerformed( ActionEvent evt ) { int keyCode = evt.getKeyEvent(); switch ( keyCode ) { case Display.GAME_FIRE: if ( mediaComponent.isFullScreen() && !ignoreEvent ) { showControlPanel(); } else { ignoreEvent = false; } break; case Display.GAME_UP: if ( volume != null ) { currentVolume = volume.getLevel() + 5; volume.setLevel( currentVolume ); } break; case Display.GAME_DOWN: if ( volume != null ) { currentVolume = volume.getLevel() - 5; volume.setLevel( currentVolume ); } break; default: break; } } } private void NotSupportedMediaContolAction() { progress.setRenderPercentageOnTop( false ); progress.setText( NedResources.NOT_SUPPORTED ); Timer timer = new Timer(); timer.schedule( new FadingNotSupportedLabelTask( timer ), 1000 ); } private class RewFFVideo implements DataChangedListener { public RewFFVideo() { } public synchronized void dataChanged( int i, int i1 ) { if ( player != null ) { try { player.setMediaTime( i1 * player.getDuration() / 100 ); } catch ( MediaException ex ) { NotSupportedMediaContolAction(); } updateProgressBar(); } else { NotSupportedMediaContolAction(); } } } private class FadingNotSupportedLabelTask extends TimerTask { private Timer mTimer; public FadingNotSupportedLabelTask( Timer aTimer ) { mTimer = aTimer; } public void run() { progress.setRenderPercentageOnTop( true ); mTimer.cancel(); } } }
package jcavern; import java.awt.event.*; import java.awt.*; import java.util.Enumeration; /** * KeyboardCommandListener receives keypress events, tracks input modes, and causes the Player * to do the appropriate actions. * * @author Bill Walker * @version $Id$ */ public class KeyboardCommandListener extends KeyAdapter { /** * A model of the game world */ private World mWorld; private WorldView mWorldView; private MissionView mMissionView; /** * The representation of the player */ private Player mPlayer; private int mCurrentMode; /** * In normal command mode (movement, etc) */ private static final int NORMAL_MODE = 1; /** * In sword attack mode */ private static final int SWORD_MODE = 2; /** * In ranged attack mode */ private static final int RANGED_ATTACK_MODE = 3; /** * In castle visiting mode */ private static final int CASTLE_MODE = 4; /** * In start using mode */ private static final int USE_MODE = 5; /** * In start using mode */ private static final int UNUSE_MODE = 6; public KeyboardCommandListener(World aWorld, WorldView aWorldView, Player aPlayer, MissionView aMissionView) { mWorld = aWorld; mWorldView = aWorldView; mPlayer = aPlayer; mMissionView = aMissionView; mCurrentMode = NORMAL_MODE; } private int parseDirectionKey(KeyEvent e) { switch (e.getKeyChar()) { case 'q' : return Location.NORTHWEST; case 'w' : return Location.NORTH; case 'e' : return Location.NORTHEAST; case 'a' : return Location.WEST; case 'd' : return Location.EAST; case 'z' : return Location.SOUTHWEST; case 'x' : return Location.SOUTH; case 'c' : return Location.SOUTHEAST; } throw new IllegalArgumentException("not a movement key!"); } /** * Handles keyboard commands. */ public void keyTyped(KeyEvent e) { try { switch (mCurrentMode) { case NORMAL_MODE: keyTypedNormalMode(e); break; case CASTLE_MODE: keyTypedCastleMode(e); mCurrentMode = NORMAL_MODE; break; case SWORD_MODE: keyTypedSwordMode(e); mCurrentMode = NORMAL_MODE; break; case RANGED_ATTACK_MODE: keyTypedRangedAttackMode(e); mCurrentMode = NORMAL_MODE; break; case USE_MODE: keyTypedUseMode(e); mCurrentMode = NORMAL_MODE; break; case UNUSE_MODE: keyTypedUnuseMode(e); mCurrentMode = NORMAL_MODE; break; } // and now, the monsters get a turn if (mCurrentMode == NORMAL_MODE) { mWorld.doTurn(); } if (mPlayer.isDead()) { JCavernApplet.current().log("Sorry, " + mPlayer.getName() + ", your game is over."); } } catch(JCavernInternalError jcie) { System.out.println("internal error " + jcie); } } private void keyTypedNormalMode(KeyEvent e) throws JCavernInternalError { switch (e.getKeyChar()) { // movement commands case 'q' : case 'w' : case 'e' : case 'a' : case 'd' : case 'z' : case 'x' : case 'c' : doMove(parseDirectionKey(e)); break; case 's' : mCurrentMode = SWORD_MODE; JCavernApplet.current().log(mPlayer.getSword().getName() + " attack, direction?"); break; case 'b' : mCurrentMode = RANGED_ATTACK_MODE; JCavernApplet.current().log("Ranged attack, direction?"); break; case 'v' : if (mPlayer.getCastle() != null) { mCurrentMode = CASTLE_MODE; JCavernApplet.current().log("Visiting Castle, command?"); } else { JCavernApplet.current().log("No castle to visit"); } break; case '.' : JCavernApplet.current().log("Sit"); break; case 'o' : doOpen(); break; case 'u' : mCurrentMode = USE_MODE; JCavernApplet.current().log("Start using which item?"); break; case 'U' : mCurrentMode = UNUSE_MODE; JCavernApplet.current().log("Stop using which item?"); break; default : JCavernApplet.current().log("Unknown command"); } } private void keyTypedCastleMode(KeyEvent e) throws JCavernInternalError { switch (e.getKeyChar()) { case 'q' : doEndMission(); break; default : JCavernApplet.current().log("Unknown castle visit command"); } } private void keyTypedSwordMode(KeyEvent e) throws JCavernInternalError { switch (e.getKeyChar()) { // direction keys case 'q' : case 'w' : case 'e' : case 'a' : case 'd' : case 'z' : case 'x' : case 'c' : doAttack(parseDirectionKey(e)); break; default : JCavernApplet.current().log("Unknown attack direction"); } } private void keyTypedRangedAttackMode(KeyEvent e) throws JCavernInternalError { switch (e.getKeyChar()) { // direction keys case 'q' : case 'w' : case 'e' : case 'a' : case 'd' : case 'z' : case 'x' : case 'c' : doRangedAttack(parseDirectionKey(e)); break; default : JCavernApplet.current().log("Unknown attack direction"); } } private void keyTypedUseMode(KeyEvent e) throws JCavernInternalError { switch (e.getKeyChar()) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : doUse(Character.getNumericValue(e.getKeyChar())); } } private void keyTypedUnuseMode(KeyEvent e) throws JCavernInternalError { switch (e.getKeyChar()) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : doUnuse(Character.getNumericValue(e.getKeyChar())); } } private void doUse(int anIndex) throws JCavernInternalError { try { mPlayer.getUnusedTreasureAt(anIndex).startUseBy(mPlayer, mWorld); } catch (IllegalArgumentException iae) { JCavernApplet.current().log("There's no item " + anIndex + " to use!"); } } private void doUnuse(int anIndex) { try { mPlayer.getInUseTreasureAt(anIndex).stopUseBy(mPlayer, mWorld); } catch (IllegalArgumentException iae) { JCavernApplet.current().log("There's no item " + anIndex + " to stop using!"); } } private void doEndMission() throws JCavernInternalError { if (mPlayer.getMission().getCompleted()) { JCavernApplet.current().log("Congratulations, " + mPlayer.getName() + "."); // let's do it again! mPlayer.setMission(MonsterFactory.createMission(mPlayer)); mMissionView.setModel(mPlayer.getMission()); // Create a world and a view of the world mWorld.populateFor(mPlayer); } else { JCavernApplet.current().log("Sorry, " + mPlayer.getName() + ", you have not completed your mission"); } } private void doRangedAttack(int direction) throws JCavernInternalError { if (mPlayer.getArrows() > 0) { try { mPlayer.rangedAttack(mWorld, direction); } catch(NonCombatantException nce) { JCavernApplet.current().log(mPlayer.getName() + " can't attack that!"); } catch(IllegalLocationException ile) { JCavernApplet.current().log(mPlayer.getName() + " shot arrow of the edge of the world!"); } } else { JCavernApplet.current().log(mPlayer.getName() + " has no more arrows!"); } mCurrentMode = NORMAL_MODE; } private void doAttack(int direction) throws JCavernInternalError { try { mPlayer.attack(mWorld, direction); } catch(IllegalLocationException nce) { JCavernApplet.current().log(mPlayer.getName() + " can't attack off the edge of the world!"); } catch(EmptyLocationException nce) { JCavernApplet.current().log(mPlayer.getName() + " has nothing to attack!"); } catch(NonCombatantException nce) { JCavernApplet.current().log(mPlayer.getName() + " can't attack that!"); } mCurrentMode = NORMAL_MODE; } private void doOpen() throws JCavernInternalError { TreasureChest aChest = (TreasureChest) mWorld.getNeighboring(mWorld.getLocation(mPlayer), new TreasureChest(null, 0)); mWorld.remove(aChest); JCavernApplet.current().log(mPlayer.getName() + " found " + aChest); if (aChest.getGold() > 0) { mPlayer.receiveGold(aChest.getGold()); } if (aChest.getContents() != null) { mPlayer.receiveItem(aChest.getContents()); } } private void doMove(int direction) throws JCavernInternalError { try { Location oldLocation = mWorld.getLocation(mPlayer); mWorld.move(mPlayer, direction); if (mPlayer.getCastle() != null) { mWorld.place(oldLocation, mPlayer.getCastle()); mPlayer.setCastle(null); } } catch (ThingCollisionException tce) { if (tce.getMovee() instanceof Castle) { Castle theCastle = (Castle) tce.getMovee(); mWorld.remove(theCastle); doMove(direction); mPlayer.setCastle(theCastle); JCavernApplet.current().log(mPlayer.getName() + " entered " + tce.getMovee().getName()); } else { JCavernApplet.current().log(mPlayer.getName() + " collided with " + tce.getMovee().getName()); } } catch (IllegalLocationException tce) { JCavernApplet.current().log(mPlayer.getName() + " can't move off the edge of the world!"); } } }
// $OldId: ExpandMixins.java,v 1.24 2002/11/11 16:08:50 schinz Exp $ package scalac.transformer; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import scalac.Global; import scalac.ast.Tree; import scalac.ast.Tree.Template; import scalac.ast.TreeList; import scalac.ast.TreeGen; import scalac.ast.TreeCloner; import scalac.ast.TreeSymbolCloner; import scalac.ast.Transformer; import scalac.symtab.Modifiers; import scalac.symtab.Scope; import scalac.symtab.Scope.SymbolIterator; import scalac.symtab.Symbol; import scalac.symtab.SymbolCloner; import scalac.symtab.SymbolSubstTypeMap; import scalac.symtab.Type; import scalac.util.Name; import scalac.util.Debug; public class ClassExpander { // // Private Fields /** The global environment */ private final Global global; /** A tree generator */ private final TreeGen gen; /** The expanding class */ private final Symbol clasz; /** The parents of the expanding class */ private final Type[] parents; /** The members of the expanding class */ private final Scope members; /** The template of the expanding class */ private final Template template; /** The body of the expanding class */ private final TreeList body; /** The type map to apply to inlined symbols and trees */ private final SymbolSubstTypeMap map; /** The symbol cloner to clone inlined symbols */ private final SymbolCloner cloner; /** The state of this class (used to prevent misuses) */ private int state; // // Public Constructors public ClassExpander(Global global, Symbol clasz, Template template) { this.global = global; this.gen = global.treeGen; this.clasz = clasz; this.parents = Type.cloneArray(clasz.parents()); this.members = clasz.members().cloneScope(); this.template = gen.Template(template.pos, template.symbol(), Tree.cloneArray(template.parents), template.body); this.body = new TreeList(); this.map = new SymbolSubstTypeMap(); this.cloner = new SymbolCloner( global.freshNameCreator, new HashMap(), map.getSymbols()); this.state = parents.length; } // // Public Methods public void inlineMixin(int i, Type type, Symbol iface, Template impl) { assert 0 < i && i < state : "state = " + state + ", i = " + i; switch (parents[i]) { case TypeRef(Type prefix, Symbol mixin, Type[] args): map.insertSymbol(mixin, clasz); cloner.owners.put(mixin.primaryConstructor(), clasz); inlineMixinTParams(type); Tree.Apply constr = (Tree.Apply)template.parents[i]; inlineMixinVParams(mixin.valueParams(), constr.args); handleMixinInterfaceMembers(mixin); inlineMixinMembers(mixin.nextInfo().members(), impl); parents[i] = Type.TypeRef(prefix, iface, args); template.parents[i] = gen.mkPrimaryConstr(constr.pos, parents[i]); state = i; return; default: throw Debug.abort("invalid base class type", parents[i]); } } public Template getTemplate() { assert 0 < state : "state = " + state; Transformer superFixer = new Transformer(global) { public Tree transform(Tree tree) { switch (tree) { case Select(Super(_, _), _): Symbol symbol = map.lookupSymbol(tree.symbol()); if (symbol != null) return gen.Select(gen.This(tree.pos, clasz), symbol); } return super.transform(tree); } }; body.append(superFixer.transform(template.body)); template.body = body.toArray(); // !!! *1 fix ExpandMixinsPhase.transformInfo and remove next line clasz.updateInfo(Type.compoundType(parents, members, clasz)); state = 0; return template; } // // Private Methods private void inlineMixinTParams(Type type) { switch (type) { case TypeRef(Type prefix, Symbol symbol, Type[] args): map.insertType(symbol.typeParams(), args); // !!! symbols could be equal but args different? need to rebind ? if (prefix.symbol() != symbol.owner()) inlineMixinTParams(prefix.baseType(symbol.owner())); return; default: throw Debug.abort("illegal case", type); } } private void inlineMixinVParams(Symbol[] params, Tree[] args) { for (int i = 0; i < params.length; i++) { Symbol member = cloner.cloneSymbol(params[i], true); member.flags &= ~Modifiers.PARAM; member.flags |= Modifiers.PRIVATE; members.enter(member); } // We need two loops because parameters may appear in their types. for (int i = 0; i < params.length; i++) { Symbol member = map.lookupSymbol(params[i]); member.setType(map.apply(member.type())); body.append(gen.ValDef(member, args[i])); } } // !!! This is just rapid fix. Needs to be reviewed. private void handleMixinInterfaceMembers(Symbol mixin) { Type[] parents = mixin.info().parents(); //assert parents.length == 2: Debug.show(mixin) +" -- "+ mixin.info(); for (int i = 1; i < parents.length; i++) handleMixinInterfaceMembersRec(parents[i].symbol()); } private void handleMixinInterfaceMembersRec(Symbol interfase) { handleMixinInterfaceMembersAux(interfase.nextInfo().members()); Type[] parents = interfase.parents(); for (int i = 0; i < parents.length; i++) { Symbol clasz = parents[i].symbol(); if (clasz.isInterface()) handleMixinInterfaceMembersRec(clasz); } } private void handleMixinInterfaceMembersAux(Scope symbols) { for (SymbolIterator i = symbols.iterator(true); i.hasNext();) { Symbol member = i.next(); if (member.kind != scalac.symtab.Kinds.TYPE) continue; Symbol subst = clasz.thisType().memberType(member).symbol(); if (subst == member) continue; Symbol subst1 = map.lookupSymbol(member); assert subst1 == null || subst1 == subst: Debug.show(member," -> ",subst," + ",subst1); if (subst1 == null) map.insertSymbol(member, subst); } } private void inlineMixinMembers(Scope symbols, Template mixin) { // The map names is used to implement an all or nothing // strategy for overloaded symbols. Map/*<Name,Name>*/ names = new HashMap(); for (SymbolIterator i = symbols.iterator(true); i.hasNext();) { Symbol member = i.next(); Name name = (Name)names.get(member.name); boolean shadowed = name == null && members.lookup(member.name) != Symbol.NONE; Symbol clone = cloner.cloneSymbol(member, shadowed); if (name != null) clone.name = name; else names.put(member.name, clone.name); if (clone.name != member.name) clone.flags &= ~Modifiers.OVERRIDE; clone.setType(clone.type().cloneTypeNoSubst(cloner)); members.enterOrOverload(clone); } // We need two loops because members may appear in their types. for (SymbolIterator i = symbols.iterator(true); i.hasNext();) { Symbol member = map.lookupSymbol(i.next()); if (member == null) continue; member.setType(map.applyParams(member.type())); } cloner.owners.put(mixin.symbol(), template.symbol()); final Set clones = new HashSet(); TreeSymbolCloner mixinSymbolCloner = new TreeSymbolCloner(cloner) { public Symbol cloneSymbol(Symbol symbol) { Symbol clone = super.cloneSymbol(symbol); clones.add(clone); return clone; } }; TreeCloner mixinTreeCloner = new TreeCloner(global, map) { public Tree transform(Tree tree) { switch (tree) { case New(Template template): assert template.parents.length == 1 : tree; assert template.body.length == 0 : tree; Tree apply = template.parents[0]; switch (apply) { case Apply(Tree clasz, Tree[] args): args = transform(args); apply = gen.Apply(apply.pos, clasz, args); return gen.New(tree.pos, apply); default: throw Debug.abort("illegal case", tree); } case Select(Super(_, _), _): Symbol sym = tree.symbol(); Symbol newSym = sym.overridingSymbol(parents[0]); if (newSym != Symbol.NONE) return gen.Select(tree.pos, gen.Super(tree.pos, newSym.owner()), newSym); else return super.transform(tree); default: return super.transform(tree); } } }; for (int i = 0; i < mixin.body.length; i++) { Tree tree = mixin.body[i]; // Inline local code and members whose symbol has been cloned. if (!tree.definesSymbol() || map.lookupSymbol(tree.symbol()) != null) { mixinSymbolCloner.traverse(tree); for (Iterator j = clones.iterator(); j.hasNext();) { Symbol clone = (Symbol)j.next(); clone.setType(map.apply(clone.type())); } clones.clear(); body.append(mixinTreeCloner.transform(tree)); } } } // }
package miner.utils; public class PlatformParas { public static ReadConfigUtil readConfigUtil= new ReadConfigUtil("/opt/build/platform_test.properties", true); //redis public static String redis_host = readConfigUtil.getValue("redis_host"); public static String redis_port = readConfigUtil.getValue("redis_port"); public static String redis_auth = readConfigUtil.getValue("redis_auth"); //mysql public static String mysql_host = readConfigUtil.getValue("mysql_host"); public static String mysql_port = readConfigUtil.getValue("mysql_port"); public static String mysql_user = readConfigUtil.getValue("mysql_user"); public static String mysql_password = readConfigUtil.getValue("mysql_password"); public static String mysql_database = readConfigUtil.getValue("mysql_database"); //hbase zookeeper public static String hbase_zookeeper_host = readConfigUtil.getValue("hbase_zookeeper_host"); //log dir public static String log_path_dir = readConfigUtil.getValue("log_path_dir"); //parallelism config public static int work_num = Integer.parseInt(readConfigUtil.getValue("work_num")); public static int begin_spout_num = Integer.parseInt(readConfigUtil.getValue("begin_spout_num")); public static int loop_spout_num = Integer.parseInt(readConfigUtil.getValue("loop_spout_num")); public static int generateurl_bolt_num = Integer.parseInt(readConfigUtil.getValue("generateurl_bolt_num")); public static int proxy_bolt_num = Integer.parseInt(readConfigUtil.getValue("proxy_bolt_num")); public static int fetch_bolt_num = Integer.parseInt(readConfigUtil.getValue("fetch_bolt_num")); public static int parse_bolt_num = Integer.parseInt(readConfigUtil.getValue("parse_bolt_num")); public static int store_bolt_num = Integer.parseInt(readConfigUtil.getValue("store_bolt_num")); //message timeout public static int message_timeout_secs = Integer.parseInt(readConfigUtil.getValue("message_timeout_secs")); //jar public static String reflect_dir = readConfigUtil.getValue("reflect_dir"); public static String logserver_port = readConfigUtil.getValue("logserver_port"); public static void main(String[] args) { System.out.println(redis_host); System.out.println(redis_auth); System.out.println(begin_spout_num); } }
package edu.umd.cs.findbugs.ba; import edu.umd.cs.findbugs.graph.AbstractGraph; import java.util.*; import org.apache.bcel.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /** * Simple control flow graph abstraction for BCEL. * @see BasicBlock * @see Edge */ public class CFG extends AbstractGraph<Edge, BasicBlock> implements Debug { /** * An Iterator over the Locations in the CFG. * Because of JSR subroutines, the same instruction may actually * be part of multiple basic blocks (with different facts * true in each, due to calling context). Locations specify * both the instruction and the basic block. */ private class LocationIterator implements Iterator<Location> { private Iterator<BasicBlock> blockIter; private BasicBlock curBlock; private Iterator<InstructionHandle> instructionIter; private Location next; private LocationIterator() { this.blockIter = blockIterator(); findNext(); } public boolean hasNext() { findNext(); return next != null; } public Location next() { findNext(); if (next == null) throw new NoSuchElementException(); Location result = next; next = null; return result; } public void remove() { throw new UnsupportedOperationException(); } private void findNext() { while (next == null) { // Make sure we have an instruction iterator if (instructionIter == null) { if (!blockIter.hasNext()) return; // At end curBlock = blockIter.next(); instructionIter = curBlock.instructionIterator(); } if (instructionIter.hasNext()) next = new Location(instructionIter.next(), curBlock); else instructionIter = null; // Go to next block } } } private BasicBlock entry, exit; private int flags; /** * Constructor. * Creates empty control flow graph (with just entry and exit nodes). */ public CFG() { } void setFlags(int flags) { this.flags = flags; } int getFlags() { return flags; } boolean isFlagSet(int flag) { return (flags & flag) != 0; } /** Get the entry node. */ public BasicBlock getEntry() { if (entry == null) { entry = allocate(); } return entry; } /** Get the exit node. */ public BasicBlock getExit() { if (exit == null) { exit = allocate(); } return exit; } public Edge addEdge(BasicBlock source, BasicBlock dest, int type) { Edge edge = addEdge(source, dest); edge.setType(type); return edge; } /** * Look up an Edge by its id. * @param id the id of the edge to look up * @return the Edge, or null if no matching Edge was found */ public Edge lookupEdgeById(int id) { Iterator<Edge> i = edgeIterator(); while (i.hasNext()) { Edge edge = i.next(); if (edge.getId() == id) return edge; } return null; } /** * Get an Iterator over the nodes (BasicBlocks) of the control flow graph. */ public Iterator<BasicBlock> blockIterator() { return vertexIterator(); } /** * Get an Iterator over the Locations in the control flow graph. */ public Iterator<Location> locationIterator() { return new LocationIterator(); } /** * Get Collection of basic blocks whose IDs are specified by * given BitSet. * @param idSet BitSet of block IDs * @return a Collection containing the blocks whose IDs are given */ public Collection<BasicBlock> getBlocks(BitSet idSet) { LinkedList<BasicBlock> result = new LinkedList<BasicBlock>(); for (Iterator<BasicBlock> i = blockIterator(); i.hasNext(); ) { BasicBlock block = i.next(); if (idSet.get(block.getId())) result.add(block); } return result; } /** * Get the first successor reachable from given edge type. * @param source the source block * @param edgeType the edge type leading to the successor * @return the successor, or null if there is no outgoing edge with * the specified edge type */ public BasicBlock getSuccessorWithEdgeType(BasicBlock source, int edgeType) { Edge edge = getOutgoingEdgeWithType(source, edgeType); return edge != null ? edge.getTarget() : null; } /** * Get the first outgoing edge in basic block with given type. * @param basicBlock the basic block * @param edgeType the edge type * @return the Edge, or null if there is no edge with that edge type */ public Edge getOutgoingEdgeWithType(BasicBlock basicBlock, int edgeType) { Iterator<Edge> i = outgoingEdgeIterator(basicBlock); while (i.hasNext()) { Edge edge = i.next(); if (edge.getType() == edgeType) return edge; } return null; } /** * Allocate a new BasicBlock. The block won't be connected to * any node in the graph. */ public BasicBlock allocate() { return addVertex(); } /** * Get number of basic blocks. * This is just here for compatibility with the old CFG * method names. */ public int getNumBasicBlocks() { return getNumVertices(); } /** * Get the number of edge labels allocated. * This is just here for compatibility with the old CFG * method names. */ public int getMaxEdgeId() { return getNumEdgeLabels(); } public void checkIntegrity() { // Ensure that basic blocks have only consecutive instructions for (Iterator<BasicBlock> i = blockIterator(); i.hasNext(); ) { BasicBlock basicBlock = i.next(); InstructionHandle prev = null; for (Iterator<InstructionHandle> j = basicBlock.instructionIterator(); j.hasNext(); ) { InstructionHandle handle = j.next(); if (prev != null && prev.getNext() != handle) throw new IllegalStateException("Non-consecutive instructions in block " + basicBlock.getId() + ": prev=" + prev + ", handle=" + handle); prev = handle; } } } protected BasicBlock createVertex() { return new BasicBlock(); } protected Edge createEdge(BasicBlock source, BasicBlock target) { return new Edge(source, target); } } // vim:ts=4
package sfBugs; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import edu.umd.cs.findbugs.annotations.Confidence; import edu.umd.cs.findbugs.annotations.DesireWarning; import edu.umd.cs.findbugs.annotations.ExpectWarning; /** * @author pugh */ public class Bug3104124 { @DesireWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.MEDIUM) @ExpectWarning(value="OS_OPEN_STREAM_EXCEPTION_PATH", confidence=Confidence.LOW) public static String fileToString(String fileName) { StringBuffer output = new StringBuffer(); try { String line; BufferedReader br = new BufferedReader(new FileReader(fileName)); while ((line = br.readLine()) != null) { output.append(line).append("\n"); } br.close(); } catch (IOException e) { e.printStackTrace(); } return output.toString(); } }
package comments.user; import static com.dyuproject.protostuffdb.EntityMetadata.ZERO_KEY; import static com.dyuproject.protostuffdb.SerializedValueUtil.asInt64; import static com.dyuproject.protostuffdb.SerializedValueUtil.readByteArrayOffsetWithTypeAsSize; import static protostuffdb.Jni.TOKEN_AS_USER; import static protostuffdb.Jni.WITH_PUBSUB; import java.io.IOException; import java.util.Arrays; import com.dyuproject.protostuff.CustomSchema; import com.dyuproject.protostuff.KeyBuilder; import com.dyuproject.protostuff.Output; import com.dyuproject.protostuff.Pipe; import com.dyuproject.protostuff.RpcHeader; import com.dyuproject.protostuff.RpcResponse; import com.dyuproject.protostuffdb.Datastore; import com.dyuproject.protostuffdb.WriteContext; /** * Comment ops. */ public final class CommentOps { private CommentOps() {} static byte[] append(byte[] data, int offset, int len, byte[] suffix) { byte[] buf = new byte[len+suffix.length]; System.arraycopy(data, offset, buf, 0, len); System.arraycopy(suffix, 0, buf, len, suffix.length); return buf; } static boolean validateAndProvide(Comment param, long now, Datastore store, WriteContext context, RpcResponse res) throws IOException { byte[] parentKey = param.parentKey; if (parentKey.length == 0 || Arrays.equals(parentKey, ZERO_KEY)) { param.parentKey = ZERO_KEY; param.provide(now, ZERO_KEY, 0); return true; } final byte[] parentValue = store.get(parentKey, Comment.EM, null, context); if (parentValue == null) return res.fail("Parent comment does not exist!"); if (param.postId.longValue() != asInt64(Comment.VO_POST_ID, parentValue)) return res.fail("Invalid post id."); int offset = readByteArrayOffsetWithTypeAsSize(Comment.FN_KEY_CHAIN, parentValue, context), size = context.type, depth = size / 9; if (depth > 127) return res.fail("The nested replies are too deep and have exceeded the limit."); param.provide(now, append(parentValue, offset, size, parentKey), depth); return true; } static boolean create(Comment req, Datastore store, RpcResponse res, Pipe.Schema<Comment.PList> resPipeSchema, RpcHeader header) throws IOException { if (TOKEN_AS_USER && header.authToken == null) return res.unauthorized(); final byte[] lastSeenKey = req.key; final WriteContext context = res.context; final long now = context.ts(Comment.EM); if (!validateAndProvide(req, now, store, context, res)) return false; final byte[] key = new byte[9]; context.fillEntityKey(key, Comment.EM, now); store.insertWithKey(key, req, req.em(), null, context); req.key = key; if (req.parentKey == ZERO_KEY) return CommentViews.visitWith(req.postId, lastSeenKey, store, res) && pub(req, res); // user posted a reply final KeyBuilder kb = context.kb() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append(req.keyChain); if (lastSeenKey == null) { // visit starting at the first child kb.$append8(0); } else { // visit starting at the entry after the last seen one lastSeenKey[lastSeenKey.length - 1] |= 0x02; kb.$append(lastSeenKey); } return CommentViews.pipeTo(res, store, context, kb.$push() .begin(Comment.IDX_POST_ID__KEY_CHAIN, Comment.EM) .$append(req.postId) .$append(req.keyChain) .$append8(0xFF) .$push()) && pub(req, res); } static boolean pub(Comment req, RpcResponse res) throws IOException { if (WITH_PUBSUB) res.output.writeObject(Comment.PList.FN_PUB, req, PUB_SCHEMA, false); return true; } static final CustomSchema<Comment> PUB_SCHEMA = new CustomSchema<Comment>(Comment.getSchema()) { @Override public void writeTo(Output output, Comment message) throws IOException { output.writeFixed64(Comment.FN_POST_ID, message.postId, false); output.writeString(Comment.FN_NAME, message.name, false); if (message.depth == 0) return; output.writeByteArray(Comment.FN_PARENT_KEY, message.parentKey, false); if (message.depth == 1) return; // root comment key output.writeByteRange(false, Comment.FN_KEY_CHAIN, message.keyChain, 9, 9, false); } }; }
package jlibs.nblr.editor.debug; import jlibs.core.annotation.processing.Printer; import jlibs.core.io.FileUtil; import jlibs.core.lang.ImpossibleException; import jlibs.core.lang.StringUtil; import jlibs.nblr.actions.BufferAction; import jlibs.nblr.actions.EventAction; import jlibs.nblr.actions.PublishAction; import jlibs.nblr.codegen.java.JavaCodeGenerator; import jlibs.nblr.editor.RuleScene; import jlibs.nblr.editor.Util; import jlibs.nblr.rules.Edge; import jlibs.nblr.rules.Node; import jlibs.nblr.rules.Rule; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.BadLocationException; import javax.swing.text.Highlighter; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import java.awt.*; import java.awt.event.ActionEvent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.net.URL; import java.net.URLClassLoader; import java.text.ParseException; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; /** * @author Santhosh Kumar T */ public class Debugger extends JPanel implements Observer{ private RuleScene scene; private JTextArea input = new JTextArea(); private JList ruleStackList = new JList(new DefaultListModel()); public Debugger(RuleScene scene){ super(new BorderLayout(5, 5)); this.scene = scene; scene.ruleObservable.addObserver(this); JToolBar toolbar = Util.toolbar( runAction, debugAction, null, stepAction, runToCursorAction, resumeAction, suspendAction ); add(toolbar, BorderLayout.NORTH); input.setFont(Util.FIXED_WIDTH_FONT); input.addCaretListener(new CaretListener(){ @Override public void caretUpdate(CaretEvent ce){ updateActions(); } }); add(new JScrollPane(input), BorderLayout.CENTER); ruleStackList.setFont(Util.FIXED_WIDTH_FONT); ruleStackList.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent lse){ Rule rule = (Rule)ruleStackList.getSelectedValue(); RuleScene scene = Debugger.this.scene; if(rule!=null && scene.getRule()!=rule) scene.setRule(scene.getSyntax(), rule); } }); add(new JScrollPane(ruleStackList), BorderLayout.EAST); message.setFont(Util.FIXED_WIDTH_FONT); add(message, BorderLayout.SOUTH); updateActions(); } private String compile(File file){ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); ArrayList<String> args = new ArrayList<String>(); args.add("-d"); args.add(file.getParentFile().getAbsolutePath()); args.add("-s"); args.add(file.getParentFile().getAbsolutePath()); args.add(file.getAbsolutePath()); ByteArrayOutputStream err = new ByteArrayOutputStream(); if(compiler.run(null, null, err, args.toArray(new String[args.size()]))==0) return null; return err.toString(); } private NBParser parser; private int inputIndex; private void start(){ try{ showMessage(""); clearGuardedBlock(); File file = new File("temp/DebuggableNBParser.java").getAbsoluteFile(); FileUtil.mkdirs(file.getParentFile()); Printer printer = new Printer(new PrintWriter(new FileWriter(file))); JavaCodeGenerator codeGenerator = new JavaCodeGenerator(scene.getSyntax(), printer); codeGenerator.setDebuggable(); codeGenerator.generateCode(); printer.close(); String error = compile(file); if(error!=null){ JOptionPane.showMessageDialog(this, error); return; } URLClassLoader classLoader = new URLClassLoader(new URL[]{FileUtil.toURL(file.getParentFile())}); Class clazz = classLoader.loadClass("DebuggableNBParser"); parser = (NBParser)clazz.getConstructor(getClass()).newInstance(this); parser.startParsing(scene.getRule().id); showMessage("Executing..."); }catch(Exception ex){ ex.printStackTrace(); JOptionPane.showMessageDialog(this, ex.getMessage()); } } private void step(){ try{ if(inputIndex<input.getDocument().getLength()){ char ch = input.getDocument().getText(inputIndex, 1).charAt(0); parser.consume(ch); inputIndex++; updateGuardedBlock(); }else{ parser.eof(); stop(null, "Input Matched"); } }catch(BadLocationException ex){ throw new ImpossibleException(ex); }catch(Exception ex){ stop(ex, null); } } private void stop(Exception ex, String message){ parser = null; inputIndex = 0; if(ex==null){ clearGuardedBlock(); showMessage(message); }else showError(ex); } private JLabel message = new JLabel(); private void showMessage(String msg){ message.setForeground(Color.BLUE); message.setText(msg); } private void showError(Exception ex){ String text = ex.getMessage(); if(!(ex instanceof ParseException)){ ex.printStackTrace(); text = "[BUG] "+text; } message.setForeground(Color.RED); message.setText(text); } private Highlighter.HighlightPainter highlightPainter = new GuardBlockHighlightPainter(Color.LIGHT_GRAY); private void updateGuardedBlock() throws BadLocationException{ input.getHighlighter().removeAllHighlights(); input.getHighlighter().addHighlight(1, inputIndex-1, highlightPainter); input.repaint(); } private void clearGuardedBlock(){ input.getHighlighter().removeAllHighlights(); input.repaint(); } private void updateActions(){ if(scene.getSyntax()!=null){ String lengthyRuleName = "XXXXXXXXX"; for(Rule rule: scene.getSyntax().rules.values()){ if(rule.name.length()>lengthyRuleName.length()) lengthyRuleName = rule.name; } ruleStackList.setPrototypeCellValue(lengthyRuleName); } JScrollPane scroll = (JScrollPane)ruleStackList.getParent().getParent(); scroll.setVisible(parser!=null); DefaultListModel model = (DefaultListModel)ruleStackList.getModel(); model.clear(); if(parser!=null){ Rule rules[] = scene.getSyntax().rules.values().toArray(new Rule[scene.getSyntax().rules.values().size()]); for(int i: parser.getRuleStack()) model.insertElementAt(rules[i], 0); ruleStackList.setSelectedIndex(model.size()-1); } scroll.revalidate(); doLayout(); input.revalidate(); runAction.setEnabled(parser==null); debugAction.setEnabled(parser==null); stepAction.setEnabled(parser!=null); resumeAction.setEnabled(parser!=null); suspendAction.setEnabled(parser!=null); runToCursorAction.setEnabled(parser!=null && inputIndex<input.getCaretPosition()); } private ImageIcon icon(String name){ return new ImageIcon(getClass().getResource(name)); } private Action runAction = new AbstractAction("Run", icon("run.png")){ public void actionPerformed(ActionEvent ae){ start(); while(parser!=null) step(); updateActions(); } }; private Action debugAction = new AbstractAction("Debug", icon("debug.png")){ public void actionPerformed(ActionEvent ae){ start(); updateActions(); } }; private Action stepAction = new AbstractAction("Step", icon("step.png")){ public void actionPerformed(ActionEvent ae){ step(); updateActions(); } }; private Action runToCursorAction = new AbstractAction("Run to Cursor", icon("runToCursor.png")){ public void actionPerformed(ActionEvent ae){ while(parser!=null && inputIndex<input.getCaretPosition()) step(); updateActions(); } }; private Action resumeAction = new AbstractAction("Resume", icon("resume.png")){ public void actionPerformed(ActionEvent ae){ while(parser!=null) step(); updateActions(); } }; private Action suspendAction = new AbstractAction("Stop", icon("suspend.png")){ public void actionPerformed(ActionEvent ae){ stop(null, ""); updateActions(); } }; private boolean ignoreRuleChange = false; @Override public void update(Observable o, Object rule){ if(ignoreRuleChange || rule==null) return; int ruleIndex = -1; ListModel model = ruleStackList.getModel(); for(int i=model.getSize()-1; i>=0; i if(model.getElementAt(i)==rule){ ruleIndex = i; break; } } if(ruleIndex==-1) ruleStackList.clearSelection(); else{ ruleStackList.setSelectedIndex(ruleIndex); ArrayList<Integer> states = new ArrayList<Integer>(); states.add(0, parser.getState()); for(int state: parser.getStateStack()) states.add(0, state); int state = states.get(ruleIndex); Node node = ((Rule)rule).nodes().get(state); if(ruleIndex==model.getSize()-1) scene.executing(node); else{ for(Edge edge: node.incoming()){ if(edge.rule==model.getElementAt(ruleIndex+1)){ scene.executing(edge); return; } } } } } private java.util.List<Node> nodes = new ArrayList<Node>(); private java.util.List<Edge> edges = new ArrayList<Edge>(); public void currentRule(int id){ // System.out.println("currentRule("+id+")"); Rule rule = (Rule)scene.getSyntax().rules.values().toArray()[id]; nodes.clear(); edges.clear(); rule.computeIDS(nodes, edges, rule.node); ignoreRuleChange = true; try{ scene.setRule(scene.getSyntax(), rule); }finally{ ignoreRuleChange = false; } } public void hitNode(int id){ // System.out.println("hitNode("+id+")"); Node node = nodes.get(id); if(node.action== BufferAction.INSTANCE){ System.out.println("BUFFERRING"); parser.buffer(); }else if(node.action instanceof PublishAction){ PublishAction action = (PublishAction)node.action; String data = parser.data(action.begin, action.end); System.out.println(action.name+"(\""+ StringUtil.toLiteral(data, false)+"\")"); }else if(node.action instanceof EventAction){ EventAction action = (EventAction)node.action; System.out.println(action.name+"()"); } scene.executing(node); } public void currentNode(int id){ // System.out.println("currentNode("+id+")"); Node node = nodes.get(id); scene.executing(node); } }
package org.openlca.jsonld; import com.google.gson.JsonElement; public class Schema { public static final String URI = "http://openlca.org/schema/v1.0/"; public static final String CONTEXT_URI = "http://greendelta.github.io/olca-schema/context.jsonld"; private static final String[] SUPPORTED = { URI }; public static boolean isSupportedSchema(String version) { for (String supported : SUPPORTED) if (supported.equals(version)) return true; return false; } public static String parseUri(JsonElement context) { if (context == null) return null; if (!context.isJsonObject()) return null; JsonElement vocab = context.getAsJsonObject().get("@vocab"); if (vocab == null) return null; return vocab.getAsString(); } public static class UnsupportedSchemaException extends Error { private static final long serialVersionUID = 1916423824713840333L; public UnsupportedSchemaException(String unsupportedSchema) { super("Schema " + unsupportedSchema + " unsupported - current schema is " + URI); } } }
package MWC.GUI.Shapes; import java.awt.Color; import java.awt.Point; import java.beans.IntrospectionException; import java.beans.MethodDescriptor; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.util.Enumeration; import java.util.Iterator; import java.util.Vector; import MWC.GUI.CanvasType; import MWC.GUI.CreateEditorForParent; import MWC.GUI.Editable; import MWC.GUI.ExtendedCanvasType; import MWC.GUI.FireExtended; import MWC.GUI.Layer; import MWC.GUI.PlainWrapper; import MWC.GUI.Plottable; import MWC.GUI.Properties.Swing.SwingWorldPathPropertyEditor; import MWC.GenericData.WorldArea; import MWC.GenericData.WorldLocation; import MWC.GenericData.WorldVector; public class PolygonShape extends PlainShape implements Editable, HasDraggableComponents, Layer { // member variables // bean info for this class public class PolygonInfo extends Editable.EditorType { public PolygonInfo(final PolygonShape data, final String theName) { super(data, theName, ""); } @Override public final MethodDescriptor[] getMethodDescriptors() { // just add the reset color field first final Class<PolygonShape> c = PolygonShape.class; final MethodDescriptor[] mds = {method(c, "addNode", null, "Add Node"),}; return mds; } @Override public String getName() { return PolygonShape.this.getName(); } @Override public PropertyDescriptor[] getPropertyDescriptors() { try { final PropertyDescriptor[] res = {prop("Filled", "whether to fill the polygon", FORMAT), displayProp( "SemiTransparent", "Semi transparent", "whether the filled polygon is semi-transparent", FORMAT), displayProp("ShowNodeLabels", "Show node labels", "whether to label the nodes", FORMAT), prop("Closed", "whether to close the polygon (ignored if filled)", FORMAT)}; return res; } catch (final IntrospectionException e) { return super.getPropertyDescriptors(); } } } public static class PolygonNode implements Editable, Plottable, CreateEditorForParent, Serializable { // bean info for this class public class PolygonNodeInfo extends Editable.EditorType { public PolygonNodeInfo(final PolygonNode data, final String theName) { super(data, theName, ""); } @Override public String getName() { return PolygonNode.this.getName(); } @Override public PropertyDescriptor[] getPropertyDescriptors() { try { final PropertyDescriptor[] res = {prop("Location", "the location of this node"),}; return res; } catch (final IntrospectionException e) { return super.getPropertyDescriptors(); } } } private static final long serialVersionUID = 1L; private String _myName; private WorldLocation _myLocation; private transient EditorType _myEditor; private transient PolygonShape _myParent; public PolygonNode(final String name, final WorldLocation location, final PolygonShape parent) { _myName = name; _myLocation = location; _myParent = parent; } /** * self-destruct * */ public void close() { _myName = null; _myLocation = null; _myEditor = null; _myParent = null; } @Override public int compareTo(final Plottable o) { return this.toString().compareTo(o.toString()); } @Override public WorldArea getBounds() { return new WorldArea(_myLocation, _myLocation); } @Override public EditorType getInfo() { if (_myEditor == null) _myEditor = new PolygonNodeInfo(this, this.getName()); return _myEditor; } public WorldLocation getLocation() { return _myLocation; } @Override public String getName() { return _myName; } @Override public Editable getParent() { return _myParent; } @Override public boolean getVisible() { return true; } @Override public boolean hasEditor() { return true; } @Override public void paint(final CanvasType dest) { // ingore System.err.println("a polygon node should not be painting itself!"); } @Override public double rangeFrom(final WorldLocation other) { return _myLocation.rangeFrom(other); } public void setLocation(final WorldLocation loc) { _myLocation = loc; } @Override public void setVisible(final boolean val) { // ignore } @Override public String toString() { return getName(); } } public static class PolygonPathEditor extends SwingWorldPathPropertyEditor { /** * over-ride the type returned by the path editor */ @Override protected String getMyType() { return "Polygon"; } } private static final long serialVersionUID = 1L; /** * the area covered by this polygon */ private WorldArea _theArea; private Vector<PolygonNode> _nodes = new Vector<PolygonNode>(); /** * our editor */ transient private Editable.EditorType _myEditor; /** * the "anchor" which labels connect to */ private WorldLocation _theAnchor; // constructor /** * whether to join the ends of the polygon * */ private boolean _closePolygon = true; // member functions /** * whether to show labels for the nodes * */ private boolean _showLabels = true; /** * constructor * * @param vector * the WorldLocation marking the centre of the polygon */ public PolygonShape(final Vector<PolygonNode> vector) { super(0, "Polygon"); // and store it _nodes = vector; // now represented our polygon as an area calcPoints(); } @Override @FireExtended public void add(final Editable point) { if (point instanceof PolygonNode) { _nodes.add((PolygonNode) point); calcPoints(); } } public void addNode() { final WorldLocation theLoc = getBounds().getCentreAtSurface(); final String theName; if (_nodes.size() == 0) theName = "1"; else { final String lastName = _nodes.lastElement().getName(); final int nameCtr = Integer.parseInt(lastName); theName = "" + (nameCtr + 1); } final PolygonNode newNode = new PolygonNode(theName, theLoc, this); _nodes.add(newNode); } @Override public void append(final Layer other) { } /** * calculate some convenience values based on the radius and centre of the polygon */ public void calcPoints() { // check we have some points if (_nodes == null) return; if (_nodes.size() > 0) { // running total of lat/longs which we can average to determine the centre double lats = 0; double longs = 0; // reset the area object _theArea = null; // ok, step through the area final Iterator<PolygonNode> points = _nodes.iterator(); while (points.hasNext()) { final WorldLocation next = points.next().getLocation(); // is this our first point? if (_theArea == null) // yes, initialise the area _theArea = new WorldArea(next, next); else // no, just extend it _theArea.extend(next); lats += next.getLat(); longs += next.getLong(); } // ok, now produce the centre _theAnchor = new WorldLocation(lats / _nodes.size(), longs / _nodes .size(), 0); } } @Override protected WorldLocation centreFor(final WorldArea bounds) { final WorldLocation res; if (_nodes != null && _nodes.size() > 0) { final int len = _nodes.size(); // work out total of lats & longs double latSum = 0; double longSum = 0; for (final PolygonNode n : _nodes) { final WorldLocation loc = n.getLocation(); latSum += loc.getLat(); longSum += loc.getLong(); } // and finally the mean of those values res = new WorldLocation(latSum / len, longSum / len, 0d); } else { res = bounds.getCentre(); } return res; } @Override public int compareTo(final Plottable arg0) { return 0; } @Override public Enumeration<Editable> elements() { // create suitable wrapper final Vector<Editable> vec = new Vector<Editable>(); // insert our nodes vec.addAll(_nodes); // done return vec.elements(); } @Override public void exportShape() { } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final ComponentConstruct currentNearest, final Layer parentLayer) { // ok - pass through our corners final Iterator<PolygonNode> myPts = _nodes.iterator(); while (myPts.hasNext()) { final WorldLocation thisLoc = (WorldLocation) myPts.next().getLocation(); // right, see if the cursor is at the centre (that's the easy component) checkThisOne(thisLoc, cursorLoc, currentNearest, this, parentLayer); } } /** * get the 'anchor point' for any labels attached to this shape */ public WorldLocation getAnchor() { return _theAnchor; } @Override public WorldArea getBounds() { return _theArea; } public boolean getClosed() { return _closePolygon; } @Override public Editable.EditorType getInfo() { if (_myEditor == null) _myEditor = new PolygonInfo(this, this.getName()); return _myEditor; } @Override public int getLineThickness() { return 0; } /** * the points representing the polygon */ public Vector<PolygonNode> getPoints() { // note, we have to return a fresh copy of the polygon // in order to know if an edit has been made the editor cannot edit the // original // NO - IGNORE THAT. We give the editor the actual polygon, since the // PolygonEditorView // will be changing the real polygon. that's all. return _nodes; } public Color getPolygonColor() { return super.getColor(); } public boolean getShowNodeLabels() { return _showLabels; } @Override public boolean hasEditor() { return true; } @Override public boolean hasOrderedChildren() { return true; } @Override public void paint(final CanvasType dest) { // are we visible? if (!getVisible()) return; if (this.getColor() != null) { // create a transparent colour final Color newcol = getColor(); dest.setColor(new Color(newcol.getRed(), newcol.getGreen(), newcol .getBlue(), TRANSPARENCY_SHADE)); } // check we have some points if (_nodes == null) return; if (_nodes.size() > 0) { // create our point lists final int[] xP = new int[_nodes.size()]; final int[] yP = new int[_nodes.size()]; // ok, step through the area final Iterator<PolygonNode> points = _nodes.iterator(); int counter = 0; while (points.hasNext()) { final PolygonNode node = points.next(); final WorldLocation next = node.getLocation(); // convert to screen final Point thisP = dest.toScreen(next); // remember the coords xP[counter] = thisP.x; yP[counter] = thisP.y; // move the counter counter++; if (_showLabels) { // and show this label final int yPos = thisP.y + 5; dest.drawText(node.getName(), thisP.x + 5, yPos); } } // ok, now plot it if (getFilled()) { if (getSemiTransparent() && dest instanceof ExtendedCanvasType) { final ExtendedCanvasType ext = (ExtendedCanvasType) dest; ext.semiFillPolygon(xP, yP, xP.length); } else dest.fillPolygon(xP, yP, xP.length); } else { if (getClosed()) dest.drawPolygon(xP, yP, xP.length); else dest.drawPolyline(xP, yP, xP.length); } } // unfortunately we don't have a way of tracking edits to the underlying // worldpath object (since the polygon editor manipulates it directly. // so, we'll recalc our bounds at each repaint. calcPoints(); // and inform the parent (so it can move the label) firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, null); } /** * get the range from the indicated world location - making this abstract allows for individual * shapes to have 'hit-spots' in various locations. */ @Override public double rangeFrom(final WorldLocation point) { double res = -1; if (_nodes.size() > 0) { // ok, step through the area final Iterator<PolygonNode> points = _nodes.iterator(); while (points.hasNext()) { final WorldLocation next = (WorldLocation) points.next().getLocation(); final double thisD = next.rangeFrom(point); // is this our first point? if (res == -1) { res = thisD; } else res = Math.min(res, thisD); } } return res; } @Override @FireExtended public void removeElement(final Editable point) { if (point instanceof PolygonNode) { _nodes.remove(point); final PolygonNode node = (PolygonNode) point; node.close(); } else { System.err.println( "tried to remove point from polygon that isn't a node!"); } } public void setClosed(final boolean polygon) { _closePolygon = polygon; } public void setPolygonColor(final Color val) { super.setColor(val); } public void setShowNodeLabels(final boolean showLabels) { _showLabels = showLabels; } @Override public void shift(final WorldLocation feature, final WorldVector vector) { // ok, just shift it... feature.addToMe(vector); calcPoints(); // and inform the parent (so it can move the label) firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, null); } @Override public void shift(final WorldVector vector) { // ok, cycle through the points, moving each one final Iterator<PolygonNode> pts = _nodes.iterator(); while (pts.hasNext()) { final WorldLocation pt = (WorldLocation) pts.next().getLocation(); final WorldLocation newLoc = pt.add(vector); pt.setLat(newLoc.getLat()); pt.setLong(newLoc.getLong()); pt.setDepth(newLoc.getDepth()); } // and update the outer bounding area calcPoints(); // and inform the parent (so it can move the label) firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, null); } }
package org.voltdb.export; import static com.google_voltpatches.common.base.Preconditions.checkNotNull; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.management.ManagementFactory; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.Callable; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; import org.json_voltpatches.JSONArray; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.voltcore.logging.VoltLogger; import org.voltcore.messaging.BinaryPayloadMessage; import org.voltcore.messaging.Mailbox; import org.voltcore.utils.CoreUtils; import org.voltcore.utils.DBBPool; import org.voltcore.utils.DBBPool.BBContainer; import org.voltcore.utils.Pair; import org.voltdb.VoltDB; import org.voltdb.VoltType; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Column; import org.voltdb.common.Constants; import org.voltdb.export.AdvertisedDataSource.ExportFormat; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.VoltFile; import com.google_voltpatches.common.base.Charsets; import com.google_voltpatches.common.base.Preconditions; import com.google_voltpatches.common.base.Throwables; import com.google_voltpatches.common.collect.ImmutableList; import com.google_voltpatches.common.io.Files; import com.google_voltpatches.common.util.concurrent.ListenableFuture; import com.google_voltpatches.common.util.concurrent.ListeningExecutorService; import com.google_voltpatches.common.util.concurrent.SettableFuture; /** * Allows an ExportDataProcessor to access underlying table queues */ public class ExportDataSource implements Comparable<ExportDataSource> { /** * Processors also log using this facility. */ private static final VoltLogger exportLog = new VoltLogger("EXPORT"); private final String m_database; private final String m_tableName; private String m_partitionColumnName = ""; private final String m_signature; private final byte [] m_signatureBytes; private final long m_generation; private final int m_partitionId; private final ExportFormat m_format; public final ArrayList<String> m_columnNames = new ArrayList<String>(); public final ArrayList<Integer> m_columnTypes = new ArrayList<Integer>(); public final ArrayList<Integer> m_columnLengths = new ArrayList<Integer>(); private long m_firstUnpolledUso = 0; private final StreamBlockQueue m_committedBuffers; private boolean m_endOfStream = false; private Runnable m_onDrain; private Runnable m_onMastership; private final ListeningExecutorService m_es; private SettableFuture<BBContainer> m_pollFuture; private final AtomicReference<Pair<Mailbox, ImmutableList<Long>>> m_ackMailboxRefs = new AtomicReference<Pair<Mailbox,ImmutableList<Long>>>(Pair.of((Mailbox)null, ImmutableList.<Long>builder().build())); private final Semaphore m_bufferPushPermits = new Semaphore(16); private final int m_nullArrayLength; private long m_lastReleaseOffset = 0; /** * Create a new data source. * @param db * @param tableName * @param isReplicated * @param partitionId * @param HSId * @param tableId * @param catalogMap */ public ExportDataSource( final Runnable onDrain, String db, String tableName, int partitionId, String signature, long generation, CatalogMap<Column> catalogMap, Column partitionColumn, String overflowPath ) throws IOException { checkNotNull( onDrain, "onDrain runnable is null"); m_format = ExportFormat.FOURDOTFOUR; m_generation = generation; m_onDrain = new Runnable() { @Override public void run() { try { onDrain.run(); } finally { m_onDrain = null; forwardAckToOtherReplicas(Long.MIN_VALUE); } } }; m_database = db; m_tableName = tableName; m_es = CoreUtils.getListeningExecutorService( "ExportDataSource gen " + m_generation + " table " + m_tableName + " partition " + partitionId, 1); String nonce = signature + "_" + partitionId; m_committedBuffers = new StreamBlockQueue(overflowPath, nonce); /* * This is not the catalog relativeIndex(). This ID incorporates * a catalog version and a table id so that it is constant across * catalog updates that add or drop tables. */ m_signature = signature; m_signatureBytes = m_signature.getBytes(Constants.UTF8ENCODING); m_partitionId = partitionId; // Add the Export meta-data columns to the schema followed by the // catalog columns for this table. m_columnNames.add("VOLT_TRANSACTION_ID"); m_columnTypes.add(((int)VoltType.BIGINT.getValue())); m_columnLengths.add(8); m_columnNames.add("VOLT_EXPORT_TIMESTAMP"); m_columnTypes.add(((int)VoltType.BIGINT.getValue())); m_columnLengths.add(8); m_columnNames.add("VOLT_EXPORT_SEQUENCE_NUMBER"); m_columnTypes.add(((int)VoltType.BIGINT.getValue())); m_columnLengths.add(8); m_columnNames.add("VOLT_PARTITION_ID"); m_columnTypes.add(((int)VoltType.BIGINT.getValue())); m_columnLengths.add(8); m_columnNames.add("VOLT_SITE_ID"); m_columnTypes.add(((int)VoltType.BIGINT.getValue())); m_columnLengths.add(8); m_columnNames.add("VOLT_EXPORT_OPERATION"); m_columnTypes.add(((int)VoltType.TINYINT.getValue())); m_columnLengths.add(1); for (Column c : CatalogUtil.getSortedCatalogItems(catalogMap, "index")) { m_columnNames.add(c.getName()); m_columnTypes.add(c.getType()); m_columnLengths.add(c.getSize()); } if (partitionColumn != null) { m_partitionColumnName = partitionColumn.getName(); } File adFile = new VoltFile(overflowPath, nonce + ".ad"); exportLog.info("Creating ad for " + nonce); assert(!adFile.exists()); byte jsonBytes[] = null; try { JSONStringer stringer = new JSONStringer(); stringer.object(); stringer.key("database").value(m_database); writeAdvertisementTo(stringer); stringer.endObject(); JSONObject jsObj = new JSONObject(stringer.toString()); jsonBytes = jsObj.toString(4).getBytes(Charsets.UTF_8); } catch (JSONException e) { Throwables.propagate(e); } try (FileOutputStream fos = new FileOutputStream(adFile)) { fos.write(jsonBytes); fos.getFD().sync(); } // compute the number of bytes necessary to hold one bit per // schema column m_nullArrayLength = ((m_columnTypes.size() + 7) & -8) >> 3; } public ExportDataSource(final Runnable onDrain, File adFile, boolean isContinueingGeneration) throws IOException { /* * Certainly no more data coming if this is coming off of disk */ m_onDrain = new Runnable() { @Override public void run() { try { onDrain.run(); } finally { m_onDrain = null; forwardAckToOtherReplicas(Long.MIN_VALUE); } } }; String overflowPath = adFile.getParent(); byte data[] = Files.toByteArray(adFile); long hsid = -1; try { JSONObject jsObj = new JSONObject(new String(data, Charsets.UTF_8)); long version = jsObj.getLong("adVersion"); if (version != 0) { throw new IOException("Unsupported ad file version " + version); } try { hsid = jsObj.getLong("hsId"); exportLog.info("Found old for export data source file ignoring m_HSId"); } catch (JSONException jex) { hsid = -1; } m_database = jsObj.getString("database"); m_generation = jsObj.getLong("generation"); m_partitionId = jsObj.getInt("partitionId"); m_signature = jsObj.getString("signature"); m_signatureBytes = m_signature.getBytes(Constants.UTF8ENCODING); m_tableName = jsObj.getString("tableName"); JSONArray columns = jsObj.getJSONArray("columns"); for (int ii = 0; ii < columns.length(); ii++) { JSONObject column = columns.getJSONObject(ii); m_columnNames.add(column.getString("name")); int columnType = column.getInt("type"); m_columnTypes.add(columnType); m_columnLengths.add(column.getInt("length")); } if (jsObj.has("format")) { m_format = ExportFormat.valueOf(jsObj.getString("format")); } else { m_format = ExportFormat.FOURDOTFOUR; } try { m_partitionColumnName = jsObj.getString("partitionColumnName"); } catch (Exception ex) { //Ignore these if we have a OLD ad file these may not exist. } } catch (JSONException e) { throw new IOException(e); } String nonce; if (hsid == -1) { nonce = m_signature + "_" + m_partitionId; } else { nonce = m_signature + "_" + hsid + "_" + m_partitionId; } //If on disk generation matches catalog generation we dont do end of stream as it will be appended to. m_endOfStream = !isContinueingGeneration; m_committedBuffers = new StreamBlockQueue(overflowPath, nonce); // compute the number of bytes necessary to hold one bit per // schema column m_nullArrayLength = ((m_columnTypes.size() + 7) & -8) >> 3; m_es = CoreUtils.getListeningExecutorService("ExportDataSource gen " + m_generation + " table " + m_tableName + " partition " + m_partitionId, 1); } public void updateAckMailboxes( final Pair<Mailbox, ImmutableList<Long>> ackMailboxes) { m_ackMailboxRefs.set( ackMailboxes); } private void releaseExportBytes(long releaseOffset) throws IOException { // if released offset is in an already-released past, just return success if (!m_committedBuffers.isEmpty() && releaseOffset < m_committedBuffers.peek().uso()) { return; } long lastUso = m_firstUnpolledUso; while (!m_committedBuffers.isEmpty() && releaseOffset >= m_committedBuffers.peek().uso()) { StreamBlock sb = m_committedBuffers.peek(); if (releaseOffset >= sb.uso() + sb.totalUso()) { m_committedBuffers.pop(); try { lastUso = sb.uso() + sb.totalUso(); } finally { sb.discard(); } } else if (releaseOffset >= sb.uso()) { sb.releaseUso(releaseOffset); lastUso = releaseOffset; break; } } m_lastReleaseOffset = releaseOffset; m_firstUnpolledUso = Math.max(m_firstUnpolledUso, lastUso); } public String getDatabase() { return m_database; } public String getTableName() { return m_tableName; } public String getSignature() { return m_signature; } public int getPartitionId() { return m_partitionId; } public String getPartitionColumnName() { return m_partitionColumnName; } public final void writeAdvertisementTo(JSONStringer stringer) throws JSONException { stringer.key("adVersion").value(0); stringer.key("generation").value(m_generation); stringer.key("partitionId").value(getPartitionId()); stringer.key("signature").value(m_signature); stringer.key("tableName").value(getTableName()); stringer.key("startTime").value(ManagementFactory.getRuntimeMXBean().getStartTime()); stringer.key("columns").array(); for (int ii=0; ii < m_columnNames.size(); ++ii) { stringer.object(); stringer.key("name").value(m_columnNames.get(ii)); stringer.key("type").value(m_columnTypes.get(ii)); stringer.key("length").value(m_columnLengths.get(ii)); stringer.endObject(); } stringer.endArray(); stringer.key("format").value(ExportFormat.FOURDOTFOUR.toString()); stringer.key("partitionColumnName").value(m_partitionColumnName); } /** * Compare two ExportDataSources for equivalence. This currently does not * compare column names, but it should once column add/drop is allowed. * This comparison is performed to decide if a datasource in a new catalog * needs to be passed to a proccessor. */ @Override public int compareTo(ExportDataSource o) { int result; result = m_database.compareTo(o.m_database); if (result != 0) { return result; } result = m_tableName.compareTo(o.m_tableName); if (result != 0) { return result; } result = (m_partitionId - o.m_partitionId); if (result != 0) { return result; } // does not verify replicated / unreplicated. // does not verify column names / schema return 0; } /** * Make sure equal objects compareTo as 0. */ @Override public boolean equals(Object o) { if (!(o instanceof ExportDataSource)) return false; return compareTo((ExportDataSource)o) == 0; } @Override public int hashCode() { // based on implementation of compareTo int result = 0; result += m_database.hashCode(); result += m_tableName.hashCode(); result += m_partitionId; // does not factor in replicated / unreplicated. // does not factor in column names / schema return result; } public long sizeInBytes() { try { return m_es.submit(new Callable<Long>() { @Override public Long call() throws Exception { return m_committedBuffers.sizeInBytes(); } }).get(); } catch (Throwable t) { Throwables.propagate(t); return 0; } } private void pushExportBufferImpl( long uso, ByteBuffer buffer, boolean sync, boolean endOfStream) throws Exception { final java.util.concurrent.atomic.AtomicBoolean deleted = new java.util.concurrent.atomic.AtomicBoolean(false); if (endOfStream) { assert(!m_endOfStream); assert(buffer == null); assert(!sync); m_endOfStream = endOfStream; if (m_committedBuffers.isEmpty()) { exportLog.info("Pushed EOS buffer with 0 bytes remaining"); if (m_pollFuture != null) { m_pollFuture.set(null); m_pollFuture = null; } if (m_onDrain != null) { m_onDrain.run(); } } else { exportLog.info("EOS for " + m_tableName + " partition " + m_partitionId + " with first unpolled uso " + m_firstUnpolledUso + " and remaining bytes " + m_committedBuffers.sizeInBytes()); } return; } assert(!m_endOfStream); if (buffer != null) { //There will be 8 bytes of no data that we can ignore, it is header space for storing //the USO in stream block if (buffer.capacity() > 8) { final BBContainer cont = DBBPool.wrapBB(buffer); if (m_lastReleaseOffset > 0 && m_lastReleaseOffset >= (uso + (buffer.capacity() - 8))) { //What ack from future is known? if (exportLog.isDebugEnabled()) { exportLog.debug("Dropping already acked USO: " + m_lastReleaseOffset + " Buffer info: " + uso + " Size: " + buffer.capacity()); } cont.discard(); return; } try { m_committedBuffers.offer(new StreamBlock( new BBContainer(buffer) { @Override public void discard() { final ByteBuffer buf = checkDoubleFree(); cont.discard(); deleted.set(true); } }, uso, false)); } catch (IOException e) { exportLog.error(e); if (!deleted.get()) { cont.discard(); } } } else { /* * TupleStreamWrapper::setBytesUsed propagates the USO by sending * over an empty stream block. The block will be deleted * on the native side when this method returns */ exportLog.info("Syncing first unpolled USO to " + uso + " for table " + m_tableName + " partition " + m_partitionId); m_firstUnpolledUso = uso; } } if (sync) { try { //Don't do a real sync, just write the in memory buffers //to a file. @Quiesce or blocking snapshot will do the sync m_committedBuffers.sync(true); } catch (IOException e) { exportLog.error(e); } } pollImpl(m_pollFuture); } public void pushExportBuffer( final long uso, final ByteBuffer buffer, final boolean sync, final boolean endOfStream) { try { m_bufferPushPermits.acquire(); } catch (InterruptedException e) { Throwables.propagate(e); } m_es.execute((new Runnable() { @Override public void run() { try { if (!m_es.isShutdown()) { pushExportBufferImpl(uso, buffer, sync, endOfStream); } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error pushing export buffer", true, t); } finally { m_bufferPushPermits.release(); } } })); } public ListenableFuture<?> closeAndDelete() { return m_es.submit(new Callable<Object>() { @Override public Object call() throws Exception { try { m_committedBuffers.closeAndDelete(); return null; } finally { m_es.shutdown(); } } }); } public long getGeneration() { return m_generation; } public ListenableFuture<?> truncateExportToTxnId(final long txnId) { return m_es.submit((new Runnable() { @Override public void run() { try { m_committedBuffers.truncateToTxnId(txnId, m_nullArrayLength); if (m_committedBuffers.isEmpty() && m_endOfStream) { if (m_pollFuture != null) { m_pollFuture.set(null); m_pollFuture = null; } if (m_onDrain != null) { m_onDrain.run(); } } } catch (Throwable t) { VoltDB.crashLocalVoltDB("Error while trying to truncate export to txnid " + txnId, true, t); } } })); } public ListenableFuture<?> close() { return m_es.submit((new Runnable() { @Override public void run() { try { m_committedBuffers.close(); } catch (IOException e) { exportLog.error(e); } finally { m_es.shutdown(); } } })); } public ListenableFuture<BBContainer> poll() { final SettableFuture<BBContainer> fut = SettableFuture.create(); try { m_es.execute(new Runnable() { @Override public void run() { try { /* * The poll is blocking through the future, shouldn't * call poll a second time until a response has been given * which nulls out the field */ if (m_pollFuture != null) { fut.setException(new RuntimeException("Should not poll more than once")); return; } if (!m_es.isShutdown()) { pollImpl(fut); } } catch (Exception e) { exportLog.error("Exception polling export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error polling export buffer", true, e); } } }); } catch (RejectedExecutionException e) { //Don't expect this to happen outside of test, but in test it's harmless exportLog.info("Polling from export data source rejected, this should be harmless"); } return fut; } private void pollImpl(SettableFuture<BBContainer> fut) { if (fut == null) { return; } try { StreamBlock first_unpolled_block = null; if (m_endOfStream && m_committedBuffers.isEmpty()) { //Returning null indicates end of stream fut.set(null); if (m_onDrain != null) { m_onDrain.run(); } return; } //Assemble a list of blocks to delete so that they can be deleted //outside of the m_committedBuffers critical section ArrayList<StreamBlock> blocksToDelete = new ArrayList<StreamBlock>(); //Inside this critical section do the work to find out //what block should be returned by the next poll. //Copying and sending the data will take place outside the critical section try { Iterator<StreamBlock> iter = m_committedBuffers.iterator(); while (iter.hasNext()) { StreamBlock block = iter.next(); // find the first block that has unpolled data if (m_firstUnpolledUso < block.uso() + block.totalUso()) { first_unpolled_block = block; m_firstUnpolledUso = block.uso() + block.totalUso(); break; } else { blocksToDelete.add(block); iter.remove(); } } } catch (RuntimeException e) { if (e.getCause() instanceof IOException) { VoltDB.crashLocalVoltDB("Error attempting to find unpolled export data", true, e); } else { throw e; } } finally { //Try hard not to leak memory for (StreamBlock sb : blocksToDelete) { sb.discard(); } } //If there are no unpolled blocks return the firstUnpolledUSO with no data if (first_unpolled_block == null) { m_pollFuture = fut; } else { fut.set( new AckingContainer(first_unpolled_block.unreleasedContainer(), first_unpolled_block.uso() + first_unpolled_block.totalUso())); m_pollFuture = null; } } catch (Throwable t) { fut.setException(t); } } class AckingContainer extends BBContainer { final long m_uso; final BBContainer m_backingCont; public AckingContainer(BBContainer cont, long uso) { super(cont.b()); m_uso = uso; m_backingCont = cont; } @Override public void discard() { checkDoubleFree(); try { m_es.execute(new Runnable() { @Override public void run() { try { m_backingCont.discard(); try { if (!m_es.isShutdown()) { ackImpl(m_uso); } } finally { forwardAckToOtherReplicas(m_uso); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }); } catch (RejectedExecutionException e) { //Don't expect this to happen outside of test, but in test it's harmless exportLog.info("Acking export data task rejected, this should be harmless"); //With the executor service stopped, it is safe to discard the backing container m_backingCont.discard(); } } } private void forwardAckToOtherReplicas(long uso) { Pair<Mailbox, ImmutableList<Long>> p = m_ackMailboxRefs.get(); Mailbox mbx = p.getFirst(); if (mbx != null) { // partition:int(4) + length:int(4) + // signaturesBytes.length + ackUSO:long(8) final int msgLen = 4 + 4 + m_signatureBytes.length + 8; ByteBuffer buf = ByteBuffer.allocate(msgLen); buf.putInt(m_partitionId); buf.putInt(m_signatureBytes.length); buf.put(m_signatureBytes); buf.putLong(uso); BinaryPayloadMessage bpm = new BinaryPayloadMessage(new byte[0], buf.array()); for( Long siteId: p.getSecond()) { mbx.send(siteId, bpm); } } } public void ack(final long uso) { m_es.execute(new Runnable() { @Override public void run() { try { if (!m_es.isShutdown()) { ackImpl(uso); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }); } private void ackImpl(long uso) { if (uso == Long.MIN_VALUE && m_onDrain != null) { m_onDrain.run(); return; } //Process the ack if any and add blocks to the delete list or move the released USO pointer if (uso > 0) { try { releaseExportBytes(uso); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error attempting to release export bytes", true, e); return; } } } /** * Trigger an execution of the mastership runnable by the associated * executor service */ public void acceptMastership() { Preconditions.checkNotNull(m_onMastership, "mastership runnable is not yet set"); m_es.execute(new Runnable() { @Override public void run() { try { if (!m_es.isShutdown()) { m_onMastership.run(); } } catch (Exception e) { exportLog.error("Error in accepting mastership", e); } } }); } /** * set the runnable task that is to be executed on mastership designation * @param toBeRunOnMastership a {@link @Runnable} task */ public void setOnMastership(Runnable toBeRunOnMastership) { Preconditions.checkNotNull(toBeRunOnMastership, "mastership runnable is null"); m_onMastership = toBeRunOnMastership; } public ExportFormat getExportFormat() { return m_format; } }
package gov.nih.nci.calab.ui.core; /** * This class calls the Struts ForwardAction to forward to a page, aslo * extends AbstractBaseAction to inherit the user authentication features. * * @author pansu */ /* CVS $Id: BaseForwardAction.java,v 1.2 2006-05-02 20:12:17 pansu Exp $ */ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.ForwardAction; public class BaseForwardAction extends AbstractBaseAction { public ActionForward executeTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ForwardAction forwardAction = new ForwardAction(); return forwardAction.execute(mapping, form, request, response); } public boolean loginRequired() { return true; } }
package edu.cornell.mannlib.vitro.webapp.controller.freemarker; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean; import edu.cornell.mannlib.vitro.webapp.beans.Portal; import edu.cornell.mannlib.vitro.webapp.controller.ContactMailServlet; import edu.cornell.mannlib.vitro.webapp.controller.Controllers; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.utils.StringUtils; import freemarker.template.Configuration; /** * Controller for comments ("contact us") page * * @author bjl23 */ public class ContactFormController extends FreeMarkerHttpServlet { private static final long serialVersionUID = 1L; private static final Log log = LogFactory.getLog(ContactFormController.class.getName()); protected String getTitle(String siteName) { return siteName + " Feedback Form"; } protected String getBody(VitroRequest vreq, Map<String, Object> body, Configuration config) { String bodyTemplate; Portal portal = vreq.getPortal(); if (!ContactMailServlet.isSmtpHostConfigured()) { body.put("errorMessage", "This application has not yet been configured to send mail. " + "An smtp host has not been specified in the configuration properties file."); bodyTemplate = "contactForm-error.ftl"; } else if (StringUtils.isEmpty(portal.getContactMail())) { body.put("errorMessage", "The feedback form is currently disabled. In order to activate the form, a site administrator must provide a contact email address in the <a href='editForm?home=1&amp;controller=Portal&amp;id=1'>Site Configuration</a>"); bodyTemplate = "contactForm-error.ftl"; } else { ApplicationBean appBean = vreq.getAppBean(); String portalType = null; int portalId = portal.getPortalId(); String appName = portal.getAppName(); if ( (appBean.getMaxSharedPortalId()-appBean.getMinSharedPortalId()) > 1 && ( (portalId >= appBean.getMinSharedPortalId() && portalId <= appBean.getMaxSharedPortalId() ) || portalId == appBean.getSharedPortalFlagNumeric() ) ) { portalType = "CALSResearch"; } else if (appName.equalsIgnoreCase("CALS Impact")) { portalType = "CALSImpact"; } else if (appName.equalsIgnoreCase("VIVO")){ portalType = "VIVO"; } else { portalType = "clone"; } body.put("portalType", portalType); body.put("portalId", portalId); body.put("formAction", "submitFeedback"); if (vreq.getHeader("Referer") == null) { vreq.getSession().setAttribute("contactFormReferer","none"); } else { vreq.getSession().setAttribute("contactFormReferer",vreq.getHeader("Referer")); } bodyTemplate = "contactForm-form.ftl"; } return mergeBodyToTemplate(bodyTemplate, body, config); } }
package gov.nih.nci.calab.ui.core; /** * This class initializes session and application scope data to prepopulate the drop-down lists required * in different view pages. * * @author pansu */ /* CVS $Id: InitSessionAction.java,v 1.38 2006-05-05 15:41:58 pansu Exp $ */ import gov.nih.nci.calab.dto.administration.AliquotBean; import gov.nih.nci.calab.dto.administration.ContainerInfoBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean; import gov.nih.nci.calab.service.administration.ManageAliquotService; import gov.nih.nci.calab.service.administration.ManageSampleService; import gov.nih.nci.calab.service.common.LookupService; import gov.nih.nci.calab.service.search.SearchSampleService; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.service.util.file.HttpFileUploadSessionData; import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class InitSessionAction extends AbstractDispatchAction { public ActionForward createRun(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "createRun"); setCreateRunSession(request); return mapping.findForward("createRun"); } public ActionForward createAssayRun(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "createAssayRun"); setCreateRunSession(request); return mapping.findForward("createAssayRun"); } private void setCreateRunSession(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); LookupService lookupService = new LookupService(); ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService(); if (session.getServletContext().getAttribute("allAssayTypes") == null) { List assayTypes = lookupService.getAllAssayTypes(); session.getServletContext().setAttribute("allAssayTypes", assayTypes); } if (session.getAttribute("workflow") == null || session.getAttribute("newWorkflowCreated") != null) { ExecuteWorkflowBean workflowBean = executeWorkflowService .getExecuteWorkflowBean(); session.setAttribute("workflow", workflowBean); } if (session.getAttribute("allUnmaskedAliquots") == null || session.getAttribute("newAliquotCreated") != null) { List aliquots = lookupService.getUnmaskedAliquots(); session.setAttribute("allUnmaskedAliquots", aliquots); } if (session.getAttribute("allAssignedAliquots") == null) { List allAssignedAliquots = lookupService.getAllAssignedAliquots(); session.setAttribute("allAssignedAliquots", allAssignedAliquots); } if (session.getServletContext().getAttribute("allAssayBeans") == null) { List allAssayBeans = lookupService.getAllAssayBeans(); session.getServletContext().setAttribute("allAssayBeans", allAssayBeans); } if (session.getServletContext().getAttribute("allUserBeans") == null) { List allUserBeans = lookupService.getAllUserBeans(); session.getServletContext().setAttribute("allUserBeans", allUserBeans); } session.removeAttribute("newWorkflowCreated"); session.removeAttribute("newAliquotCreated"); } public ActionForward useAliquot(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "useAliquot"); HttpSession session = request.getSession(); LookupService lookupService = new LookupService(); if (session.getAttribute("allUnmaskedAliquots") == null || session.getAttribute("newAliquotCreated") != null) { List<AliquotBean> allAliquots = lookupService.getUnmaskedAliquots(); session.setAttribute("allUnmaskedAliquots", allAliquots); } ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService(); if (session.getAttribute("workflow") == null || session.getAttribute("newWorkflowCreated") != null) { ExecuteWorkflowBean workflowBean = executeWorkflowService .getExecuteWorkflowBean(); session.setAttribute("workflow", workflowBean); } // clear the new aliquote created flag session.removeAttribute("newAliquotCreated"); // clear the new workflow created flag session.removeAttribute("newWorkflowcreated"); return mapping.findForward("useAliquot"); } public ActionForward createSample(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "createSample"); HttpSession session = request.getSession(); LookupService lookupService = new LookupService(); ManageSampleService mangeSampleService = new ManageSampleService(); // if values don't exist in the database or if no new samples created. // call the service if (session.getAttribute("allSampleContainerTypes") == null || session.getAttribute("newSampleCreated") != null) { List containerTypes = lookupService.getAllSampleContainerTypes(); session.setAttribute("allSampleContainerTypes", containerTypes); } if (session.getServletContext().getAttribute("allSampleTypes") == null) { List sampleTypes = lookupService.getAllSampleTypes(); session.getServletContext().setAttribute("allSampleTypes", sampleTypes); } if (session.getServletContext().getAttribute("allSampleSOPs") == null) { List sampleSOPs = mangeSampleService.getAllSampleSOPs(); session.getServletContext().setAttribute("allSampleSOPs", sampleSOPs); } if (session.getServletContext().getAttribute("sampleContainerInfo") == null) { ContainerInfoBean containerInfo = lookupService .getSampleContainerInfo(); session.getServletContext().setAttribute("sampleContainerInfo", containerInfo); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); return mapping.findForward("createSample"); } public ActionForward createAliquot(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "createAliquot"); HttpSession session = request.getSession(); LookupService lookupService = new LookupService(); ManageAliquotService manageAliquotService = new ManageAliquotService(); if (session.getAttribute("allSamples") == null || session.getAttribute("newSampleCreated") != null) { List samples = lookupService.getAllSamples(); session.setAttribute("allSamples", samples); } if (session.getAttribute("allAliquotContainerTypes") == null || session.getAttribute("newAliquotCreated") != null) { List containerTypes = lookupService.getAllAliquotContainerTypes(); session.setAttribute("allAliquotContainerTypes", containerTypes); } if (session.getAttribute("allUnmaskedAliquots") == null || session.getAttribute("newAliquotCreated") != null) { List aliquots = lookupService.getUnmaskedAliquots(); session.setAttribute("allUnmaskedAliquots", aliquots); } if (session.getServletContext().getAttribute("aliquotContainerInfo") == null) { ContainerInfoBean containerInfo = lookupService .getAliquotContainerInfo(); session.getServletContext().setAttribute("aliquotContainerInfo", containerInfo); } if (session.getServletContext().getAttribute("aliquotCreateMethods") == null) { List methods = manageAliquotService.getAliquotCreateMethods(); session.getServletContext().setAttribute("aliquotCreateMethods", methods); } // clear new aliquot created flag and new sample created flag session.removeAttribute("newAliquotCreated"); session.removeAttribute("newSampleCreated"); return mapping.findForward("createAliquot"); } public ActionForward searchWorkflow(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "searchWorkflow"); HttpSession session = request.getSession(); LookupService lookupService = new LookupService(); if (session.getServletContext().getAttribute("allAssayTypes") == null) { List assayTypes = lookupService.getAllAssayTypes(); session.getServletContext().setAttribute("allAssayTypes", assayTypes); } if (session.getServletContext().getAttribute("allUsernames") == null) { List allUserBeans = lookupService.getAllUserBeans(); session.getServletContext().setAttribute("allUserBeans", allUserBeans); } return mapping.findForward("searchWorkflow"); } public ActionForward searchSample(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "searchSample"); HttpSession session = request.getSession(); LookupService lookupService = new LookupService(); SearchSampleService searchSampleService = new SearchSampleService(); if (session.getServletContext().getAttribute("allSampleTypes") == null) { List sampleTypes = lookupService.getAllSampleTypes(); session.getServletContext().setAttribute("allSampleTypes", sampleTypes); } if (session.getAttribute("allSampleSources") == null || session.getAttribute("newSampleCreated") != null) { List sampleSources = searchSampleService.getAllSampleSources(); session.setAttribute("allSampleSources", sampleSources); } if (session.getAttribute("allSourceSampleIds") == null || session.getAttribute("newSampleCreated") != null) { List sourceSampleIds = searchSampleService.getAllSourceSampleIds(); session.setAttribute("allSourceSampleIds", sourceSampleIds); } if (session.getServletContext().getAttribute("allUserBeans") == null) { List allUserBeans = lookupService.getAllUserBeans(); session.getServletContext().setAttribute("allUserBeans", allUserBeans); } if (session.getServletContext().getAttribute("sampleContainerInfo") == null) { ContainerInfoBean containerInfo = lookupService .getSampleContainerInfo(); session.getServletContext().setAttribute("sampleContainerInfo", containerInfo); } if (session.getServletContext().getAttribute("aliquotContainerInfo") == null) { ContainerInfoBean containerInfo = lookupService .getAliquotContainerInfo(); session.getServletContext().setAttribute("aliquotContainerInfo", containerInfo); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); return mapping.findForward("searchSample"); } public ActionForward workflowMessage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "workflowMessage"); setWorkflowMessageSession(request); return mapping.findForward("workflowMessage"); } public ActionForward fileUploadOption(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "fileUploadOption"); setWorkflowMessageSession(request); return mapping.findForward("fileUploadOption"); } public ActionForward fileDownload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "fileDownload"); setWorkflowMessageSession(request); return mapping.findForward("fileDownload"); } public ActionForward runFileMask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "runFileMask"); setWorkflowMessageSession(request); return mapping.findForward("runFileMask"); } public ActionForward uploadForward(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { clearSessionData(request, "uploadForward"); setWorkflowMessageSession(request); HttpSession session = request.getSession(); // read HttpFileUploadSessionData from session HttpFileUploadSessionData hFileUploadData = (HttpFileUploadSessionData) request .getSession().getAttribute("httpFileUploadSessionData"); // based on the type=in/out/upload and runId to modify the // forwardPage String type = hFileUploadData.getFromType(); String runId = hFileUploadData.getRunId(); String inout = hFileUploadData.getInout(); String runName = hFileUploadData.getRun(); session.removeAttribute("httpFileUploadSessionData"); String urlPrefix = request.getContextPath(); if (type.equalsIgnoreCase("in") || type.equalsIgnoreCase("out")) { // cannot forward to a page with the request parameter, so // use response response.sendRedirect(urlPrefix + "/workflowForward.do?type=" + type + "&runName=" + runName + "&runId=" + runId + "&inout=" + inout); } else if (type.equalsIgnoreCase("upload")) { session.setAttribute("runId", runId); String forwardPage = "fileUploadOption"; return mapping.findForward(forwardPage); } return null; } private void setWorkflowMessageSession(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService(); if (session.getAttribute("workflow") == null || session.getAttribute("newWorkflowCreated") != null) { ExecuteWorkflowBean workflowBean = executeWorkflowService .getExecuteWorkflowBean(); session.setAttribute("workflow", workflowBean); } session.removeAttribute("newWorkflowCreated"); } public boolean loginRequired() { return true; } private void clearSessionData(HttpServletRequest request, String forwardPage) { HttpSession session = request.getSession(); if (!forwardPage.equals("createAliquot")) { // clear session attributes created during create aliquot session.removeAttribute("allSamples"); session.removeAttribute("allAliquotContainerTypes"); } session.removeAttribute("aliquotMatrix"); session.removeAttribute("createAliquotForm"); session.removeAttribute("createSampleForm"); if (!forwardPage.equals("createSample")) { // clear session attributes created during create sample session.removeAttribute("allSampleContainerTypes"); } if (!forwardPage.equals("searchSample")) { // clear session attributes created during search sample session.removeAttribute("samples"); session.removeAttribute("aliquots"); } if (!forwardPage.equals("uploadForward")) { // clear session attributes creatd during fileUpload session.removeAttribute("httpFileUploadSessionData"); } if (forwardPage.equals("createSample") || forwardPage.equals("createAliquot") || forwardPage.equals("searchSample") || forwardPage.equals("searchWorkflow")) { // clear session attributes created during execute workflow pages session.removeAttribute("workflow"); } // get user and date information String creator = ""; if (session.getAttribute("user") != null) { UserBean user = (UserBean) session.getAttribute("user"); creator = user.getLoginId(); } String creationDate = StringUtils.convertDateToString(new Date(), CalabConstants.DATE_FORMAT); session.setAttribute("creator", creator); session.setAttribute("creationDate", creationDate); } }
package pl.edu.pw.ii.pik01.seeknresolve.controller.user; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import pl.edu.pw.ii.pik01.seeknresolve.domain.common.test.builders.UserBuilder; import pl.edu.pw.ii.pik01.seeknresolve.domain.dto.ChangePasswordDTO; import pl.edu.pw.ii.pik01.seeknresolve.domain.dto.CreateUserDTO; import pl.edu.pw.ii.pik01.seeknresolve.domain.entity.User; import pl.edu.pw.ii.pik01.seeknresolve.domain.entity.UserRole; import pl.edu.pw.ii.pik01.seeknresolve.service.common.DtosFactory; import pl.edu.pw.ii.pik01.seeknresolve.service.user.UserService; import javax.persistence.EntityNotFoundException; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(MockitoJUnitRunner.class) public class UserControllerTest { private MockMvc mockMvc; @Mock private UserService userService; @Before public void setUp() { UserController userController = new UserController(userService); mockMvc = MockMvcBuilders.standaloneSetup(userController).build(); } @Test public void shouldReturn404ForNonExistingUser() throws Exception { when(userService.findByLogin(anyString())).thenThrow(EntityNotFoundException.class); mockMvc.perform(get("/user/details/NonExistingUser")). andExpect(status().isNotFound()). andExpect(content().contentType(MediaType.APPLICATION_JSON)); } @Test public void shouldReturn200AndUserData() throws Exception { User existingUser = new UserBuilder().withLogin("cthulu") .withFirstName("Al-Khadhulu") .withLastName("Kuthulu") .withEmail("cthulu@worldDestroyer.xx") .withRole(new UserRole("God")) .build(); when(userService.findByLogin("cthulu")).thenReturn(DtosFactory.createUserDetailsDTO(existingUser)); mockMvc.perform(get("/user/details/cthulu")). andExpect(status().isOk()). andExpect(content().contentType(MediaType.APPLICATION_JSON)). andExpect(jsonPath("$.error").doesNotExist()). andExpect(jsonPath("$.object.login").value("cthulu")). andExpect(jsonPath("$.object.firstName").value("Al-Khadhulu")). andExpect(jsonPath("$.object.lastName").value("Kuthulu")). andExpect(jsonPath("$.object.email").value("cthulu@worldDestroyer.xx")). andExpect(jsonPath("$.object.userRole").value("God")); } @Test public void shouldCreateUser() throws Exception { CreateUserDTO createUserDTO = new CreateUserDTO(); createUserDTO.setLogin("AwasomeLogin"); createUserDTO.setPassword("Password"); createUserDTO.setUserRole("USER"); when(userService.createAndSaveNewUser(any())).thenAnswer(Return.firstParameter()); mockMvc.perform(post("/user/create"). contentType(MediaType.APPLICATION_JSON). content(asJson(createUserDTO))). andExpect(status().isOk()). andExpect(content().contentType(MediaType.APPLICATION_JSON)). andExpect(jsonPath("$.status").value("CREATED")). andExpect(jsonPath("$.object.login").value("AwasomeLogin")); } @Test public void testChangePassword() throws Exception { ChangePasswordDTO changePasswordDTO = new ChangePasswordDTO("mdz", "qwerty", "qwerty"); mockMvc.perform(post("/user/changePassword"). contentType(MediaType.APPLICATION_JSON). content(asJson(changePasswordDTO))). andExpect(status().isOk()). andExpect(content().contentType(MediaType.APPLICATION_JSON)). andExpect(jsonPath("$.status").value("UPDATED")); } private String asJson(Object object) throws JsonProcessingException { return new ObjectMapper().writeValueAsString(object); } private static class Return<T> implements Answer<T> { private int paramNumber = 0; public static <Z> Return<Z> firstParameter() { Return<Z> r = new Return<>(); r.paramNumber = 0; return r; } @Override @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { return (T) invocation.getArguments()[paramNumber]; } } }
package io.github.secondflight.Parkour.Main; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; public class Parkour extends JavaPlugin implements Listener{ public final Logger logger = Logger.getLogger("Minecraft"); public Parkour plugin; public static Map<Player, String> edit = new HashMap<Player, String>(); public static Map<Player, String> string = new HashMap<Player, String>(); public static Map<Player, Block> block = new HashMap<Player, Block>(); public void onEnable() { plugin = this; PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info(pdfFile.getName() + " has been Enabled."); getServer().getPluginManager().registerEvents(this, this); getConfig().options().copyDefaults(true); saveConfig(); } public void onDisable() { } @EventHandler public void clickEvent (PlayerInteractEvent event) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { Block b = event.getClickedBlock(); for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) { if (!(getConfig().get("courses." + s + ".start.x") == null)) { if (b.getX() == getConfig().getInt("courses." + s + ".start.x") && b.getY() == getConfig().getInt("courses." + s + ".start.y") && b.getZ() == getConfig().getInt("courses." + s + ".start.z")) { event.getPlayer().sendMessage("start"); } } if (!(getConfig().get("courses." + s + ".end.x") == null)) { if (b.getX() == getConfig().getInt("courses." + s + ".end.x") && b.getY() == getConfig().getInt("courses." + s + ".end.y") && b.getZ() == getConfig().getInt("courses." + s + ".end.z")) { event.getPlayer().sendMessage("end"); } } } } } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(sender instanceof Player) { Player player = (Player) sender; if (command.getName().equalsIgnoreCase("parkour") && args.length == 3 && args[0].equalsIgnoreCase("new")) { boolean error = false; try { Integer.parseInt(args[2]); } catch (Exception ex) { error = true; } if (!error) { if ((!(getConfig().get("courses") == null) && !(getConfig().getConfigurationSection("courses").getKeys(false).contains(args[1]))) || getConfig().get("courses") == null) { getConfig().set("courses." + args[1] + ".world", player.getWorld().getName()); getConfig().set("courses." + args[1] + ".points", Integer.parseInt(args[2])); //saveConfig(); player.sendMessage("A new course has been created. Do " + ChatColor.RED + "/parkour edit " + args[1] + ChatColor.WHITE + " to continue."); } else { player.sendMessage(ChatColor.RED + "There is already a parkour end sign with that name!"); player.sendMessage(""); player.sendMessage(" If you would like to make a new course with this name, please remove the old one first by using " + ChatColor.RED + "/parkour remove [name] " + ChatColor.WHITE + "or" + ChatColor.RED + " /parkour remove [index]" + ChatColor.WHITE + ". Note: You can also edit an existing parkour course by using " + ChatColor.RED + "/parkour edit [name] " + ChatColor.WHITE + "or" + ChatColor.RED + " /parkour edit [index]" + ChatColor.WHITE + "."); } } else { player.sendMessage(ChatColor.RED + "Invalid arguments - [points] must be a number."); player.sendMessage(""); player.sendMessage(ChatColor.RED + "Usage: /parkour new [name] [points]"); player.sendMessage("See " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info."); } } else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("new") && !(args.length == 3)) { player.sendMessage(ChatColor.RED + "Usage: /parkour new [name] [points]"); player.sendMessage("See " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info."); } if (command.getName().equalsIgnoreCase("parkour") && args.length == 1 && args[0].equalsIgnoreCase("list")) { if (!(getConfig().get("courses") == null)) { if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) { player.sendMessage("Here are the active parkour end points:"); player.sendMessage(""); for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) { player.sendMessage(ChatColor.YELLOW + "Name: " + ChatColor.WHITE + s); player.sendMessage("Start X: " + getConfig().get("courses." + s + ".start.x")); player.sendMessage("Start Y: " + getConfig().get("courses." + s + ".start.y")); player.sendMessage("Start Z: " + getConfig().get("courses." + s + ".start.z")); player.sendMessage("End X: " + getConfig().get("courses." + s + ".end.x")); player.sendMessage("End Y: " + getConfig().get("courses." + s + ".end.y")); player.sendMessage("End Z: " + getConfig().get("courses." + s + ".end.z")); player.sendMessage("World: " + getConfig().get("courses." + s + ".world")); player.sendMessage("Point value: " + getConfig().get("courses." + s + ".points")); if (Bukkit.getServer().getWorld(getConfig().getString("courses." + s + ".world")).getBlockAt(getConfig().getInt("courses." + s + ".start.x"), getConfig().getInt("courses." + s + ".start.y"), getConfig().getInt("courses." + s + ".start.z")).getType() == Material.AIR) { player.sendMessage(ChatColor.RED + "WARNING: There is no block at the start location, making it inaccessable."); player.sendMessage("This can be fixed by placing a block, such as a sign, at the location. You can teleport to this location by using " + ChatColor.RED + "/parkour tp " + s + ChatColor.WHITE + "."); } if (Bukkit.getServer().getWorld(getConfig().getString("courses." + s + ".world")).getBlockAt(getConfig().getInt("courses." + s + ".end.x"), getConfig().getInt("courses." + s + ".end.y"), getConfig().getInt("courses." + s + ".end.z")).getType() == Material.AIR) { player.sendMessage(ChatColor.RED + "WARNING: There is no block at the end location, making it inaccessable."); player.sendMessage("This can be fixed by placing a block, such as a sign, at the location. You can teleport to this location by using " + ChatColor.RED + "/parkour tp " + s + ChatColor.WHITE + "."); } player.sendMessage(""); } }else { player.sendMessage("There are no parkour end points in the config right now."); player.sendMessage("See " + ChatColor.RED + "/parkour new" + ChatColor.WHITE + " to add one."); } } else { player.sendMessage("There are no parkour end points in the config right now."); player.sendMessage("See " + ChatColor.RED + "/parkour new" + ChatColor.WHITE + " to add one."); } } else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("list") && !(args.length == 1)) { player.sendMessage(ChatColor.RED + "Usage: /parkour list"); player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info."); } if (command.getName().equalsIgnoreCase("parkour") && args.length == 2 && args[0].equalsIgnoreCase("tp")) { if (!(getConfig().get("courses") == null)) { if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) { boolean error = true; for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) { if (s.equals(args[1])) { error = false; break; } } if (!error) { player.teleport (new Location(Bukkit.getServer().getWorld(getConfig().getString("courses." + args[1] + ".world")), (double) getConfig().getInt("courses." + args[1] + ".end.x") + 0.5, (double) getConfig().getInt("courses." + args[1] + ".end.y"), (double) getConfig().getInt("courses." + args[1] + ".end.z") + 0.5)); } else { player.sendMessage(ChatColor.RED + "Invalid course name."); player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names."); } } else { player.sendMessage(ChatColor.RED + "There are no active parkour courses to teleport to."); player.sendMessage("You can use " + ChatColor.RED + "/parkour new [name] [point value]" + ChatColor.WHITE + " to make a new one."); } } else { player.sendMessage(ChatColor.RED + "There are no active parkour courses to teleport to."); player.sendMessage("You can use " + ChatColor.RED + "/parkour new [name] [point value]" + ChatColor.WHITE + " to make a new one."); } } else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("tp") && !(args.length == 2)) { player.sendMessage(ChatColor.RED + "Usage: /parkour tp [course name]"); player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names."); player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info."); } if (command.getName().equalsIgnoreCase("parkour") && args.length == 2 && args[0].equalsIgnoreCase("remove")) { if (!(getConfig().get("courses") == null)) { if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) { boolean error = true; for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) { if (s.equals(args[1])) { error = false; break; } } if (!error) { getConfig().getConfigurationSection("courses").set(args[1], null); //saveConfig(); player.sendMessage("Course '" + args[1] + "' has successfully been removed."); } else { player.sendMessage(ChatColor.RED + "Invalid course name."); player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names."); } } else { player.sendMessage(ChatColor.RED + "There are no active parkour courses to remove."); } } else { player.sendMessage(ChatColor.RED + "There are no active parkour courses to remove."); } } else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("remove") && !(args.length == 2)) { player.sendMessage(ChatColor.RED + "Usage: /parkour remove [course name]"); player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info."); } if (command.getName().equalsIgnoreCase("parkour") && args.length > 2 && args[0].equalsIgnoreCase("edit")) { if (!(getConfig().get("courses") == null)) { if (getConfig().getConfigurationSection("courses").getKeys(false).size() > 0) { boolean error = true; for (String s : getConfig().getConfigurationSection("courses").getKeys(false)) { if (s.equals(args[1])) { error = false; break; } } if (!error) { if (args[2].equalsIgnoreCase("setstart")) { getConfig().set("courses." + args[1] + ".start.x", player.getLocation().getBlockX()); getConfig().set("courses." + args[1] + ".start.y", player.getLocation().getBlockY()); getConfig().set("courses." + args[1] + ".start.z", player.getLocation().getBlockZ()); player.sendMessage(ChatColor.GREEN + "The start point for '" + args[1] + "' has been set to your current location."); } else if (args[2].equalsIgnoreCase("setend")) { getConfig().set("courses." + args[1] + ".end.x", player.getLocation().getBlockX()); getConfig().set("courses." + args[1] + ".end.y", player.getLocation().getBlockY()); getConfig().set("courses." + args[1] + ".end.z", player.getLocation().getBlockZ()); player.sendMessage(ChatColor.GREEN + "The end point for '" + args[1] + "' has been set to your current location."); } else if (args.length == 4 && args[2].equalsIgnoreCase("setname")) { getConfig().set("courses." + args[1] + ".end.x", args[3]); } } else { player.sendMessage(ChatColor.RED + "Invalid course name."); player.sendMessage("You can use " + ChatColor.RED + "/parkour list" + ChatColor.WHITE + " to get all the active courses and their names."); } } else { player.sendMessage(ChatColor.RED + "There are no active parkour courses to edit."); } } else { player.sendMessage(ChatColor.RED + "There are no active parkour courses to edit."); } } else if (command.getName().equalsIgnoreCase("parkour") && args[0].equalsIgnoreCase("edit") && !(args.length > 2)) { //TODO: usage player.sendMessage(ChatColor.RED + "Usage: /parkour edit [course name] [action]"); player.sendMessage("Use " + ChatColor.RED + "/parkour help" + ChatColor.WHITE + " for more info."); } if (command.getName().equalsIgnoreCase("test")) { // test goes here lel } } return false; } }
package jade.tools.introspector.gui; import javax.swing.*; import java.awt.event.*; /** This class listens to the events fired by the main menu bar. @author Andrea Squeri,Corti Denis,Ballestracci Paolo - Universita` di Parma @version $Date$ $Revision$ */ public class MainBarListener implements ActionListener{ private MainWindow mainWnd; public MainBarListener(MainWindow main){ mainWnd=main; } public void actionPerformed(ActionEvent e){ AbstractButton source=(AbstractButton) e.getSource(); int ID=source.getMnemonic(); switch(ID){ case 2: //view message+state JCheckBoxMenuItem item=(JCheckBoxMenuItem) source; if (item.isSelected()) mainWnd.setMessagePanelVisible(true); else mainWnd.setMessagePanelVisible(false); break; case 3://view Behaviour JCheckBoxMenuItem item1=(JCheckBoxMenuItem) source; if (item1.isSelected()) mainWnd.setBehaviourPanelVisible(true); else mainWnd.setBehaviourPanelVisible(false); break; case 4://kill System.out.println("kill agent"); break; case 5://suspend System.out.println("suspend agent"); break; case 6://wakeup System.out.println("WakeUp agent"); break; case 7://wait System.out.println("wait agent"); break; } } }
package won.matcher.sparql.actor; import java.io.IOException; import java.net.URI; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.jena.graph.Node; import org.apache.jena.graph.Triple; import org.apache.jena.query.Dataset; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelExtract; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StatementBoundary; import org.apache.jena.rdf.model.StatementBoundaryBase; import org.apache.jena.rdf.model.impl.ResourceImpl; import org.apache.jena.sparql.algebra.Algebra; import org.apache.jena.sparql.algebra.Op; import org.apache.jena.sparql.algebra.OpAsQuery; import org.apache.jena.sparql.algebra.op.OpBGP; import org.apache.jena.sparql.algebra.op.OpDistinct; import org.apache.jena.sparql.algebra.op.OpProject; import org.apache.jena.sparql.algebra.op.OpUnion; import org.apache.jena.sparql.core.BasicPattern; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.engine.binding.BindingFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.github.jsonldjava.core.JsonLdError; import akka.actor.ActorRef; import akka.actor.OneForOneStrategy; import akka.actor.SupervisorStrategy; import akka.actor.UntypedActor; import akka.cluster.pubsub.DistributedPubSub; import akka.cluster.pubsub.DistributedPubSubMediator; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Function; import scala.concurrent.duration.Duration; import won.matcher.service.common.event.BulkHintEvent; import won.matcher.service.common.event.BulkAtomEvent; import won.matcher.service.common.event.HintEvent; import won.matcher.service.common.event.AtomEvent; import won.matcher.sparql.config.SparqlMatcherConfig; import won.protocol.model.AtomState; import won.protocol.util.AtomModelWrapper; import won.protocol.util.RdfUtils; import won.protocol.util.linkeddata.LinkedDataSource; import won.protocol.vocabulary.WON; /** * Siren/Solr based abstract matcher with all implementations for querying as * well as indexing atoms. */ @Component @Scope("prototype") public class SparqlMatcherActor extends UntypedActor { private LoggingAdapter log = Logging.getLogger(getContext().system(), this); private ActorRef pubSubMediator; @Autowired private SparqlMatcherConfig config; @Autowired private LinkedDataSource linkedDataSource; @Override public void preStart() throws IOException { // subscribe to atom events pubSubMediator = DistributedPubSub.get(getContext().system()).mediator(); } @Override public void onReceive(final Object o) throws Exception { String eventTypeForLogging = "unknown"; Optional<String> uriForLogging = Optional.empty(); try { if (o instanceof AtomEvent) { eventTypeForLogging = "AtomEvent"; AtomEvent atomEvent = (AtomEvent) o; uriForLogging = Optional.ofNullable(atomEvent.getUri()); if (atomEvent.getEventType().equals(AtomEvent.TYPE.ACTIVE)) { processActiveAtomEvent(atomEvent); } else if (atomEvent.getEventType().equals(AtomEvent.TYPE.INACTIVE)) { processInactiveAtomEvent(atomEvent); } else { unhandled(o); } } else if (o instanceof BulkAtomEvent) { eventTypeForLogging = "BulkAtomEvent"; log.info("received bulk atom event, processing {} atom events ...", ((BulkAtomEvent) o).getAtomEvents().size()); for (AtomEvent event : ((BulkAtomEvent) o).getAtomEvents()) { processActiveAtomEvent(event); } } else { eventTypeForLogging = "unhandled"; unhandled(o); } } catch (Exception e) { log.info(String.format("Caught exception when processing %s event %s. More info on loglevel 'debug'", eventTypeForLogging, uriForLogging.orElse("[no uri available]"))); log.debug("caught exception", e); if (log.isDebugEnabled()) { e.printStackTrace(); } } } protected void processInactiveAtomEvent(AtomEvent atomEvent) throws IOException, JsonLdError { log.info("Received inactive atom."); } private static String hashFunction(Object input) { return Integer.toHexString(input.hashCode()); } private static final Var resultName = Var.alloc("result"); private static final Var thisAtom = Var.alloc("thisAtom"); private static final Var scoreName = Var.alloc("score"); private static BasicPattern createDetailsQuery(Model model, Statement parentStatement) { BasicPattern pattern = new BasicPattern(); StreamSupport.stream(Spliterators.spliteratorUnknownSize(model.listStatements(), Spliterator.CONCURRENT), true) .map((statement) -> { Triple triple = statement.asTriple(); RDFNode object = statement.getObject(); Node newSubject = Var.alloc(hashFunction(triple.getSubject())); Node newObject = triple.getObject(); if (triple.getSubject().equals(parentStatement.getObject().asNode())) { newSubject = resultName.asNode(); } if (object.isAnon()) { newObject = Var.alloc(hashFunction(newObject)); } return new Triple(newSubject, triple.getPredicate(), newObject); }).filter(p -> p != null).forEach(pattern::add); return pattern; } private static Op createAtomQuery(Model model, Statement parentStatement) { StatementBoundary boundary = new StatementBoundaryBase() { public boolean stopAt(Statement s) { return parentStatement.getSubject().equals(s.getSubject()); } }; Model subModel = new ModelExtract(boundary).extract(parentStatement.getObject().asResource(), model); BasicPattern pattern = createDetailsQuery(subModel, parentStatement); if (pattern.isEmpty()) { return null; } return new OpBGP(pattern); } /** * Produces hints for the atom and possibly also 'inverse' hints. Inverse hints * are hints sent to the atoms we find as matches for the original atom. The * score is calculated as a function of scores provided by the embedded sparql * queries: the range of those scores is projected on a range of 0-1. For * inverse matches, the score is always 100%, because there is only one possible * match - the original atom. Note: this could be improved by remembering * reported match scores in the matcher and using historic scores for * normalization, but that's a lot more work. */ protected void processActiveAtomEvent(AtomEvent atomEvent) throws IOException { AtomModelWrapper atom = new AtomModelWrapper(atomEvent.deserializeAtomDataset()); log.debug("starting sparql-based matching for atom {}", atom.getAtomUri()); List<ScoredAtom> matches = queryAtom(atom); log.debug("found {} match candidates", matches.size()); // produce hints after post-filtering the matches we found: Collection<HintEvent> hintEvents = produceHints(atom, matches.stream().filter(foundAtom -> foundAtom.atom.getAtomState() == AtomState.ACTIVE) // may // not // have // updated // our // atom // state // the // database. // re-check! .filter(foundAtom -> postFilter(atom, foundAtom.atom)) .collect(Collectors.toList())); publishHintEvents(hintEvents, atom.getAtomUri(), false); // but use the whole list of matches for inverse matching final boolean noHintForCounterpart = atom.flag(WON.NoHintForCounterpart); if (!noHintForCounterpart) { // we want do do inverse matching: // 1. check if the inverse match is appropriate // 2. do post-filtering // 3. produce hints // 4. collect all inverse hints and publish in one event Dataset atomDataset = atom.copyDataset(); List<HintEvent> inverseHintEvents = matches.stream().filter(n -> n.atom.getAtomState() == AtomState.ACTIVE) .filter(matchedAtom -> !matchedAtom.atom.flag(WON.NoHintForMe) && !atom.getAtomUri().equals(matchedAtom.atom.getAtomUri())) .map(matchedAtom -> { // query for the matched atom - but only in the dataset containing the original // atom. If we have a match, it means // that the matched atom should also get a hint, otherwise it should not. if (log.isDebugEnabled()) { log.debug("checking if match {} of {} should get a hint by inverse matching it in atom's dataset: \n{}", new Object[] { matchedAtom.atom.getAtomUri(), atom.getAtomUri(), RdfUtils.toString(atomDataset) }); } List<ScoredAtom> matchesForMatchedAtom = queryAtom(matchedAtom.atom, Optional.of(new AtomModelWrapperAndDataset(atom, atomDataset))); if (log.isDebugEnabled()) { log.debug("match {} of {} is also getting a hint: {}", new Object[] { matchedAtom.atom.getAtomUri(), atom.getAtomUri(), matchesForMatchedAtom.size() > 0 }); } return new AbstractMap.SimpleEntry<>(matchedAtom.atom, matchesForMatchedAtom.stream() .filter(n -> n.atom.getAtomState() == AtomState.ACTIVE) .filter(inverseMatch -> postFilter(matchedAtom.atom, inverseMatch.atom)) .collect(Collectors.toList())); }).map(entry -> produceHints(entry.getKey(), entry.getValue())) .flatMap(hints -> hints.stream()).collect(Collectors.toList()); // now that we've collected all inverse hints, publish them publishHintEvents(inverseHintEvents, atom.getAtomUri(), true); } log.debug("finished sparql-based matching for atom {}", atom.getAtomUri()); } private Collection<HintEvent> produceHints(AtomModelWrapper atom, List<ScoredAtom> matches) { // find max score Optional<Double> maxScore = matches.stream().map(n -> n.score).max((x, y) -> (int) Math.signum(x - y)); if (!maxScore.isPresent()) { // this should not happen return Collections.EMPTY_LIST; } // find min score Optional<Double> minScore = matches.stream().map(n -> n.score).min((x, y) -> (int) Math.signum(x - y)); if (!maxScore.isPresent()) { // this should not happen return Collections.EMPTY_LIST; } double range = (maxScore.get() - minScore.get()); return matches.stream().sorted((hint1, hint2) -> (int) Math.signum(hint2.score - hint1.score)) // sort // descending .limit(config.getLimitResults()).map(hint -> { double score = range == 0 ? 1.0 : (hint.score - minScore.get()) / range; return new HintEvent(atom.getWonNodeUri(), atom.getAtomUri(), hint.atom.getWonNodeUri(), hint.atom.getAtomUri(), config.getMatcherUri(), score); }).collect(Collectors.toList()); } /** * publishes the specified hint events. * * @param hintEvents the collection of HintEvent to publish * @param atomURI used for logging * @param inverse used for logging */ private void publishHintEvents(Collection<HintEvent> hintEvents, String atomURI, boolean inverse) { BulkHintEvent bulkHintEvent = new BulkHintEvent(); bulkHintEvent.addHintEvents(hintEvents); pubSubMediator.tell(new DistributedPubSubMediator.Publish(bulkHintEvent.getClass().getName(), bulkHintEvent), getSelf()); log.debug("sparql-based " + (inverse ? "inverse " : "") + "matching for atom {} (found {} matches)", atomURI, bulkHintEvent.getHintEvents().size()); } private Optional<Op> clientSuppliedQuery(String queryString) { Query query = QueryFactory.create(queryString); if (query.getQueryType() != Query.QueryTypeSelect) { return Optional.empty(); } if (!query.getProjectVars().contains(resultName)) { return Optional.empty(); } Op op = Algebra.compile(query); return Optional.of(op); } private Optional<Op> defaultQuery(AtomModelWrapper atom) { Model model = atom.getAtomModel(); String atomURI = atom.getAtomUri(); ArrayList<Op> queries = new ArrayList<>(3); Statement seeks = model.getProperty(model.createResource(atomURI), model.createProperty("https://w3id.org/won/core#seeks")); if (seeks != null) { Op seeksQuery = createAtomQuery(model, seeks); if (seeksQuery != null) queries.add(seeksQuery); } Statement search = model.getProperty(model.createResource(atomURI), model.createProperty("https://w3id.org/won/core#hasSearchString")); if (search != null) { String searchString = search.getString(); queries.add(SparqlMatcherUtils.createSearchQuery(searchString, resultName, 2, true, true)); } return queries.stream().reduce((left, right) -> new OpUnion(left, right)) .map((union) -> new OpDistinct(new OpProject(union, Arrays.asList(new Var[] { resultName })))); } private List<ScoredAtom> queryAtom(AtomModelWrapper atom) { return queryAtom(atom, Optional.empty()); } /** * Query for matches to the atom, optionally the atomToCheck is used to search * in. If atomToCheck is passed, it is used as the result data iff the * atomToCheck is a match for atom. This saves us a linked data lookup for data * we already have. * * @param atom * @param atomToCheck * @return */ private List<ScoredAtom> queryAtom(AtomModelWrapper atom, Optional<AtomModelWrapperAndDataset> atomToCheck) { Optional<Op> query; Optional<String> userQuery = atom.getQuery(); if (userQuery.isPresent()) { query = clientSuppliedQuery(userQuery.get()); } else { query = defaultQuery(atom); } List<ScoredAtom> atoms = query.map(q -> { if (log.isDebugEnabled()) { log.debug("transforming query, adding 'no hint for counterpart' restriction: {}", q); } Op noHintForCounterpartQuery = SparqlMatcherUtils.noHintForCounterpartQuery(q, resultName); if (log.isDebugEnabled()) { log.debug("transformed query: {}", noHintForCounterpartQuery); log.debug("transforming query, adding 'wihout no hint for counterpart' restriction: {}", q); } Op hintForCounterpartQuery = SparqlMatcherUtils.hintForCounterpartQuery(q, resultName); if (log.isDebugEnabled()) { log.debug("transformed query: {}", hintForCounterpartQuery); } return Stream.concat(executeQuery(noHintForCounterpartQuery, atomToCheck, atom.getAtomUri()), executeQuery(hintForCounterpartQuery, atomToCheck, atom.getAtomUri())) .collect(Collectors.toList()); }).orElse(Collections.emptyList()); return atoms; } /** * Executes the query, optionally only searching in the atomToCheck. * * @param q * @param atomToCheck * @param atomURI - the URI of the atom we are matching for * @return */ private Stream<ScoredAtom> executeQuery(Op q, Optional<AtomModelWrapperAndDataset> atomToCheck, String atomURI) { Query compiledQuery = OpAsQuery.asQuery(q); // if we were given an atomToCheck, restrict the query result to that uri so // that // we get exactly one result if that uri is found for the atom List<Binding> valuesBlockBindings = new ArrayList<>(); List<Var> valuesBlockVariables = new ArrayList<>(); // bind the ?thisAtom variable to the atom we are matching for valuesBlockBindings.add(BindingFactory.binding(thisAtom, new ResourceImpl(atomURI.toString()).asNode())); valuesBlockVariables.add(thisAtom); if (atomToCheck.isPresent()) { valuesBlockBindings.add(BindingFactory.binding(resultName, new ResourceImpl(atomToCheck.get().atomModelWrapper.getAtomUri()).asNode())); valuesBlockVariables.add(resultName); } compiledQuery.setValuesDataBlock(valuesBlockVariables, valuesBlockBindings); // make sure we order by score, if present, and we limit the results if (compiledQuery.getProjectVars().contains(scoreName)) { compiledQuery.addOrderBy(scoreName, Query.ORDER_DESCENDING); } if (!compiledQuery.hasLimit() || compiledQuery.getLimit() > config.getLimitResults() * 5) { compiledQuery.setLimit(config.getLimitResults() * 5); } compiledQuery.setOffset(0); compiledQuery.setDistinct(true); if (log.isDebugEnabled()) { log.debug("executeQuery query: {}, atomToCheck: {}", new Object[] { compiledQuery, atomToCheck }); } List<ScoredAtomUri> foundUris = new LinkedList<>(); // process query results iteratively try (QueryExecution execution = QueryExecutionFactory.sparqlService(config.getSparqlEndpoint(), compiledQuery)) { ResultSet result = execution.execSelect(); while (result.hasNext()) { QuerySolution querySolution = result.next(); RDFNode atomUriNode = querySolution.get(resultName.getName()); if (atomUriNode == null || !atomUriNode.isURIResource()) { continue; } String foundAtomURI = atomUriNode.asResource().getURI(); double score = 1.0; if (querySolution.contains(scoreName.getName())) { RDFNode scoreNode = querySolution.get(scoreName.getName()); if (scoreNode != null && scoreNode.isLiteral()) { try { score = scoreNode.asLiteral().getDouble(); } catch (NumberFormatException e) { // if the score is not interpretable as double, ignore it } } } foundUris.add(new ScoredAtomUri(foundAtomURI, score)); } } catch (Exception e) { log.info("caught exception during sparql-based matching (more info on loglevel 'debug'): {} ", e.getMessage()); if (log.isDebugEnabled()) { e.printStackTrace(); } return Stream.empty(); } // load data in parallel return foundUris.parallelStream().map(foundAtomUri -> { try { // if we have an atomToCheck, return it if the URI we found actually is its URI, // otherwise null if ((atomToCheck.isPresent())) { AtomModelWrapper result = atomToCheck.get().atomModelWrapper.getAtomUri().equals(foundAtomUri.uri) ? atomToCheck.get().atomModelWrapper : null; if (result == null) { return null; } return new ScoredAtom(result, foundAtomUri.score); } else { // no atomToCheck, which happens when we first look for matches in the graph // store: // download the linked data and return a new AtomModelWrapper Dataset ds = linkedDataSource.getDataForResource(URI.create(foundAtomUri.uri)); // make sure we don't accidentally use empty or faulty results if (!AtomModelWrapper.isAAtom(ds)) { return null; } return new ScoredAtom(new AtomModelWrapper(ds), foundAtomUri.score); } } catch (Exception e) { log.info("caught exception trying to load atom URI {} : {} (more on loglevel 'debug')", foundAtomUri, e.getMessage()); if (log.isDebugEnabled()) { e.printStackTrace(); } return null; } }).filter(foundAtom -> foundAtom != null); } private static Set<String> getMatchingContexts(AtomModelWrapper atom) { Model model = atom.getAtomModel(); Resource atomURI = model.createResource(atom.getAtomUri()); Property matchingContextProperty = model.createProperty("https://w3id.org/won/core#matchingContext"); Stream<RDFNode> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize( model.listObjectsOfProperty(atomURI, matchingContextProperty), Spliterator.CONCURRENT), false); return stream.map(node -> node.asLiteral().getString()).collect(Collectors.toSet()); } private boolean postFilter(AtomModelWrapper atom, AtomModelWrapper foundAtom) { try { if (atom.getAtomUri().equals(foundAtom.getAtomUri())) { return false; } if (atom.flag(WON.NoHintForMe)) { return false; } if (foundAtom.flag(WON.NoHintForCounterpart)) { return false; } Set<String> atomContexts = getMatchingContexts(atom); if (!atomContexts.isEmpty()) { Set<String> foundAtomContexts = getMatchingContexts(foundAtom); foundAtomContexts.retainAll(atomContexts); if (foundAtomContexts.isEmpty()) { return false; } } Calendar now = Calendar.getInstance(); if (now.after(foundAtom.getDoNotMatchAfter())) return false; if (now.before(foundAtom.getDoNotMatchBefore())) return false; return true; } catch (Exception e) { log.info("caught Exception during post-filtering, ignoring match", e); } return false; } @Override public SupervisorStrategy supervisorStrategy() { SupervisorStrategy supervisorStrategy = new OneForOneStrategy(0, Duration.Zero(), new Function<Throwable, SupervisorStrategy.Directive>() { @Override public SupervisorStrategy.Directive apply(Throwable t) throws Exception { log.warning("Actor encountered error: {}", t); // default behaviour return SupervisorStrategy.escalate(); } }); return supervisorStrategy; } private class AtomModelWrapperAndDataset { private AtomModelWrapper atomModelWrapper; private Dataset dataset; public AtomModelWrapperAndDataset(AtomModelWrapper atomModelWrapper, Dataset dataset) { super(); this.atomModelWrapper = atomModelWrapper; this.dataset = dataset; } } private class ScoredAtom { private AtomModelWrapper atom; private double score; public ScoredAtom(AtomModelWrapper atom, double score) { super(); this.atom = atom; this.score = score; } } private class ScoredAtomUri { private String uri; private double score; public ScoredAtomUri(String uri, double score) { super(); this.uri = uri; this.score = score; } } }
package won.matcher.sparql.actor; import java.io.IOException; import java.net.URI; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.jena.graph.Node; import org.apache.jena.graph.NodeFactory; import org.apache.jena.graph.Triple; import org.apache.jena.query.Dataset; import org.apache.jena.query.Query; import org.apache.jena.query.QueryExecution; import org.apache.jena.query.QueryExecutionFactory; import org.apache.jena.query.QueryFactory; import org.apache.jena.query.QuerySolution; import org.apache.jena.query.ResultSet; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelExtract; import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StatementBoundary; import org.apache.jena.rdf.model.StatementBoundaryBase; import org.apache.jena.rdf.model.impl.ResourceImpl; import org.apache.jena.sparql.algebra.Algebra; import org.apache.jena.sparql.algebra.Op; import org.apache.jena.sparql.algebra.OpAsQuery; import org.apache.jena.sparql.algebra.op.OpBGP; import org.apache.jena.sparql.algebra.op.OpDistinct; import org.apache.jena.sparql.algebra.op.OpFilter; import org.apache.jena.sparql.algebra.op.OpPath; import org.apache.jena.sparql.algebra.op.OpProject; import org.apache.jena.sparql.algebra.op.OpUnion; import org.apache.jena.sparql.core.BasicPattern; import org.apache.jena.sparql.core.TriplePath; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.engine.binding.BindingFactory; import org.apache.jena.sparql.expr.E_LogicalOr; import org.apache.jena.sparql.expr.E_StrContains; import org.apache.jena.sparql.expr.E_StrLowerCase; import org.apache.jena.sparql.expr.Expr; import org.apache.jena.sparql.expr.ExprList; import org.apache.jena.sparql.expr.ExprVar; import org.apache.jena.sparql.expr.nodevalue.NodeValueBoolean; import org.apache.jena.sparql.expr.nodevalue.NodeValueString; import org.apache.jena.sparql.function.library.min; import org.apache.jena.sparql.path.P_Alt; import org.apache.jena.sparql.path.P_Link; import org.apache.jena.sparql.path.P_NegPropSet; import org.apache.jena.sparql.path.P_Seq; import org.apache.jena.sparql.path.P_ZeroOrOne; import org.apache.jena.sparql.path.Path; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.github.jsonldjava.core.JsonLdError; import akka.actor.ActorRef; import akka.actor.OneForOneStrategy; import akka.actor.SupervisorStrategy; import akka.actor.UntypedActor; import akka.cluster.pubsub.DistributedPubSub; import akka.cluster.pubsub.DistributedPubSubMediator; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Function; import scala.concurrent.duration.Duration; import won.matcher.service.common.event.BulkHintEvent; import won.matcher.service.common.event.BulkNeedEvent; import won.matcher.service.common.event.HintEvent; import won.matcher.service.common.event.NeedEvent; import won.matcher.sparql.config.SparqlMatcherConfig; import won.protocol.util.NeedModelWrapper; import won.protocol.util.RdfUtils; import won.protocol.util.linkeddata.LinkedDataSource; import won.protocol.vocabulary.WON; /** * Siren/Solr based abstract matcher with all implementations for querying as * well as indexing needs. */ @Component @Scope("prototype") public class SparqlMatcherActor extends UntypedActor { private LoggingAdapter log = Logging.getLogger(getContext().system(), this); private ActorRef pubSubMediator; @Autowired private SparqlMatcherConfig config; @Autowired private LinkedDataSource linkedDataSource; @Override public void preStart() throws IOException { // subscribe to need events pubSubMediator = DistributedPubSub.get(getContext().system()).mediator(); } @Override public void onReceive(final Object o) throws Exception { String eventTypeForLogging = "unknown"; Optional<String> uriForLogging = Optional.empty(); try { if (o instanceof NeedEvent) { eventTypeForLogging = "NeedEvent"; NeedEvent needEvent = (NeedEvent) o; uriForLogging = Optional.ofNullable(needEvent.getUri()); if (needEvent.getEventType().equals(NeedEvent.TYPE.ACTIVE)) { processActiveNeedEvent(needEvent); } else if (needEvent.getEventType().equals(NeedEvent.TYPE.INACTIVE)) { processInactiveNeedEvent(needEvent); } else { unhandled(o); } } else if (o instanceof BulkNeedEvent) { eventTypeForLogging = "BulkNeedEvent"; log.info("received bulk need event, processing {} need events ...", ((BulkNeedEvent) o).getNeedEvents().size()); for (NeedEvent event : ((BulkNeedEvent) o).getNeedEvents()) { processActiveNeedEvent(event); } } else { eventTypeForLogging = "unhandled"; unhandled(o); } } catch (Exception e) { log.info(String.format("Caught exception when processing %s event %s. More info on loglevel 'debug'", eventTypeForLogging, uriForLogging.orElse("[no uri available]"))); log.debug("caught exception", e); } } protected void processInactiveNeedEvent(NeedEvent needEvent) throws IOException, JsonLdError { log.info("Received inactive need."); } private static String hashFunction(Object input) { return Integer.toHexString(input.hashCode()); } private static final Var resultName = Var.alloc("result"); private static final Var scoreName = Var.alloc("score"); private static BasicPattern createDetailsQuery(Model model) { BasicPattern pattern = new BasicPattern(); StreamSupport.stream(Spliterators.spliteratorUnknownSize(model.listStatements(), Spliterator.CONCURRENT), true) .map((statement) -> { Triple triple = statement.asTriple(); RDFNode object = statement.getObject(); Node newSubject = Var.alloc(hashFunction(triple.getSubject())); Node newObject = triple.getObject(); if (object.isAnon()) { newObject = Var.alloc(hashFunction(newObject)); } return new Triple(newSubject, triple.getPredicate(), newObject); }).filter(p -> p != null).forEach(pattern::add); return pattern; } private static Op createNeedQuery(Model model, Statement parentStatement, Node newPredicate) { StatementBoundary boundary = new StatementBoundaryBase() { public boolean stopAt(Statement s) { return parentStatement.getSubject().equals(s.getSubject()); } }; Model subModel = new ModelExtract(boundary).extract(parentStatement.getObject().asResource(), model); BasicPattern pattern = createDetailsQuery(subModel); if(pattern.isEmpty()) { return null; } pattern.add(new Triple(resultName, newPredicate, Var.alloc(hashFunction(parentStatement.getObject())))); return new OpBGP(pattern); } private static Op createSearchQuery(String searchString) { Node blank = NodeFactory.createURI(""); P_Link blankPath = new P_Link(blank); P_NegPropSet negation = new P_NegPropSet(); negation.add(blankPath); P_Alt any = new P_Alt(blankPath, negation); //TODO: REMOVE "http://purl.org/webofneeds/model P_Link isPath = new P_Link(NodeFactory.createURI("http://purl.org/webofneeds/model P_Link seeksPath = new P_Link(NodeFactory.createURI("http://purl.org/webofneeds/model#seeks")); Path searchPath = Collections.<Path>nCopies(5, new P_ZeroOrOne(any)).stream().reduce(new P_Alt(isPath, seeksPath), P_Seq::new); Var textSearchTarget = Var.alloc("textSearchTarget"); Op pathOp = new OpPath(new TriplePath( resultName, searchPath, textSearchTarget)); Expr filterExpression = Arrays.stream(searchString.toLowerCase().split(" ")) .<Expr>map(searchPart -> new E_StrContains( new E_StrLowerCase(new ExprVar(textSearchTarget)), new NodeValueString(searchPart) ) ) .reduce((left, right) -> new E_LogicalOr(left, right)) .orElse(new NodeValueBoolean(true)); return OpFilter.filterBy( new ExprList( filterExpression ), pathOp ); } protected void processActiveNeedEvent(NeedEvent needEvent) throws IOException { NeedModelWrapper need = new NeedModelWrapper(needEvent.deserializeNeedDataset()); log.debug("starting sparql-based matching for need {}", need.getNeedUri()); List<ScoredNeed> matches = queryNeed(need); log.debug("found {} match candidates", matches.size()); Dataset needDataset = need.copyDataset(); final boolean noHintForCounterpart = need.hasFlag(WON.NO_HINT_FOR_COUNTERPART); Map<NeedModelWrapper, List<ScoredNeed>> filteredNeeds = Stream.concat( Stream.of(new AbstractMap.SimpleEntry<>(need, matches)), //add the reverse match, if no flags forbid it matches.stream().map(matchedNeed -> { boolean noHintForMe = matchedNeed.need.hasFlag(WON.NO_HINT_FOR_ME); if (!noHintForCounterpart && !noHintForMe && !need.getNeedUri().equals(matchedNeed.need.getNeedUri())) { // query for the matched need - but only in the dataset containing the original need. If we have a match, it means // that the matched need should also get a hint, otherwise it should not. if (log.isDebugEnabled()) { log.debug("checking if match {} of {} should get a hint by inverse matching it in need's dataset: \n{}", new Object[] {matchedNeed.need.getNeedUri(), need.getNeedUri(), RdfUtils.toString(needDataset) } ); } List<ScoredNeed> matchForMatchedNeed = queryNeed(matchedNeed.need, Optional.of(new NeedModelWrapperAndDataset(need, needDataset))); if (log.isDebugEnabled()) { log.debug("match {} of {} is also getting a hint: {}", new Object[] {matchedNeed.need.getNeedUri(), need.getNeedUri(), matchForMatchedNeed.size() > 0}); } return new AbstractMap.SimpleEntry<>(matchedNeed.need, matchForMatchedNeed); } else { // the flags in the original or in the matched need forbid a hint. don't add one. return new AbstractMap.SimpleEntry<>(matchedNeed.need, (List<ScoredNeed>) Collections.EMPTY_LIST); } })) .map(entry -> { List<ScoredNeed> filteredMatches = entry.getValue().stream().filter(f -> postFilter(entry.getKey(), f.need)).collect(Collectors.toList()); return new AbstractMap.SimpleEntry<>(entry.getKey(), filteredMatches); }).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); BulkHintEvent bulkHintEvent = new BulkHintEvent(); Optional<Double> maxScore = filteredNeeds.values().stream().flatMap(value -> value.stream()).map(n -> n.score).max((x, y) -> (int) Math.signum(x - y)); if (!maxScore.isPresent()) { //this should not happen return; } Optional<Double> minScore = filteredNeeds.values().stream().flatMap(value -> value.stream()).map(n -> n.score).min((x, y) -> (int) Math.signum(x - y)); if (!maxScore.isPresent()) { //this should not happen return; } double range = (maxScore.get() - minScore.get()); filteredNeeds.forEach((hintTarget, hints) -> { hints .stream() .sorted((hint1, hint2) -> (int) Math.signum(hint2.score - hint1.score)) //sort descending .limit(config.getLimitResults()) .forEach(hint -> { double score = range == 0 ? hint.score - minScore.get() : (hint.score - minScore.get()) / range; bulkHintEvent.addHintEvent( new HintEvent( hintTarget.getWonNodeUri(), hintTarget.getNeedUri(), hint.need.getWonNodeUri(), hint.need.getNeedUri(), config.getMatcherUri(), score)); }); }); pubSubMediator.tell(new DistributedPubSubMediator.Publish(bulkHintEvent.getClass().getName(), bulkHintEvent), getSelf()); log.debug("finished sparql-based matching for need {} (found {} matches)", need.getNeedUri(), bulkHintEvent.getHintEvents().size()); } private Optional<Op> clientSuppliedQuery(String queryString) { Query query = QueryFactory.create(queryString); if(query.getQueryType() != Query.QueryTypeSelect) { return Optional.empty(); } if(!query.getProjectVars().contains(resultName)) { return Optional.empty(); } Op op = Algebra.compile(query); return Optional.of(new OpDistinct(op)); } private Optional<Op> defaultQuery(NeedModelWrapper need) { Model model = need.getNeedModel(); String needURI = need.getNeedUri(); ArrayList<Op> queries = new ArrayList<>(3); Statement seeks = model.getProperty(model.createResource(needURI), model.createProperty("http://purl.org/webofneeds/model#seeks")); if (seeks != null) { //TODO: REMOVE "http://purl.org/webofneeds/model Op seeksQuery = createNeedQuery(model, seeks, NodeFactory.createURI("http://purl.org/webofneeds/model if(seeksQuery != null) queries.add(seeksQuery); } //TODO: REMOVE "http://purl.org/webofneeds/model Statement is = model.getProperty(model.createResource(needURI), model.createProperty("http://purl.org/webofneeds/model if (is != null) { Op isQuery = createNeedQuery(model, is, NodeFactory.createURI("http://purl.org/webofneeds/model#seeks")); if(isQuery != null) queries.add(isQuery); } Statement search = model.getProperty(model.createResource(needURI), model.createProperty("http://purl.org/webofneeds/model#hasSearchString")); if (search != null) { String searchString = search.getString(); queries.add(createSearchQuery(searchString)); } return queries.stream() .reduce((left, right) -> new OpUnion(left, right)) .map((union) -> new OpDistinct( new OpProject( union, Arrays.asList(new Var[]{resultName}) ) ) ); } private List<ScoredNeed> queryNeed(NeedModelWrapper need) { return queryNeed(need, Optional.empty()); } /** * Query for matches to the need, optionally the needToCheck is used to search in. If needToCheck is passed, * it is used as the result data iff the needToCheck is a match for need. This saves us a linked data lookup for * data we already have. * * @param need * @param needToCheck * @return */ private List<ScoredNeed> queryNeed(NeedModelWrapper need, Optional<NeedModelWrapperAndDataset> needToCheck) { Optional<Op> query; Optional<String> userQuery = need.getQuery(); if (userQuery.isPresent()) { query = clientSuppliedQuery(userQuery.get()); } else { query = defaultQuery(need); } List<ScoredNeed> needs = query.map(q -> { if (log.isDebugEnabled()) { log.debug("transforming query, adding 'no hint for counterpart' restriction: {}", q); } Op noHintForCounterpartQuery = SparqlMatcherUtils.noHintForCounterpartQuery(q, resultName, config.getLimitResults()*5); if (log.isDebugEnabled()) { log.debug("transformed query: {}", noHintForCounterpartQuery); log.debug("transforming query, adding 'wihout no hint for counterpart' restriction: {}", q); } Op hintForCounterpartQuery = SparqlMatcherUtils.hintForCounterpartQuery(q, resultName, config.getLimitResults() * 5); if (log.isDebugEnabled()) { log.debug("transformed query: {}", hintForCounterpartQuery); } return Stream.concat( executeQuery(noHintForCounterpartQuery, needToCheck), executeQuery(hintForCounterpartQuery, needToCheck) ).collect(Collectors.toList()); }) .orElse(Collections.EMPTY_LIST); return needs; } /** * Executes the query, optionally only searching in the needToCheck. * @param q * @param needToCheck * @return */ private Stream<ScoredNeed> executeQuery(Op q, Optional<NeedModelWrapperAndDataset> needToCheck) { Query compiledQuery = OpAsQuery.asQuery(q); // if we were given a needToCheck, restrict the query result to that uri so that // we get exactly one result if that uri is found for the need if (needToCheck.isPresent()) { Binding binding = BindingFactory.binding(resultName, new ResourceImpl(needToCheck.get().needModelWrapper.getNeedUri()).asNode()); compiledQuery.setValuesDataBlock(Collections.singletonList(resultName), Collections.singletonList(binding)); } if (log.isDebugEnabled()) { log.debug("executeQuery query: {}, needToCheck: {}", new Object[] {compiledQuery, needToCheck}); } List<ScoredNeedUri> foundUris = new LinkedList<>(); // process query results iteratively try (QueryExecution execution = QueryExecutionFactory .sparqlService(config.getSparqlEndpoint(), compiledQuery) ) { ResultSet result = execution.execSelect(); while(result.hasNext()) { QuerySolution querySolution = result.next(); String foundNeedURI = querySolution.get(resultName.getName()).toString(); double score = 1.0; if (querySolution.contains(scoreName.getName())) { RDFNode scoreNode = querySolution.get(scoreName.getName()); if (scoreNode != null && scoreNode.isLiteral()) { try { score = scoreNode.asLiteral().getDouble(); } catch (NumberFormatException e) { //if the score is not interpretable as double, ignore it } } } foundUris.add(new ScoredNeedUri(foundNeedURI, score)); } } catch (Exception e) { log.info("caught exception during sparql-based matching (more info on loglevel 'debug'): {} ", e.getMessage()); if (log.isDebugEnabled()) { e.printStackTrace(); } return Stream.empty(); } //load data in parallel return foundUris.parallelStream().map(foundNeedUri -> { try { //if we have a needToCheck, return it if the URI we found actually is its URI, otherwise null if ((needToCheck.isPresent())) { NeedModelWrapper result = needToCheck.get().needModelWrapper.getNeedUri().equals(foundNeedUri.uri) ? needToCheck.get().needModelWrapper : null; if (result == null) { return null; } return new ScoredNeed(result, foundNeedUri.score); } else { // no needToCheck, which happens when we first look for matches in the graph store: // download the linked data and return a new NeedModelWrapper return new ScoredNeed(new NeedModelWrapper(linkedDataSource.getDataForResource(URI.create(foundNeedUri.uri))), foundNeedUri.score); } } catch (Exception e) { log.info("caught exception trying to load need URI {} : {} (more on loglevel 'debug')" , foundNeedUri, e.getMessage() ); if (log.isDebugEnabled()) { e.printStackTrace(); } return null; } }).filter(foundNeed -> foundNeed != null); } private static Set<String> getMatchingContexts(NeedModelWrapper need) { Model model = need.getNeedModel(); Resource needURI = model.createResource(need.getNeedUri()); Property matchingContextProperty = model.createProperty("http://purl.org/webofneeds/model#hasMatchingContext"); Stream<RDFNode> stream = StreamSupport.stream( Spliterators.spliteratorUnknownSize(model.listObjectsOfProperty(needURI, matchingContextProperty), Spliterator.CONCURRENT), false); return stream.map(node -> node.asLiteral().getString()).collect(Collectors.toSet()); } private boolean postFilter(NeedModelWrapper need, NeedModelWrapper foundNeed) { try { if (need.getNeedUri().equals(foundNeed.getNeedUri())) { return false; } if (need.hasFlag(WON.NO_HINT_FOR_ME)) { return false; } if (foundNeed.hasFlag(WON.NO_HINT_FOR_COUNTERPART)) { return false; } Set<String> needContexts = getMatchingContexts(need); if (!needContexts.isEmpty()) { Set<String> foundNeedContexts = getMatchingContexts(foundNeed); foundNeedContexts.retainAll(needContexts); if (foundNeedContexts.isEmpty()) { return false; } } Calendar now = Calendar.getInstance(); if (now.after(foundNeed.getDoNotMatchAfter())) return false; if (now.before(foundNeed.getDoNotMatchBefore())) return false; return true; } catch (Exception e) { log.info("caught Exception during post-filtering, ignoring match", e); } return false; } @Override public SupervisorStrategy supervisorStrategy() { SupervisorStrategy supervisorStrategy = new OneForOneStrategy(0, Duration.Zero(), new Function<Throwable, SupervisorStrategy.Directive>() { @Override public SupervisorStrategy.Directive apply(Throwable t) throws Exception { log.warning("Actor encountered error: {}", t); // default behaviour return SupervisorStrategy.escalate(); } }); return supervisorStrategy; } private class NeedModelWrapperAndDataset { private NeedModelWrapper needModelWrapper; private Dataset dataset; public NeedModelWrapperAndDataset(NeedModelWrapper needModelWrapper, Dataset dataset) { super(); this.needModelWrapper = needModelWrapper; this.dataset = dataset; } } private class ScoredNeed { private NeedModelWrapper need; private double score; public ScoredNeed(NeedModelWrapper need, double score) { super(); this.need = need; this.score = score; } } private class ScoredNeedUri { private String uri; private double score; public ScoredNeedUri(String uri, double score) { super(); this.uri = uri; this.score = score; } } }
package esg.common.security; import esg.common.generated.security.*; import esg.common.util.ESGFProperties; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.FileOutputStream; import java.io.BufferedReader; import java.io.FileReader; import java.io.StringReader; import java.io.StringWriter; import java.util.Date; import java.util.Properties; import java.util.Set; import java.util.HashSet; import javax.xml.transform.stream.StreamSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.impl.*; /** Description: Object used to load policy xml descriptor files, manipulate policy information and save the policy information back to descriptor file. **/ public class PolicyGleaner { private static final Log log = LogFactory.getLog(PolicyGleaner.class); private static final String policyFile = "esgf_policies.xml"; private String policyPath = null; private Properties props = null; private String stringOutput = "<oops>"; private Set<PolicyWrapper> policySet = null; private Policies myPolicy = null; private boolean dirty = false; public PolicyGleaner() { this(null); } public PolicyGleaner(Properties props) { this.props = props; this.init(); } public void init() { try { if(props == null) this.props = new ESGFProperties(); } catch(Exception e) { log.error(e); } // /usr/local/tomcat/webapps/esgf-security/WEB-INF/classes/esg/security/config/ policyPath = props.getProperty("security.app.home",".")+File.separator+"WEB-INF"+File.separator+"classes"+File.separator+"esg"+File.separator+"security"+File.separator+"config"+File.separator; policySet = new HashSet<PolicyWrapper>(); myPolicy = new Policies(); } public Policies getMyPolicy() { return myPolicy; } public synchronized PolicyGleaner loadMyPolicy() { return this.loadMyPolicy(policyPath+policyFile); } public synchronized PolicyGleaner loadMyPolicy(String filename) { log.info("Loading my policy info from "+filename); try{ JAXBContext jc = JAXBContext.newInstance(Policies.class); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<Policies> root = u.unmarshal(new StreamSource(new File(filename)),Policies.class); myPolicy = root.getValue(); int count = 0; for(Policy policy : myPolicy.getPolicy()) { policySet.add(new PolicyWrapper(policy)); count++; } //dedup log.trace("Unmarshalled ["+myPolicy.getPolicy().size()+"] policies - Inspected ["+count+"] polices - resulted in ["+policySet.size()+"] policies"); dirty=true; }catch(Exception e) { throw new ESGFPolicyException("Unable to properly load local policy from ["+filename+"]", e); } return this; } public synchronized boolean savePolicy() { return savePolicyAs(myPolicy,policyPath+policyFile); } public synchronized boolean savePolicy(Policies policy) { return savePolicyAs(policy, policyPath+policyFile); } public synchronized boolean savePolicyAs(String location) { return savePolicyAs(myPolicy, location); } public synchronized boolean savePolicyAs(Policies policy, String policyFileLocation) { boolean success = false; if (policy == null) { log.error("Sorry internal policy representation is null ? ["+policy+"] perhaps you need to load policy file first?"); return success; } log.info("Saving policy information to "+policyFileLocation); try{ JAXBContext jc = JAXBContext.newInstance(Policies.class); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(policy, new FileOutputStream(policyFileLocation)); success = true; dirty=false; }catch(Exception e) { log.error(e); } return success; } //Policy manipulation methods public PolicyGleaner addPolicy(String resource, String groupName, String roleName, String action) { dirty=true; Policy p = new Policy(); p.setResource(resource); p.setAttributeType(groupName); p.setAttributeValue(roleName); p.setAction(action); policySet.add(new PolicyWrapper(p)); return this; } public PolicyGleaner removePolicy(String resource, String groupName, String roleName, String action) { dirty=true; Policy p = new Policy(); p.setResource(resource); p.setAttributeType(groupName); p.setAttributeValue(roleName); p.setAction(action); policySet.remove(new PolicyWrapper(p)); return this; } public PolicyGleaner removeAllForGroup(String groupName) { dirty=true; log.trace("Removing all policies with group = "+groupName); Set<PolicyWrapper> delSet = new HashSet<PolicyWrapper>(); for(PolicyWrapper policyWrapper : policySet) { if(policyWrapper.getPolicy().getAttributeType().equals(groupName)) { delSet.add(policyWrapper); log.trace("Removing policy: "+policyWrapper); } } if(policySet.removeAll(delSet)) { log.trace("ok"); } else { log.trace("nope"); } return this; } public PolicyGleaner remoteAllForRole(String roleName) { dirty=true; log.trace("Removing all policies with role = "+roleName); Set<PolicyWrapper> delSet = new HashSet<PolicyWrapper>(); for(PolicyWrapper policyWrapper : policySet) { if(policyWrapper.getPolicy().getAttributeValue().equals(roleName)) { delSet.add(policyWrapper); log.trace("Removing policy: "+policyWrapper); } } if(policySet.removeAll(delSet)) { log.trace("ok"); } else { log.trace("nope"); } return this; } public PolicyGleaner removeAllForAction(String action) { dirty=true; log.trace("Removing all policies with action = "+action); Set<PolicyWrapper> delSet = new HashSet<PolicyWrapper>(); for(PolicyWrapper policyWrapper : policySet) { if(policyWrapper.getPolicy().getAction().equals(action)) { delSet.add(policyWrapper); log.trace("Removing policy: "+policyWrapper); } } if(policySet.removeAll(delSet)) { log.trace("ok"); } else { log.trace("nope"); } return this; } public PolicyGleaner commit() { dirty=true; myPolicy.getPolicy().clear(); for(PolicyWrapper policyWrapper : policySet) { log.trace("preparing to commit: \n"+policyWrapper); myPolicy.getPolicy().add(policyWrapper.getPolicy()); } log.trace("commit done"); return this; } public int size() { return policySet.size(); } public PolicyGleaner clear() { policySet.clear(); myPolicy.getPolicy().clear(); return this; } public String toString() { return this.toString(false); } public String toString(boolean force) { if(dirty || force) { StringBuffer sb = new StringBuffer("Policies: "); for(PolicyWrapper policyWrapper : policySet) { sb.append(policyWrapper.toString()); } stringOutput = sb.toString(); } dirty=false; return stringOutput; } class PolicyWrapper { Policy policy = null; final String outputString; PolicyWrapper(Policy policy) { this.policy = policy; StringBuffer sb = new StringBuffer("policy: "); sb.append("["+policy.getResource()+"] "); sb.append("g["+policy.getAttributeType()+"] "); sb.append("r["+policy.getAttributeValue()+"] "); sb.append("a["+policy.getAction()+"]"); outputString = sb.toString(); } Policy getPolicy() { return policy; } public boolean equals(Object o) { if(!(o instanceof PolicyWrapper)) return false; return outputString.equals(o.toString()); } public int hashCode() { return outputString.hashCode(); } public String toString() { return outputString; } } //Main: For quick testing... public static void main(String[] args) { PolicyGleaner pGleaner = null; pGleaner = new PolicyGleaner(); pGleaner.addPolicy(".*test.*", "superGroup", "boss", "Write"); pGleaner.addPolicy(".*cmip5.*", "otherGroup", "user", "Read"); pGleaner.commit().savePolicyAs("test_policy.out"); //if(args.length > 0) { // if(args[0].equals("load")) { // System.out.println(args[0]+"ing..."); // pGleaner = new PolicyGleaner(); // if(args.length == 2) { // if(args[1].equals("default")) { // System.out.println(pGleaner.loadMyPolicy()); // }else { // System.out.println(pGleaner.loadMyPolicy(args[1])); // //Do some manipulation here... // //And show it... // if(args.length == 3) { // pGleaner.savePolicyAs(args[2]); // }else{ // pGleaner.savePolicy(); // }else { } }
package won.owner.web.service; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import won.owner.pojo.SocketToConnect; import won.owner.service.impl.OwnerApplicationService; import won.owner.web.service.serversideaction.EventTriggeredAction; import won.owner.web.service.serversideaction.EventTriggeredActionContainer; import won.protocol.exception.WonMessageProcessingException; import won.protocol.message.WonMessage; import won.protocol.message.WonMessageDirection; import won.protocol.message.WonMessageType; import won.protocol.message.builder.WonMessageBuilder; import won.protocol.message.processor.WonMessageProcessor; import won.protocol.service.WonNodeInformationService; import won.protocol.util.AuthenticationThreadLocal; import won.protocol.util.linkeddata.LinkedDataSource; @Component public class ServerSideActionService implements WonMessageProcessor { EventTriggeredActionContainer<WonMessage> actionContainer = new EventTriggeredActionContainer<WonMessage>(); @Autowired WonNodeInformationService wonNodeInformationService; @Autowired private LinkedDataSource linkedDataSourceOnBehalfOfAtom; @Autowired private LinkedDataSource linkedDataSource; // ownerApplicationService for sending messages from the owner to the node private OwnerApplicationService ownerApplicationService; /** * Connect the specified sockets, optionally waiting until the respective atoms * have been created. Use the specified authentication for sending messages on * behalf of the user the authentication was obtained from. */ public void connect(List<SocketToConnect> sockets, Authentication authentication) { // a little bit of shared state for the actions we are creating: if (sockets == null || sockets.size() != 2) { throw new IllegalArgumentException("2 sockets expected"); } // we want to have 2 atoms before we can start connecting: final AtomicInteger atomCounter = new AtomicInteger(0); final AtomicBoolean connectSent = new AtomicBoolean(false); final URI fromSocket = URI.create(sockets.get(0).getSocket()); final URI toSocket = URI.create(sockets.get(1).getSocket()); // count the pending sockets int atoms = (int) sockets.stream().filter(f -> !f.isPending()).count(); atomCounter.set(atoms); final Function<Optional<WonMessage>, Collection<EventTriggeredAction<WonMessage>>> action = new Function<Optional<WonMessage>, Collection<EventTriggeredAction<WonMessage>>>() { @Override public Collection<EventTriggeredAction<WonMessage>> apply(Optional<WonMessage> msg) { // process success responses for create if (msg.isPresent() && atomCounter.get() < 2 && isResponseToCreateOfSockets(msg.get(), sockets)) { // we're processing a response event for the creation of one of our atoms. atomCounter.incrementAndGet(); } // maybe we're processing a response to create, maybe we're processing an empty // event: if (atomCounter.get() >= 2) { // we have all the atoms we need for the connect. if (connectSent.compareAndSet(false, true)) { // we haven't sent the connect yet, do it now and register a new action // waiting for the connect on the receiving end. sendConnect(fromSocket, toSocket, authentication); return Arrays.asList(new EventTriggeredAction<WonMessage>( String.format("Connect %s and %s: Expecting incoming connect from %s for %s", fromSocket, toSocket, fromSocket, toSocket), m -> isConnectFromSocketForSocket(m.get(), fromSocket, toSocket), this)); } else { // we have sent the connect, check if we're processing the connect on the // receiving end. If so, send an open. if (isConnectFromSocketForSocket(msg.get(), fromSocket, toSocket)) { reactWithConnect(msg.get(), authentication); // that's it - don't register any more actions } } } else { // we are still waiting for atom creation to finish. return this action waiting // for another create response return Arrays.asList(new EventTriggeredAction<>( String.format("Connect %s and %s: Expecting response for create", fromSocket, toSocket), m -> m.isPresent() && isResponseToCreateOfSockets(m.get(), sockets), this)); } // none of the above - this is the last execution of this action. return Collections.emptyList(); } }; // add the action in such a way that it is triggered on add (with an empty // Optional<WonMessage>) this.actionContainer.addAction(new EventTriggeredAction<WonMessage>( String.format("Connect %s and %s", fromSocket, toSocket), action)); } private boolean isResponseToCreateOfSockets(WonMessage msg, List<SocketToConnect> sockets) { return sockets.stream().anyMatch(socket -> socket.isPending() && isResponseToCreateOfSocket(msg, socket)); } private boolean isResponseToCreateOfSocket(WonMessage msg, SocketToConnect socket) { if (!msg.isMessageWithResponse()) { return false; } WonMessage response = msg.getResponse().get(); return response.getRespondingToMessageType() == WonMessageType.CREATE_ATOM && response.getEnvelopeType() == WonMessageDirection.FROM_SYSTEM && socket.getSocket().startsWith(msg.getAtomURI() + " } private boolean isConnectFromSocketForSocket(WonMessage msg, URI sender, URI receiver) { if (!msg.isMessageWithBothResponses()) { // we expect a message with responses from both nodes return false; } return msg.getMessageType() == WonMessageType.CONNECT && msg.getSenderSocketURI() != null && sender.equals(msg.getSenderSocketURI()) && msg.getRecipientSocketURI() != null && receiver.equals(msg.getRecipientSocketURI()); } private void sendConnect(URI fromSocket, URI toSocket, Authentication authentication) { WonMessage msgToSend = WonMessageBuilder .connect() .sockets().sender(fromSocket).recipient(toSocket) .content().text("Connect message automatically sent by a server-side action") .build(); try { AuthenticationThreadLocal.setAuthentication(authentication); ownerApplicationService.prepareAndSendMessage(msgToSend); } finally { // be sure to remove the principal from the threadlocal AuthenticationThreadLocal.remove(); } } private void reactWithConnect(WonMessage connectMessageToReactTo, Authentication authentication) { WonMessage msgToSend = WonMessageBuilder .connect() .sockets().reactingTo(connectMessageToReactTo) .content().text("Open message automatically sent by a server-side action") .build(); try { AuthenticationThreadLocal.setAuthentication(authentication); ownerApplicationService.prepareAndSendMessage(msgToSend); } finally { // be sure to remove the principal from the threadlocal AuthenticationThreadLocal.remove(); } } @Override public WonMessage process(WonMessage message) throws WonMessageProcessingException { actionContainer.executeFor(Optional.of(message)); return message; } public void setOwnerApplicationService(OwnerApplicationService ownerApplicationService) { this.ownerApplicationService = ownerApplicationService; } public void setLinkedDataSourceOnBehalfOfAtom(LinkedDataSource linkedDataSourceOnBehalfOfAtom) { this.linkedDataSourceOnBehalfOfAtom = linkedDataSourceOnBehalfOfAtom; } }
package org.apache.commons.beanutils; import java.beans.BeanInfo; import java.beans.IndexedPropertyDescriptor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class BeanUtils { /** * The debugging detail level for this component. */ private static int debug = 0; public static int getDebug() { return (debug); } public static void setDebug(int newDebug) { debug = newDebug; } public static Object cloneBean(Object bean) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { Class clazz = bean.getClass(); Object newBean = clazz.newInstance(); PropertyUtils.copyProperties(newBean, bean); return (newBean); } public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) // return (Collections.EMPTY_MAP); return (new java.util.HashMap()); PropertyDescriptor descriptors[] = PropertyUtils.getPropertyDescriptors(bean); Map description = new HashMap(descriptors.length); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (descriptors[i].getReadMethod() != null) description.put(name, getProperty(bean, name)); } return (description); } public static String[] getArrayProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getProperty(bean, name); if (value == null) { return (null); } else if (value instanceof Collection) { ArrayList values = new ArrayList(); Iterator items = ((Collection) value).iterator(); while (items.hasNext()) { Object item = items.next(); if (item == null) values.add((String) null); else values.add(item.toString()); } return ((String[]) values.toArray(new String[values.size()])); } else if (value.getClass().isArray()) { ArrayList values = new ArrayList(); try { int n = Array.getLength(value); for (int i = 0; i < n; i++) { values.add(Array.get(value, i).toString()); } } catch (ArrayIndexOutOfBoundsException e) { ; } return ((String[]) values.toArray(new String[values.size()])); } else { String results[] = new String[1]; results[0] = value.toString(); return (results); } } public static String getIndexedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getIndexedProperty(bean, name); return (ConvertUtils.convert(value)); } public static String getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getIndexedProperty(bean, name, index); return (ConvertUtils.convert(value)); } public static String getMappedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getMappedProperty(bean, name); return (ConvertUtils.convert(value)); } public static String getMappedProperty(Object bean, String name, String key) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getMappedProperty(bean, name, key); return (ConvertUtils.convert(value)); } public static String getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getNestedProperty(bean, name); return (ConvertUtils.convert(value)); } public static String getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (getNestedProperty(bean, name)); } public static String getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Object value = PropertyUtils.getSimpleProperty(bean, name); return (ConvertUtils.convert(value)); } public static void populate(Object bean, Map properties) throws IllegalAccessException, InvocationTargetException { if ((bean == null) || (properties == null)) return; /* if (debug >= 1) System.out.println("BeanUtils.populate(" + bean + ", " + properties + ")"); */ // Loop through the property name/value pairs to be set Iterator names = properties.keySet().iterator(); while (names.hasNext()) { // Identify the property name and value(s) to be assigned String name = (String) names.next(); if (name == null) continue; Object value = properties.get(name); // String or String[] /* if (debug >= 1) System.out.println(" name='" + name + "', value.class='" + (value == null ? "NONE" : value.getClass().getName()) + "'"); */ // Get the property descriptor of the requested property (if any) PropertyDescriptor descriptor = null; DynaProperty dynaProperty = null; try { if (bean instanceof DynaBean) { dynaProperty = ((DynaBean) bean).getDynaClass().getDynaProperty(name); } else { descriptor = PropertyUtils.getPropertyDescriptor(bean, name); } } catch (Throwable t) { /* if (debug >= 1) System.out.println(" getPropertyDescriptor: " + t); */ descriptor = null; dynaProperty = null; } if ((descriptor == null) && (dynaProperty == null)) { /* if (debug >= 1) System.out.println(" No such property, skipping"); */ continue; } /* if (debug >= 1) System.out.println(" Property descriptor is '" + descriptor + "'"); */ // Process differently for JavaBeans and DynaBeans if (descriptor != null) { // Identify the relevant setter method (if there is one) Method setter = null; if (descriptor instanceof IndexedPropertyDescriptor) setter = ((IndexedPropertyDescriptor) descriptor). getIndexedWriteMethod(); else if (descriptor instanceof MappedPropertyDescriptor) setter =((MappedPropertyDescriptor) descriptor).getMappedWriteMethod(); if (setter == null) setter = descriptor.getWriteMethod(); if (setter == null) { /* if (debug >= 1) System.out.println(" No setter method, skipping"); */ continue; } Class parameterTypes[] = setter.getParameterTypes(); /* if (debug >= 1) System.out.println(" Setter method is '" + setter.getName() + "(" + parameterTypes[0].getName() + (parameterTypes.length > 1 ? ", " + parameterTypes[1].getName() : "" ) + ")'"); */ Class parameterType = parameterTypes[0]; if (parameterTypes.length > 1) parameterType = parameterTypes[1]; // Indexed or mapped setter // Convert the parameter value as required for this setter method Object parameters[] = new Object[1]; if (parameterTypes[0].isArray()) { if (value instanceof String) { String values[] = new String[1]; values[0] = (String) value; parameters[0] = ConvertUtils.convert((String[]) values, parameterType); } else if (value instanceof String[]) { parameters[0] = ConvertUtils.convert((String[]) value, parameterType); } else { parameters[0] = value; } } else { if (value instanceof String) { parameters[0] = ConvertUtils.convert((String) value, parameterType); } else if (value instanceof String[]) { parameters[0] = ConvertUtils.convert(((String[]) value)[0], parameterType); } else { parameters[0] = value; } } // Invoke the setter method try { PropertyUtils.setProperty(bean, name, parameters[0]); } catch (NoSuchMethodException e) { /* if (debug >= 1) { System.out.println(" CANNOT HAPPEN: " + e); e.printStackTrace(System.out); } */ } } else { // Handle scalar and indexed properties differently Object newValue = null; Class type = dynaProperty.getType(); if (type.isArray()) { if (value instanceof String) { String values[] = new String[1]; values[0] = (String) value; newValue = ConvertUtils.convert((String[]) values, type); } else if (value instanceof String[]) { newValue = ConvertUtils.convert((String[]) value, type); } else { newValue = value; } } else { if (value instanceof String) { newValue = ConvertUtils.convert((String) value, type); } else if (value instanceof String[]) { newValue = ConvertUtils.convert(((String[]) value)[0], type); } else { newValue = value; } } // Invoke the setter method try { PropertyUtils.setProperty(bean, name, newValue); } catch (NoSuchMethodException e) { /* if (debug >= 1) { System.out.println(" CANNOT HAPPEN: " + e); e.printStackTrace(System.out); } */ } } } } }
package ru.ydn.wicket.wicketorientdb.rest; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Authenticator; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.wicket.protocol.http.WebApplication; import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.request.resource.AbstractResource; import org.apache.wicket.request.resource.SharedResourceReference; import org.apache.wicket.util.encoding.UrlEncoder; import org.apache.wicket.util.io.IOUtils; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.string.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.network.OServerNetworkListener; import com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpAbstract; import ru.ydn.wicket.wicketorientdb.IOrientDbSettings; import ru.ydn.wicket.wicketorientdb.OrientDbWebApplication; import ru.ydn.wicket.wicketorientdb.OrientDbWebSession; /** * Bridge to OrientDB REST API */ public class OrientDBHttpAPIResource extends AbstractResource { public static final String MOUNT_PATH = "/orientdb"; public static final String ORIENT_DB_KEY=OrientDBHttpAPIResource.class.getSimpleName(); private static final Logger LOG = LoggerFactory.getLogger(OrientDBHttpAPIResource.class); @SuppressWarnings("restriction") private static class MultiUserCache implements sun.net.www.protocol.http.AuthCache{ public void put(String pkey, sun.net.www.protocol.http.AuthCacheValue value){ } public sun.net.www.protocol.http.AuthCacheValue get(String pkey, String skey){ return null; } public void remove(String pkey, sun.net.www.protocol.http.AuthCacheValue entry){ } } @Override protected ResourceResponse newResourceResponse(Attributes attributes) { final WebRequest request = (WebRequest) attributes.getRequest(); final HttpServletRequest httpRequest = (HttpServletRequest) request.getContainerRequest(); final PageParameters params = attributes.getParameters(); final ResourceResponse response = new ResourceResponse(); if(response.dataNeedsToBeWritten(attributes)) { String orientDbHttpURL = OrientDbWebApplication.get().getOrientDbSettings().getOrientDBRestApiUrl(); if(orientDbHttpURL!=null) { StringBuilder sb = new StringBuilder(orientDbHttpURL); for(int i=0; i<params.getIndexedCount();i++) { //replace provided database name String segment = i==1?OrientDbWebSession.get().getDatabase().getName():params.get(i).toString(); sb.append(UrlEncoder.PATH_INSTANCE.encode(segment, "UTF8")).append('/'); } if(sb.charAt(sb.length()-1)=='/')sb.setLength(sb.length()-1); String queryString = request.getUrl().getQueryString(); if(!Strings.isEmpty(queryString)) sb.append(queryString); final String url = sb.toString(); final StringWriter sw = new StringWriter(); final PrintWriter out = new PrintWriter(sw); HttpURLConnection con=null; try { URL orientURL = new URL(url); con = (HttpURLConnection)orientURL.openConnection(); con.setDoInput(true); con.setUseCaches(false); String method = httpRequest.getMethod(); con.setRequestMethod(method); con.setUseCaches(false); if("post".equalsIgnoreCase(method) || "put".equalsIgnoreCase(method)) { con.setDoOutput(true); IOUtils.copy(httpRequest.getInputStream(), con.getOutputStream()); } IOUtils.copy(con.getInputStream(), out, "UTF-8"); response.setStatusCode(con.getResponseCode()); response.setContentType(con.getContentType()); } catch (IOException e) { LOG.error("Can't communicate with OrientDB REST", e); if(con!=null) { try { response.setError(con.getResponseCode(), con.getResponseMessage()); InputStream errorStream = con.getErrorStream(); if(errorStream!=null) IOUtils.copy(errorStream, out, "UTF-8"); } catch (IOException e1) { LOG.error("Can't response by error", e1); } } } finally { if(con!=null)con.disconnect(); } response.setWriteCallback(new WriteCallback() { @Override public void writeData(Attributes attributes) throws IOException { attributes.getResponse().write(sw.toString()); } }); } else { response.setError(HttpServletResponse.SC_BAD_GATEWAY, "OrientDB REST URL is not specified"); } } return response; } public static void mountOrientDbRestApi(WebApplication app) { mountOrientDbRestApi(new OrientDBHttpAPIResource(), app); } /** * Mounts OrientDB REST API Bridge to an app * @param resource {@link OrientDBHttpAPIResource} to mount * @param app {@link WebApplication} to mount to */ @SuppressWarnings("restriction") public static void mountOrientDbRestApi(OrientDBHttpAPIResource resource, WebApplication app) { app.getSharedResources().add(ORIENT_DB_KEY, resource); app.mountResource(MOUNT_PATH, new SharedResourceReference(ORIENT_DB_KEY)); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String username; String password; OrientDbWebSession session = OrientDbWebSession.get(); if(session.isSignedIn()) { username = session.getUsername(); password = session.getPassword(); } else { IOrientDbSettings settings = OrientDbWebApplication.get().getOrientDbSettings(); username = settings.getDBUserName(); password = settings.getDBUserPassword(); } return new PasswordAuthentication (username, password.toCharArray()); } }); CookieHandler.setDefault(new PersonalCookieManager()); sun.net.www.protocol.http.AuthCacheValue.setAuthCache(new MultiUserCache()); } }
package org.elasticsearch.xpack.core.scheduler; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.util.concurrent.EsExecutors; import org.elasticsearch.common.util.concurrent.FutureUtils; import java.time.Clock; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class SchedulerEngine { public static class Job { private final String id; private final Schedule schedule; public Job(String id, Schedule schedule) { this.id = id; this.schedule = schedule; } public String getId() { return id; } public Schedule getSchedule() { return schedule; } } public static class Event { private final String jobName; private final long triggeredTime; private final long scheduledTime; public Event(String jobName, long triggeredTime, long scheduledTime) { this.jobName = jobName; this.triggeredTime = triggeredTime; this.scheduledTime = scheduledTime; } public String getJobName() { return jobName; } public long getTriggeredTime() { return triggeredTime; } public long getScheduledTime() { return scheduledTime; } } public interface Listener { void triggered(Event event); } public interface Schedule { /** * Returns the next scheduled time after the given time, according to this schedule. If the given schedule * cannot resolve the next scheduled time, then {@code -1} is returned. It really depends on the type of * schedule to determine when {@code -1} is returned. Some schedules (e.g. IntervalSchedule) will never return * {@code -1} as they can always compute the next scheduled time. {@code Cron} based schedules are good example * of schedules that may return {@code -1}, for example, when the schedule only points to times that are all * before the given time (in which case, there is no next scheduled time for the given time). * * Example: * * cron 0 0 0 * 1 ? 2013 (only points to days in January 2013) * * time 2015-01-01 12:00:00 (this time is in 2015) * */ long nextScheduledTimeAfter(long startTime, long now); } private final Map<String, ActiveSchedule> schedules = ConcurrentCollections.newConcurrentMap(); private final Clock clock; private final ScheduledExecutorService scheduler; private final Logger logger; private final List<Listener> listeners = new CopyOnWriteArrayList<>(); public SchedulerEngine(final Settings settings, final Clock clock) { this(settings, clock, LogManager.getLogger(SchedulerEngine.class)); } SchedulerEngine(final Settings settings, final Clock clock, final Logger logger) { this.clock = Objects.requireNonNull(clock, "clock"); this.scheduler = Executors.newScheduledThreadPool( 1, EsExecutors.daemonThreadFactory(Objects.requireNonNull(settings, "settings"), "trigger_engine_scheduler")); this.logger = Objects.requireNonNull(logger, "logger"); } public void register(Listener listener) { listeners.add(listener); } public void unregister(Listener listener) { listeners.remove(listener); } public void start(Collection<Job> jobs) { jobs.forEach(this::add); } public void stop() { scheduler.shutdownNow(); try { scheduler.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public void add(Job job) { ActiveSchedule schedule = new ActiveSchedule(job.getId(), job.getSchedule(), clock.millis()); schedules.compute(schedule.name, (name, previousSchedule) -> { if (previousSchedule != null) { previousSchedule.cancel(); } return schedule; }); } public boolean remove(String jobId) { ActiveSchedule removedSchedule = schedules.remove(jobId); if (removedSchedule != null) { removedSchedule.cancel(); } return removedSchedule != null; } /** * @return The number of currently active/triggered jobs */ public int jobCount() { return schedules.size(); } protected void notifyListeners(final String name, final long triggeredTime, final long scheduledTime) { final Event event = new Event(name, triggeredTime, scheduledTime); for (final Listener listener : listeners) { try { listener.triggered(event); } catch (final Exception e) { // do not allow exceptions to escape this method; we should continue to notify listeners and schedule the next run logger.warn(new ParameterizedMessage("listener failed while handling triggered event [{}]", name), e); } } } class ActiveSchedule implements Runnable { private final String name; private final Schedule schedule; private final long startTime; private volatile ScheduledFuture<?> future; private volatile long scheduledTime; ActiveSchedule(String name, Schedule schedule, long startTime) { this.name = name; this.schedule = schedule; this.startTime = startTime; this.scheduleNextRun(startTime); } @Override public void run() { final long triggeredTime = clock.millis(); try { notifyListeners(name, triggeredTime, scheduledTime); } catch (final Throwable t) { /* * Allowing the throwable to escape here will lead to be it being caught in FutureTask#run and set as the outcome of this * task; however, we never inspect the the outcomes of these scheduled tasks and so allowing the throwable to escape * unhandled here could lead to us losing fatal errors. Instead, we rely on ExceptionsHelper#dieOnError to appropriately * dispatch any error to the uncaught exception handler. We should never see an exception here as these do not escape from * SchedulerEngine#notifyListeners. */ ExceptionsHelper.dieOnError(t); throw t; } scheduleNextRun(triggeredTime); } private void scheduleNextRun(long currentTime) { this.scheduledTime = schedule.nextScheduledTimeAfter(startTime, currentTime); if (scheduledTime != -1) { long delay = Math.max(0, scheduledTime - currentTime); future = scheduler.schedule(this, delay, TimeUnit.MILLISECONDS); } } public void cancel() { FutureUtils.cancel(future); } } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.Res; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.VerticalFlowLayout; import org.jivesoftware.spark.component.panes.CollapsiblePane; import org.jivesoftware.spark.component.renderer.JPanelRenderer; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.log.Log; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JWindow; import javax.swing.Timer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * Container representing a RosterGroup within the Contact List. */ public class ContactGroup extends CollapsiblePane implements MouseListener { private List<ContactItem> contactItems = new ArrayList<ContactItem>(); private List<ContactGroup> contactGroups = new ArrayList<ContactGroup>(); private List<ContactGroupListener> listeners = new ArrayList<ContactGroupListener>(); private String groupName; private DefaultListModel model = new DefaultListModel(); private JList list; private boolean sharedGroup; private JPanel listPanel; // Used to display no contacts in list. private final ContactItem noContacts = new ContactItem("There are no online contacts in this group.", null); private JWindow window = new JWindow(); private final ListMotionListener motionListener = new ListMotionListener(); private boolean canShowPopup; private MouseEvent mouseEvent; /** * Create a new ContactGroup. * * @param groupName the name of the new ContactGroup. */ public ContactGroup(String groupName) { list = new JList(model); setTitle(getGroupTitle(groupName)); // Use JPanel Renderer list.setCellRenderer(new JPanelRenderer()); this.groupName = groupName; listPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)); listPanel.add(list, listPanel); this.setContentPane(listPanel); if (!isOfflineGroup()) { list.setDragEnabled(true); list.setTransferHandler(new ContactGroupTransferHandler()); } // Allow for mouse events to take place on the title bar getTitlePane().addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseReleased(MouseEvent e) { checkPopup(e); } public void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { e.consume(); fireContactGroupPopupEvent(e); } } }); // Items should have selection listener list.addMouseListener(this); list.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent keyEvent) { } public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyChar() == KeyEvent.VK_ENTER) { ContactItem item = (ContactItem)list.getSelectedValue(); fireContactItemDoubleClicked(item); } } public void keyReleased(KeyEvent keyEvent) { } }); noContacts.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); noContacts.getNicknameLabel().setForeground(Color.GRAY); model.addElement(noContacts); // Add Popup Window addPopupWindow(); } /** * Adds a <code>ContactItem</code> to the ContactGroup. * * @param item the ContactItem. */ public void addContactItem(ContactItem item) { if (model.getSize() == 1 && model.getElementAt(0) == noContacts) { model.remove(0); } if ("Offline Group".equals(groupName)) { item.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); item.getNicknameLabel().setForeground(Color.GRAY); } item.setGroupName(getGroupName()); contactItems.add(item); List<ContactItem> tempItems = getContactItems(); Collections.sort(tempItems, itemComparator); int index = tempItems.indexOf(item); Object[] objs = list.getSelectedValues(); model.insertElementAt(item, index); int[] intList = new int[objs.length]; for (int i = 0; i < objs.length; i++) { ContactItem contact = (ContactItem)objs[i]; intList[i] = model.indexOf(contact); } if (intList.length > 0) { list.setSelectedIndices(intList); } fireContactItemAdded(item); } /** * Call whenever the UI needs to be updated. */ public void fireContactGroupUpdated() { list.validate(); list.repaint(); updateTitle(); } public void addContactGroup(ContactGroup contactGroup) { final JPanel panel = new JPanel(new GridBagLayout()); panel.add(contactGroup, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 15, 0, 0), 0, 0)); panel.setBackground(Color.white); contactGroup.setSubPane(true); // contactGroup.setStyle(CollapsiblePane.TREE_STYLE); listPanel.add(panel); contactGroups.add(contactGroup); } /** * Removes a child ContactGroup. * * @param contactGroup the contact group to remove. */ public void removeContactGroup(ContactGroup contactGroup) { Component[] comps = listPanel.getComponents(); for (int i = 0; i < comps.length; i++) { Component comp = comps[i]; if (comp instanceof JPanel) { JPanel panel = (JPanel)comp; ContactGroup group = (ContactGroup)panel.getComponent(0); if (group == contactGroup) { listPanel.remove(panel); break; } } } contactGroups.remove(contactGroup); } public void setPanelBackground(Color color) { Component[] comps = listPanel.getComponents(); for (int i = 0; i < comps.length; i++) { Component comp = comps[i]; if (comp instanceof JPanel) { JPanel panel = (JPanel)comp; panel.setBackground(color); } } } /** * Returns a ContactGroup based on it's name. * * @param groupName the name of the group. * @return the ContactGroup. */ public ContactGroup getContactGroup(String groupName) { final Iterator groups = new ArrayList(contactGroups).iterator(); while (groups.hasNext()) { ContactGroup group = (ContactGroup)groups.next(); if (group.getGroupName().equals(groupName)) { return group; } } return null; } /** * Removes a <code>ContactItem</code>. * * @param item the ContactItem to remove. */ public void removeContactItem(ContactItem item) { contactItems.remove(item); model.removeElement(item); updateTitle(); fireContactItemRemoved(item); } /** * Returns a <code>ContactItem</code> by the nickname the user has been assigned. * * @param nickname the nickname of the user. * @return the ContactItem. */ public ContactItem getContactItemByNickname(String nickname) { final Iterator iter = new ArrayList(contactItems).iterator(); while (iter.hasNext()) { ContactItem item = (ContactItem)iter.next(); if (item.getNickname().equals(nickname)) { return item; } } return null; } /** * Returns a <code>ContactItem</code> by the users bare bareJID. * * @param bareJID the bareJID of the user. * @return the ContactItem. */ public ContactItem getContactItemByJID(String bareJID) { final Iterator iter = new ArrayList(contactItems).iterator(); while (iter.hasNext()) { ContactItem item = (ContactItem)iter.next(); if (item.getFullJID().equals(bareJID)) { return item; } } return null; } /** * Returns all <code>ContactItem</cod>s in the ContactGroup. * * @return all ContactItems. */ public List<ContactItem> getContactItems() { return new ArrayList<ContactItem>(contactItems); } /** * Returns the name of the ContactGroup. * * @return the name of the ContactGroup. */ public String getGroupName() { return groupName; } public void mouseClicked(MouseEvent e) { Object o = list.getSelectedValue(); if (!(o instanceof ContactItem)) { return; } // Iterator through rest ContactItem item = (ContactItem)o; if (e.getClickCount() == 2) { fireContactItemDoubleClicked(item); } else if (e.getClickCount() == 1) { fireContactItemClicked(item); } } public void mouseEntered(MouseEvent e) { int loc = list.locationToIndex(e.getPoint()); Object o = model.getElementAt(loc); if (!(o instanceof ContactItem)) { return; } ContactItem item = (ContactItem)o; if (item == null) { return; } list.setCursor(GraphicUtils.HAND_CURSOR); } public void mouseExited(MouseEvent e) { window.setVisible(false); Object o = null; try { int loc = list.locationToIndex(e.getPoint()); o = model.getElementAt(loc); if (!(o instanceof ContactItem)) { return; } } catch (Exception e1) { Log.error(e1); return; } ContactItem item = (ContactItem)o; if (item == null) { return; } list.setCursor(GraphicUtils.DEFAULT_CURSOR); } public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseReleased(MouseEvent e) { checkPopup(e); } private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { // Check for multi selection int[] indeces = list.getSelectedIndices(); List selection = new ArrayList(); for (int i = 0; i < indeces.length; i++) { selection.add(model.getElementAt(indeces[i])); } if (selection.size() > 1) { firePopupEvent(e, selection); return; } // Otherwise, handle single selection int index = list.locationToIndex(e.getPoint()); Object o = model.getElementAt(index); if (!(o instanceof ContactItem)) { return; } ContactItem item = (ContactItem)o; list.setSelectedIndex(index); firePopupEvent(e, item); } } /** * Add a <code>ContactGroupListener</code>. * * @param listener the ContactGroupListener. */ public void addContactGroupListener(ContactGroupListener listener) { listeners.add(listener); } /** * Removes a <code>ContactGroupListener</code>. * * @param listener the ContactGroupListener. */ public void removeContactGroupListener(ContactGroupListener listener) { listeners.remove(listener); } private void fireContactItemClicked(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemClicked(item); } } private void fireContactItemDoubleClicked(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemDoubleClicked(item); } } private void firePopupEvent(MouseEvent e, ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).showPopup(e, item); } } private void firePopupEvent(MouseEvent e, Collection items) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).showPopup(e, items); } } private void fireContactGroupPopupEvent(MouseEvent e) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactGroupPopup(e, this); } } private void fireContactItemAdded(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemAdded(item); } } private void fireContactItemRemoved(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemRemoved(item); } } private void updateTitle() { if ("Offline Group".equals(groupName)) { setTitle("Offline Group"); return; } int count = 0; List list = new ArrayList(getContactItems()); int size = list.size(); for (int i = 0; i < size; i++) { ContactItem it = (ContactItem)list.get(i); if (it.isAvailable()) { count++; } } setTitle(getGroupTitle(groupName) + " (" + count + " online)"); if (model.getSize() == 0) { model.addElement(noContacts); } } /** * Returns the containing <code>JList</code> of the ContactGroup. * * @return the JList. */ public JList getList() { return list; } /** * Clears all selections within this group. */ public void clearSelection() { list.clearSelection(); } /** * Returns true if the ContactGroup contains available users. * * @return true if the ContactGroup contains available users. */ public boolean hasAvailableContacts() { final Iterator iter = contactGroups.iterator(); while (iter.hasNext()) { ContactGroup group = (ContactGroup)iter.next(); if (group.hasAvailableContacts()) { return true; } } Iterator contacts = getContactItems().iterator(); while (contacts.hasNext()) { ContactItem item = (ContactItem)contacts.next(); if (item.getPresence() != null) { return true; } } return false; } /** * Sorts ContactItems. */ final Comparator<ContactItem> itemComparator = new Comparator() { public int compare(Object contactItemOne, Object contactItemTwo) { final ContactItem item1 = (ContactItem)contactItemOne; final ContactItem item2 = (ContactItem)contactItemTwo; return item1.getNickname().toLowerCase().compareTo(item2.getNickname().toLowerCase()); } }; /** * Returns true if this ContactGroup is the Offline Group. * * @return true if OfflineGroup. */ public boolean isOfflineGroup() { return "Offline Group".equals(getGroupName()); } /** * Returns true if this ContactGroup is the Unfiled Group. * * @return true if UnfiledGroup. */ public boolean isUnfiledGroup() { return "Unfiled".equals(getGroupName()); } public String toString() { return getGroupName(); } /** * Returns true if ContactGroup is a Shared Group. * * @return true if Shared Group. */ public boolean isSharedGroup() { return sharedGroup; } /** * Set to true if this ContactGroup is a shared Group. * * @param sharedGroup true if shared group. */ protected void setSharedGroup(boolean sharedGroup) { this.sharedGroup = sharedGroup; if (sharedGroup) { setToolTipText(Res.getString("message.is.shared.group", getGroupName())); } } /** * Returns all Selected Contacts within the ContactGroup. * * @return all selected ContactItems. */ public List getSelectedContacts() { final List items = new ArrayList(); Object[] selections = list.getSelectedValues(); final int no = selections != null ? selections.length : 0; for (int i = 0; i < no; i++) { ContactItem item = (ContactItem)selections[i]; items.add(item); } return items; } public JPanel getContainerPanel() { return listPanel; } public Collection getContactGroups() { return contactGroups; } /** * Lets make sure that the panel doesn't stretch past the * scrollpane view pane. * * @return the preferred dimension */ public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width = 0; return size; } public void setGroupName(String groupName) { this.groupName = groupName; } public String getGroupTitle(String title) { int lastIndex = title.lastIndexOf("::"); if (lastIndex != -1) { title = title.substring(lastIndex + 2); } return title; } public boolean isSubGroup(String groupName) { return groupName.indexOf("::") != -1; } public boolean isSubGroup() { return isSubGroup(getGroupName()); } public JPanel getListPanel() { return listPanel; } private void addPopupWindow() { final Timer timer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { canShowPopup = true; motionListener.mouseMoved(mouseEvent); } }); list.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent mouseEvent) { timer.start(); } public void mouseExited(MouseEvent mouseEvent) { timer.stop(); canShowPopup = false; } }); list.addMouseMotionListener(motionListener); } private class ListMotionListener extends MouseMotionAdapter { private ContactItem activeItem; public void mouseMoved(MouseEvent e) { if(e != null){ mouseEvent = e; } if(!canShowPopup){ return; } int loc = list.locationToIndex(e.getPoint()); Point point = list.indexToLocation(loc); ContactItem item = (ContactItem)model.getElementAt(loc); if (item == null || item.getFullJID() == null) { return; } if (activeItem != null && activeItem == item) { return; } activeItem = item; window.setVisible(false); window = new JWindow(); window.setFocusableWindowState(false); ContactInfo info = new ContactInfo(item); window.getContentPane().add(info); window.pack(); info.setBorder(BorderFactory.createEtchedBorder()); Point mainWindowLocation = SparkManager.getMainWindow().getLocationOnScreen(); Point listLocation = list.getLocationOnScreen(); int x = (int)mainWindowLocation.getX() + SparkManager.getMainWindow().getWidth(); final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if ((int)screenSize.getWidth() - 250 >= x) { window.setLocation(x, (int)listLocation.getY() + (int)point.getY()); window.setVisible(true); } else { window.setLocation((int)mainWindowLocation.getX() - 250, (int)listLocation.getY() + (int)point.getY()); window.setVisible(true); } } } }
package com.xpn.xwiki.test; import junit.extensions.TestSetup; import junit.framework.Test; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Commandline; import org.apache.tools.ant.taskdefs.ExecTask; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * JUnit TestSetup extension that starts/stops XWiki using a script passed using System Properties. * These properties are meant to be passed by the underlying build system. This class is meant to * wrap a JUnit TestSuite. For example: * * <pre><code> * public static Test suite() * { * // Create some TestSuite object here * return new XWikiTestSetup(suite); * } * </code></pre> * * <p> * Note: We could start XWiki using Java directly but we're using a script so that we can test the * exact same script used by XWiki users who download the standalone distribution. * </p> * * @version $Id: $ */ public class XWikiTestSetup extends TestSetup { private static final String EXECUTION_DIRECTORY = System.getProperty("xwikiExecutionDirectory"); private static final String START_COMMAND = System.getProperty("xwikiExecutionStartCommand"); private static final String STOP_COMMAND = System.getProperty("xwikiExecutionStopCommand"); private static final String PORT = System.getProperty("xwikiPort", "8080"); private static final boolean DEBUG = System.getProperty("debug", "false").equalsIgnoreCase("true"); private static final int TIMEOUT_SECONDS = 60; private Project project; public XWikiTestSetup(Test test) { super(test); this.project = new Project(); this.project.init(); this.project.addBuildListener(new AntBuildListener(DEBUG)); } protected void setUp() throws Exception { startXWikiInSeparateThread(); waitForXWikiToLoad(); } private void startXWikiInSeparateThread() { Thread startThread = new Thread(new Runnable() { public void run() { try { startXWiki(); } catch (Exception e) { throw new RuntimeException(e); } } }); startThread.start(); } private void startXWiki() throws Exception { ExecTask execTask = (ExecTask) this.project.createTask("exec"); execTask.setDir(new File(EXECUTION_DIRECTORY)); Commandline commandLine = new Commandline(START_COMMAND); execTask.setCommand(commandLine); execTask.execute(); } private Task createStopTask() { ExecTask execTask = (ExecTask) this.project.createTask("exec"); execTask.setDir(new File(EXECUTION_DIRECTORY)); Commandline commandLine = new Commandline(STOP_COMMAND); execTask.setCommand(commandLine); return execTask; } private void waitForXWikiToLoad() throws Exception { // Wait till the main page becomes available which means the server is started fine System.out.println("Checking that XWiki is up and running..."); URL url = new URL("http://localhost:" + PORT + "/xwiki/bin/view/Main/WebHome"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); boolean connected = false; boolean timedOut = false; long startTime = System.currentTimeMillis(); while (!connected && !timedOut) { try { connection.connect(); int responseCode = connection.getResponseCode(); if (DEBUG) { System.out.println("Result of pinging [" + url + "] = [" + responseCode + "], Message = [" + connection.getResponseMessage() + "]"); } connected = (responseCode < 400 || responseCode == 401); } catch (IOException e) { // Do nothing as it simply means the server is not ready yet... } Thread.sleep(100L); timedOut = (System.currentTimeMillis() - startTime > TIMEOUT_SECONDS * 1000L); } if (timedOut) { String message = "Failed to start XWiki in [" + TIMEOUT_SECONDS + "] seconds"; System.out.println(message); tearDown(); throw new RuntimeException(message); } } protected void tearDown() throws Exception { // Stop XWiki createStopTask().execute(); } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.Res; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.VerticalFlowLayout; import org.jivesoftware.spark.component.panes.CollapsiblePane; import org.jivesoftware.spark.component.renderer.JPanelRenderer; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.Timer; /** * Container representing a RosterGroup within the Contact List. */ public class ContactGroup extends CollapsiblePane implements MouseListener { private List<ContactItem> contactItems = new ArrayList<ContactItem>(); private List<ContactGroup> contactGroups = new ArrayList<ContactGroup>(); private List<ContactGroupListener> listeners = new ArrayList<ContactGroupListener>(); private List<ContactItem> offlineContacts = new ArrayList<ContactItem>(); private String groupName; private DefaultListModel model; private JList contactItemList; private boolean sharedGroup; private JPanel listPanel; // Used to display no contacts in list. private final ContactItem noContacts = new ContactItem("There are no online contacts in this group.", null); private final ListMotionListener motionListener = new ListMotionListener(); private boolean canShowPopup; private MouseEvent mouseEvent; private LocalPreferences preferences; /** * Create a new ContactGroup. * * @param groupName the name of the new ContactGroup. */ public ContactGroup(String groupName) { // Initialize Model and UI model = new DefaultListModel(); contactItemList = new JList(model); preferences = SettingsManager.getLocalPreferences(); setTitle(getGroupTitle(groupName)); // Use JPanel Renderer contactItemList.setCellRenderer(new JPanelRenderer()); this.groupName = groupName; listPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)); listPanel.add(contactItemList, listPanel); this.setContentPane(listPanel); if (!isOfflineGroup()) { contactItemList.setDragEnabled(true); contactItemList.setTransferHandler(new ContactGroupTransferHandler()); } // Allow for mouse events to take place on the title bar getTitlePane().addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseReleased(MouseEvent e) { checkPopup(e); } public void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { e.consume(); fireContactGroupPopupEvent(e); } } }); // Items should have selection listener contactItemList.addMouseListener(this); contactItemList.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent keyEvent) { } public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyChar() == KeyEvent.VK_ENTER) { ContactItem item = (ContactItem)contactItemList.getSelectedValue(); fireContactItemDoubleClicked(item); } ContactList.activeKeyEvent = keyEvent; } public void keyReleased(KeyEvent keyEvent) { ContactList.activeKeyEvent = null; } }); noContacts.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); noContacts.getNicknameLabel().setForeground(Color.GRAY); model.addElement(noContacts); // Add Popup Window addPopupWindow(); } /** * Adds a new offline contact. * * @param nickname the nickname of the offline contact. * @param jid the jid of the offline contact. */ public void addOfflineContactItem(String nickname, String jid, String status) { // Build new ContactItem final ContactItem offlineItem = new ContactItem(nickname, jid); offlineItem.setGroupName(getGroupName()); final Presence offlinePresence = PresenceManager.getPresence(jid); offlineItem.setPresence(offlinePresence); // set offline icon offlineItem.setIcon(PresenceManager.getIconFromPresence(offlinePresence)); // Set status if applicable. if (ModelUtil.hasLength(status)) { offlineItem.setStatusText(status); } // Add to offlien contacts. offlineContacts.add(offlineItem); insertOfflineContactItem(offlineItem); } /** * Inserts a new offline <code>ContactItem</code> into the ui model. * * @param offlineItem the ContactItem to add. */ public void insertOfflineContactItem(ContactItem offlineItem) { if (model.contains(offlineItem)) { return; } if (!preferences.isOfflineGroupVisible()) { Collections.sort(offlineContacts, itemComparator); int index = offlineContacts.indexOf(offlineItem); int totalListSize = contactItems.size(); int newPos = totalListSize + index; if (newPos > model.size()) { newPos = model.size(); } model.insertElementAt(offlineItem, newPos); if (model.contains(noContacts)) { model.removeElement(noContacts); } } } /** * Removes an offline <code>ContactItem</code> from the Offline contact * model and ui. * * @param item the offline contact item to remove. */ public void removeOfflineContactItem(ContactItem item) { offlineContacts.remove(item); removeContactItem(item); } /** * Removes an offline <code>ContactItem</code> from the offline contact model and ui. * * @param jid the offline contact item to remove. */ public void removeOfflineContactItem(String jid) { final List<ContactItem> items = new ArrayList<ContactItem>(offlineContacts); for (ContactItem item : items) { if (item.getJID().equals(jid)) { removeOfflineContactItem(item); } } } /** * Toggles the visibility of Offline Contacts. * * @param show true if offline contacts should be shown, otherwise false. */ public void toggleOfflineVisibility(boolean show) { final List<ContactItem> items = new ArrayList<ContactItem>(offlineContacts); for (ContactItem item : items) { if (show) { insertOfflineContactItem(item); } else { model.removeElement(item); } } } /** * Adds a <code>ContactItem</code> to the ContactGroup. * * @param item the ContactItem. */ public void addContactItem(ContactItem item) { // Remove from offline group if it exists removeOfflineContactItem(item.getJID()); if (model.contains(noContacts)) { model.remove(0); } if ("Offline Group".equals(groupName)) { item.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); item.getNicknameLabel().setForeground(Color.GRAY); } item.setGroupName(getGroupName()); contactItems.add(item); List<ContactItem> tempItems = getContactItems(); Collections.sort(tempItems, itemComparator); int index = tempItems.indexOf(item); Object[] objs = contactItemList.getSelectedValues(); model.insertElementAt(item, index); int[] intList = new int[objs.length]; for (int i = 0; i < objs.length; i++) { ContactItem contact = (ContactItem)objs[i]; intList[i] = model.indexOf(contact); } if (intList.length > 0) { contactItemList.setSelectedIndices(intList); } fireContactItemAdded(item); } /** * Call whenever the UI needs to be updated. */ public void fireContactGroupUpdated() { contactItemList.validate(); contactItemList.repaint(); updateTitle(); } public void addContactGroup(ContactGroup contactGroup) { final JPanel panel = new JPanel(new GridBagLayout()); panel.add(contactGroup, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 15, 0, 0), 0, 0)); panel.setBackground(Color.white); contactGroup.setSubPane(true); // contactGroup.setStyle(CollapsiblePane.TREE_STYLE); listPanel.add(panel); contactGroups.add(contactGroup); } /** * Removes a child ContactGroup. * * @param contactGroup the contact group to remove. */ public void removeContactGroup(ContactGroup contactGroup) { Component[] comps = listPanel.getComponents(); for (int i = 0; i < comps.length; i++) { Component comp = comps[i]; if (comp instanceof JPanel) { JPanel panel = (JPanel)comp; ContactGroup group = (ContactGroup)panel.getComponent(0); if (group == contactGroup) { listPanel.remove(panel); break; } } } contactGroups.remove(contactGroup); } public void setPanelBackground(Color color) { Component[] comps = listPanel.getComponents(); for (int i = 0; i < comps.length; i++) { Component comp = comps[i]; if (comp instanceof JPanel) { JPanel panel = (JPanel)comp; panel.setBackground(color); } } } /** * Returns a ContactGroup based on it's name. * * @param groupName the name of the group. * @return the ContactGroup. */ public ContactGroup getContactGroup(String groupName) { final Iterator groups = new ArrayList(contactGroups).iterator(); while (groups.hasNext()) { ContactGroup group = (ContactGroup)groups.next(); if (group.getGroupName().equals(groupName)) { return group; } } return null; } /** * Removes a <code>ContactItem</code>. * * @param item the ContactItem to remove. */ public void removeContactItem(ContactItem item) { contactItems.remove(item); model.removeElement(item); updateTitle(); fireContactItemRemoved(item); } /** * Returns a <code>ContactItem</code> by the nickname the user has been assigned. * * @param nickname the nickname of the user. * @return the ContactItem. */ public ContactItem getContactItemByNickname(String nickname) { final Iterator iter = new ArrayList(contactItems).iterator(); while (iter.hasNext()) { ContactItem item = (ContactItem)iter.next(); if (item.getNickname().equals(nickname)) { return item; } } return null; } /** * Returns a <code>ContactItem</code> by the users bare bareJID. * * @param bareJID the bareJID of the user. * @return the ContactItem. */ public ContactItem getContactItemByJID(String bareJID) { final Iterator iter = new ArrayList(contactItems).iterator(); while (iter.hasNext()) { ContactItem item = (ContactItem)iter.next(); if (item.getJID().equals(bareJID)) { return item; } } return null; } /** * Returns all <code>ContactItem</cod>s in the ContactGroup. * * @return all ContactItems. */ public List<ContactItem> getContactItems() { final List<ContactItem> list = new ArrayList<ContactItem>(contactItems); Collections.sort(list, itemComparator); return list; } /** * Returns the name of the ContactGroup. * * @return the name of the ContactGroup. */ public String getGroupName() { return groupName; } public void mouseClicked(MouseEvent e) { Object o = contactItemList.getSelectedValue(); if (!(o instanceof ContactItem)) { return; } // Iterator through rest ContactItem item = (ContactItem)o; if (e.getClickCount() == 2) { fireContactItemDoubleClicked(item); } else if (e.getClickCount() == 1) { fireContactItemClicked(item); } } public void mouseEntered(MouseEvent e) { int loc = contactItemList.locationToIndex(e.getPoint()); Object o = model.getElementAt(loc); if (!(o instanceof ContactItem)) { return; } ContactItem item = (ContactItem)o; if (item == null) { return; } contactItemList.setCursor(GraphicUtils.HAND_CURSOR); } public void mouseExited(MouseEvent e) { Object o = null; try { int loc = contactItemList.locationToIndex(e.getPoint()); if (loc == -1) { return; } o = model.getElementAt(loc); if (!(o instanceof ContactItem)) { ContactInfoWindow.getInstance().dispose(); return; } } catch (Exception e1) { Log.error(e1); return; } ContactItem item = (ContactItem)o; if (item == null) { return; } contactItemList.setCursor(GraphicUtils.DEFAULT_CURSOR); } public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseReleased(MouseEvent e) { checkPopup(e); } private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { // Otherwise, handle single selection int index = contactItemList.locationToIndex(e.getPoint()); if (index != -1) { int[] indexes = contactItemList.getSelectedIndices(); boolean selected = false; for (int i = 0; i < indexes.length; i++) { int o = indexes[i]; if (index == o) { selected = true; } } if (!selected) { contactItemList.setSelectedIndex(index); fireContactItemClicked((ContactItem)contactItemList.getSelectedValue()); } } final Collection selectedItems = SparkManager.getChatManager().getSelectedContactItems(); if (selectedItems.size() > 1) { firePopupEvent(e, selectedItems); return; } else if (selectedItems.size() == 1) { final ContactItem contactItem = (ContactItem)selectedItems.iterator().next(); firePopupEvent(e, contactItem); } } } /** * Add a <code>ContactGroupListener</code>. * * @param listener the ContactGroupListener. */ public void addContactGroupListener(ContactGroupListener listener) { listeners.add(listener); } /** * Removes a <code>ContactGroupListener</code>. * * @param listener the ContactGroupListener. */ public void removeContactGroupListener(ContactGroupListener listener) { listeners.remove(listener); } private void fireContactItemClicked(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemClicked(item); } } private void fireContactItemDoubleClicked(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemDoubleClicked(item); } } private void firePopupEvent(MouseEvent e, ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).showPopup(e, item); } } private void firePopupEvent(MouseEvent e, Collection items) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).showPopup(e, items); } } private void fireContactGroupPopupEvent(MouseEvent e) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactGroupPopup(e, this); } } private void fireContactItemAdded(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemAdded(item); } } private void fireContactItemRemoved(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemRemoved(item); } } private void updateTitle() { if ("Offline Group".equals(groupName)) { setTitle("Offline Group"); return; } int count = 0; List list = new ArrayList(getContactItems()); int size = list.size(); for (int i = 0; i < size; i++) { ContactItem it = (ContactItem)list.get(i); if (it.isAvailable()) { count++; } } setTitle(getGroupTitle(groupName) + " (" + count + " online)"); if (model.getSize() == 0) { model.addElement(noContacts); } } /** * Returns the containing <code>JList</code> of the ContactGroup. * * @return the JList. */ public JList getList() { return contactItemList; } /** * Clears all selections within this group. */ public void clearSelection() { contactItemList.clearSelection(); } public void removeAllContacts() { // Remove all users from online group. Iterator contactItems = new ArrayList(getContactItems()).iterator(); while (contactItems.hasNext()) { ContactItem item = (ContactItem)contactItems.next(); removeContactItem(item); } // Remove all users from offline group. for (ContactItem item : getOfflineContacts()) { removeOfflineContactItem(item); } } /** * Returns true if the ContactGroup contains available users. * * @return true if the ContactGroup contains available users. */ public boolean hasAvailableContacts() { final Iterator iter = contactGroups.iterator(); while (iter.hasNext()) { ContactGroup group = (ContactGroup)iter.next(); if (group.hasAvailableContacts()) { return true; } } Iterator contacts = getContactItems().iterator(); while (contacts.hasNext()) { ContactItem item = (ContactItem)contacts.next(); if (item.getPresence() != null) { return true; } } return false; } public Collection<ContactItem> getOfflineContacts() { return new ArrayList<ContactItem>(offlineContacts); } /** * Sorts ContactItems. */ final Comparator<ContactItem> itemComparator = new Comparator() { public int compare(Object contactItemOne, Object contactItemTwo) { final ContactItem item1 = (ContactItem)contactItemOne; final ContactItem item2 = (ContactItem)contactItemTwo; return item1.getNickname().toLowerCase().compareTo(item2.getNickname().toLowerCase()); } }; /** * Returns true if this ContactGroup is the Offline Group. * * @return true if OfflineGroup. */ public boolean isOfflineGroup() { return "Offline Group".equals(getGroupName()); } /** * Returns true if this ContactGroup is the Unfiled Group. * * @return true if UnfiledGroup. */ public boolean isUnfiledGroup() { return "Unfiled".equals(getGroupName()); } public String toString() { return getGroupName(); } /** * Returns true if ContactGroup is a Shared Group. * * @return true if Shared Group. */ public boolean isSharedGroup() { return sharedGroup; } /** * Set to true if this ContactGroup is a shared Group. * * @param sharedGroup true if shared group. */ protected void setSharedGroup(boolean sharedGroup) { this.sharedGroup = sharedGroup; if (sharedGroup) { setToolTipText(Res.getString("message.is.shared.group", getGroupName())); } } /** * Returns all Selected Contacts within the ContactGroup. * * @return all selected ContactItems. */ public List getSelectedContacts() { final List items = new ArrayList(); Object[] selections = contactItemList.getSelectedValues(); final int no = selections != null ? selections.length : 0; for (int i = 0; i < no; i++) { ContactItem item = (ContactItem)selections[i]; items.add(item); } return items; } public JPanel getContainerPanel() { return listPanel; } public Collection getContactGroups() { return contactGroups; } /** * Lets make sure that the panel doesn't stretch past the * scrollpane view pane. * * @return the preferred dimension */ public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width = 0; return size; } /** * Sets the name of group. * * @param groupName the contact group name. */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * Returns the "pretty" title of the ContactGroup. * * @param title the title. * @return the new title. */ public String getGroupTitle(String title) { int lastIndex = title.lastIndexOf("::"); if (lastIndex != -1) { title = title.substring(lastIndex + 2); } return title; } /** * Returns true if the group is nested. * * @param groupName the name of the group. * @return true if the group is nested. */ public boolean isSubGroup(String groupName) { return groupName.indexOf("::") != -1; } /** * Returns true if this group is nested. * * @return true if nested. */ public boolean isSubGroup() { return isSubGroup(getGroupName()); } /** * Returns the underlying container for the JList. * * @return the underlying container of the JList. */ public JPanel getListPanel() { return listPanel; } /** * Adds an internal popup listesner. */ private void addPopupWindow() { final Timer timer = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { canShowPopup = true; } }); contactItemList.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent mouseEvent) { timer.start(); } public void mouseExited(MouseEvent mouseEvent) { timer.stop(); canShowPopup = false; ContactInfoWindow.getInstance().dispose(); } }); contactItemList.addMouseMotionListener(motionListener); } private class ListMotionListener extends MouseMotionAdapter { public void mouseMoved(MouseEvent e) { if (e != null) { mouseEvent = e; } if (!canShowPopup) { return; } if (e == null) { return; } displayWindow(e); } } /** * Displays the <code>ContactInfoWindow</code>. * * @param e the mouseEvent that triggered this event. */ private void displayWindow(MouseEvent e) { ContactInfoWindow.getInstance().display(this, e); } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.resource.Res; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.RosterGroup; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.packet.VCard; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.UserManager; import org.jivesoftware.spark.component.TitlePanel; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.ResourceUtils; import org.jivesoftware.spark.util.log.Log; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Vector; /** * The RosterDialog is used to add new users to the users XMPP Roster. */ public class RosterDialog implements PropertyChangeListener, ActionListener { private JPanel panel; private JTextField jidField; private JTextField nicknameField; private final Vector<String> groupModel = new Vector<String>(); private JComboBox groupBox; private JOptionPane pane; private JDialog dialog; private ContactList contactList; /** * Create a new instance of RosterDialog. */ public RosterDialog() { contactList = SparkManager.getWorkspace().getContactList(); panel = new JPanel(); JLabel contactIDLabel = new JLabel(); jidField = new JTextField(); JLabel nicknameLabel = new JLabel(); nicknameField = new JTextField(); JLabel groupLabel = new JLabel(); groupBox = new JComboBox(groupModel); JButton newGroupButton = new JButton(); pane = null; dialog = null; panel.setLayout(new GridBagLayout()); panel.add(contactIDLabel, new GridBagConstraints(0, 0, 1, 1, 0.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); panel.add(jidField, new GridBagConstraints(1, 0, 1, 1, 1.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); panel.add(nicknameLabel, new GridBagConstraints(0, 1, 1, 1, 0.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); panel.add(nicknameField, new GridBagConstraints(1, 1, 1, 1, 1.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); panel.add(groupLabel, new GridBagConstraints(0, 2, 1, 1, 0.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); panel.add(groupBox, new GridBagConstraints(1, 2, 1, 1, 1.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); panel.add(newGroupButton, new GridBagConstraints(2, 2, 1, 1, 0.0D, 0.0D, 17, 2, new Insets(5, 5, 5, 5), 0, 0)); newGroupButton.addActionListener(this); ResourceUtils.resLabel(contactIDLabel, jidField, Res.getString("label.jabber.id") + ":"); ResourceUtils.resLabel(nicknameLabel, nicknameField, Res.getString("label.nickname") + ":"); ResourceUtils.resLabel(groupLabel, groupBox, Res.getString("label.group") + ":"); ResourceUtils.resButton(newGroupButton, Res.getString("button.new")); for (ContactGroup group : contactList.getContactGroups()) { if (!group.isOfflineGroup() && !"Unfiled".equalsIgnoreCase(group.getGroupName()) && !group.isSharedGroup()) { groupModel.add(group.getGroupName()); } } groupBox.setEditable(true); if (groupModel.size() == 0) { groupBox.addItem("Friends"); } if (groupModel.size() > 0) { groupBox.setSelectedIndex(0); } jidField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { String jid = jidField.getText(); if (ModelUtil.hasLength(jid) && jid.indexOf('@') == -1) { // Append server address jidField.setText(jid + "@" + SparkManager.getConnection().getServiceName()); } String nickname = nicknameField.getText(); if (!ModelUtil.hasLength(nickname) && ModelUtil.hasLength(jid)) { nicknameField.setText(StringUtils.parseName(jidField.getText())); } } }); } /** * Sets the default <code>ContactGroup</code> to display in the combo box. * * @param contactGroup the default ContactGroup. */ public void setDefaultGroup(ContactGroup contactGroup) { String groupName = contactGroup.getGroupName(); if (groupModel.contains(groupName)) { groupBox.setSelectedItem(groupName); } else if (groupModel.size() > 0) { groupBox.addItem(groupName); groupBox.setSelectedItem(groupName); } } /** * Sets the default jid to show in the jid field. * * @param jid the jid. */ public void setDefaultJID(String jid) { jidField.setText(jid); } /** * Sets the default nickname to show in the nickname field. * * @param nickname the nickname. */ public void setDefaultNickname(String nickname) { nicknameField.setText(nickname); } public void actionPerformed(ActionEvent e) { String group = JOptionPane.showInputDialog(dialog, Res.getString("label.enter.group.name") +":", Res.getString("title.new.roster.group"), 3); if (group != null && group.length() > 0 && !groupModel.contains(group)) { SparkManager.getConnection().getRoster().createGroup(group); groupModel.add(group); int size = groupModel.size(); groupBox.setSelectedIndex(size - 1); } } /** * Display the RosterDialog using a parent container. * * @param parent the parent Frame. */ public void showRosterDialog(JFrame parent) { TitlePanel titlePanel = new TitlePanel(Res.getString("title.add.contact"), Res.getString("message.add.contact.to.list"), SparkRes.getImageIcon(SparkRes.USER1_32x32), true); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); mainPanel.add(titlePanel, BorderLayout.NORTH); Object[] options = { Res.getString("add"), Res.getString("cancel") }; pane = new JOptionPane(panel, -1, 2, null, options, options[0]); mainPanel.add(pane, BorderLayout.CENTER); dialog = new JDialog(parent, Res.getString("title.add.contact"), true); dialog.pack(); dialog.setContentPane(mainPanel); dialog.setSize(350, 250); dialog.setLocationRelativeTo(parent); pane.addPropertyChangeListener(this); dialog.setVisible(true); dialog.toFront(); dialog.requestFocus(); jidField.requestFocus(); } /** * Display the RosterDialog using the MainWindow as the parent. */ public void showRosterDialog() { showRosterDialog(SparkManager.getMainWindow()); } public void propertyChange(PropertyChangeEvent e) { if (pane != null && pane.getValue() instanceof Integer) { pane.removePropertyChangeListener(this); dialog.dispose(); return; } String value = (String)pane.getValue(); String errorMessage = Res.getString("title.error"); if (Res.getString("cancel").equals(value)) { dialog.setVisible(false); } else if (Res.getString("add").equals(value)) { String contact = UserManager.escapeJID(jidField.getText()); String nickname = nicknameField.getText(); String group = (String)groupBox.getSelectedItem(); if (!ModelUtil.hasLength(nickname) && ModelUtil.hasLength(contact)) { // Try to load nickname from VCard VCard vcard = new VCard(); try { vcard.load(SparkManager.getConnection(), contact); nickname = vcard.getNickName(); } catch (XMPPException e1) { Log.error(e1); } // If no nickname, use first name. if (!ModelUtil.hasLength(nickname)) { nickname = StringUtils.parseName(contact); } nicknameField.setText(nickname); } ContactGroup contactGroup = contactList.getContactGroup(group); boolean isSharedGroup = contactGroup != null && contactGroup.isSharedGroup(); if (isSharedGroup) { errorMessage = Res.getString("message.cannot.add.contact.to.shared.group"); } else if (!ModelUtil.hasLength(contact)) { errorMessage = Res.getString("message.specify.contact.jid"); } else if (StringUtils.parseBareAddress(contact).indexOf("@") == -1) { errorMessage = Res.getString("message.invalid.jid.error"); } else if (!ModelUtil.hasLength(group)) { errorMessage = Res.getString("message.specify.group"); } else if (ModelUtil.hasLength(contact) && ModelUtil.hasLength(group) && !isSharedGroup) { addEntry(); dialog.setVisible(false); return; } JOptionPane.showMessageDialog(dialog, errorMessage, Res.getString("title.error"), JOptionPane.ERROR_MESSAGE); pane.setValue(JOptionPane.UNINITIALIZED_VALUE); } } private void addEntry() { String jid = jidField.getText(); if (jid.indexOf("@") == -1) { jid = jid + "@" + SparkManager.getConnection().getHost(); } String nickname = nicknameField.getText(); String group = (String)groupBox.getSelectedItem(); jid = UserManager.escapeJID(jid); // Add as a new entry addEntry(jid, nickname, group); } /** * Adds a new entry to the users Roster. * * @param jid the jid. * @param nickname the nickname. * @param group the contact group. * @return the new RosterEntry. */ public RosterEntry addEntry(String jid, String nickname, String group) { String[] groups = {group}; Roster roster = SparkManager.getConnection().getRoster(); RosterEntry userEntry = roster.getEntry(jid); boolean isSubscribed = true; if (userEntry != null) { isSubscribed = userEntry.getGroups().size() == 0; } if (isSubscribed) { try { roster.createEntry(jid, nickname, new String[]{group}); } catch (XMPPException e) { Log.error("Unable to add new entry " + jid, e); } return roster.getEntry(jid); } try { RosterGroup rosterGroup = roster.getGroup(group); if (rosterGroup == null) { rosterGroup = roster.createGroup(group); } if (userEntry == null) { roster.createEntry(jid, nickname, groups); userEntry = roster.getEntry(jid); } else { userEntry.setName(nickname); rosterGroup.addEntry(userEntry); } userEntry = roster.getEntry(jid); } catch (XMPPException ex) { Log.error(ex); } return userEntry; } }
package org.orbeon.oxf.processor; import org.apache.log4j.Logger; import org.dom4j.Element; import org.dom4j.QName; import org.orbeon.oxf.cache.*; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.debugger.api.BreakpointKey; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.pipeline.api.PipelineContext.Trace; import org.orbeon.oxf.pipeline.api.PipelineContext.TraceInfo; import org.orbeon.oxf.processor.generator.DOMGenerator; import org.orbeon.oxf.processor.validation.MSVValidationProcessor; import org.orbeon.oxf.properties.Properties; import org.orbeon.oxf.properties.PropertySet; import org.orbeon.oxf.util.IndentedLogger; import org.orbeon.oxf.util.LoggerFactory; import org.orbeon.oxf.util.PipelineUtils; import org.orbeon.oxf.xml.*; import org.orbeon.oxf.xml.XMLUtils; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.oxf.xml.dom4j.LocationSAXContentHandler; import org.orbeon.oxf.xml.dom4j.NonLazyUserDataDocument; import org.orbeon.saxon.om.DocumentInfo; import org.orbeon.saxon.om.FastStringBuffer; import org.orbeon.saxon.tinytree.TinyBuilder; import org.w3c.dom.Document; import org.xml.sax.ContentHandler; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.sax.TransformerHandler; import java.util.*; /** * Helper class that implements default method of the Processor interface. */ public abstract class ProcessorImpl implements Processor { final public static Logger logger = LoggerFactory.createLogger(ProcessorImpl.class); public static IndentedLogger indentedLogger = new IndentedLogger(logger, "XPL processor"); public static final String INPUT_DATA = "data"; public static final String INPUT_CONFIG = "config"; public static final String OUTPUT_DATA = "data"; public static final String PROCESSOR_VALIDATION_FLAG = "oxf.validation.processor"; public static final String USER_VALIDATION_FLAG = "oxf.validation.user"; public static final String SAX_INSPECTION_FLAG = "oxf.sax.inspection"; public static final char KEY_SEPARATOR = '?'; private static final List<ProcessorInput> EMPTY_INPUT_LIST = Collections.emptyList(); private String id; private QName name; private Map<String, List<ProcessorInput>> inputMap = new LinkedHashMap<String, List<ProcessorInput>>(); private Map<String, ProcessorOutput> outputMap = new LinkedHashMap<String, ProcessorOutput>(); private int outputCount = 0; private List<ProcessorInputOutputInfo> inputsInfo = new ArrayList<ProcessorInputOutputInfo>(0); private List<ProcessorInputOutputInfo> outputsInfo = new ArrayList<ProcessorInputOutputInfo>(0); private LocationData locationData; public static final String PROCESSOR_INPUT_SCHEME_OLD = "oxf:"; public static final String PROCESSOR_INPUT_SCHEME = "input:"; /** * Return a property set for this processor. */ protected PropertySet getPropertySet() { return Properties.instance().getPropertySet(getName()); } public LocationData getLocationData() { return locationData; } public void setLocationData( final LocationData loc ) { locationData = loc; } public void setId(String id) { this.id = id; } public String getId() { return id; } public QName getName() { return name; } public void setName(QName name) { this.name = name; } public ProcessorInput getInputByName(String name) { List l = (List) inputMap.get(name); if (l == null) throw new ValidationException("Cannot find input \"" + name + "\"", getLocationData()); if (l.size() != 1) throw new ValidationException("Found more than one input \"" + name + "\"", getLocationData()); return (ProcessorInput) l.get(0); } public List<ProcessorInput> getInputsByName(String name) { final List<ProcessorInput> result = inputMap.get(name); return result == null ? EMPTY_INPUT_LIST : result; } public ProcessorInput createInput(final String name) { final ProcessorInputOutputInfo inputInfo = getInputInfo(name); // The PropertySet can be null during properties initialization. This should be one of the // rare places where this should be tested on. By default, enable validation so the // properties can be validated! final PropertySet propertySet = Properties.instance().getPropertySet(); final Boolean valEnabled = (propertySet == null) ? new Boolean(true) : propertySet.getBoolean(PROCESSOR_VALIDATION_FLAG, true); if (valEnabled.booleanValue() && inputInfo != null && inputInfo.getSchemaURI() != null) { if (logger.isDebugEnabled()) logger.debug("Creating validator for input name '" + name + "' and schema-uri '" + inputInfo.getSchemaURI() + "'"); // Create and hook-up input validation processor if needed final Processor inputValidator = new MSVValidationProcessor(inputInfo.getSchemaURI()); // Connect schema to validator final Processor schema = PipelineUtils.createURLGenerator(SchemaRepository.instance().getSchemaLocation(inputInfo.getSchemaURI())); PipelineUtils.connect(schema, OUTPUT_DATA, inputValidator, MSVValidationProcessor.INPUT_SCHEMA); PipelineUtils.connect(MSVValidationProcessor.NO_DECORATION_CONFIG, OUTPUT_DATA, inputValidator, INPUT_CONFIG); // Create data input and output final ProcessorInput inputValData = inputValidator.createInput(INPUT_DATA); final ProcessorOutput outputValData = inputValidator.createOutput(OUTPUT_DATA); ProcessorInput fakeInput = new ProcessorInput() { public String getDebugMessage() { return inputValData.getDebugMessage(); } public LocationData getLocationData() { return inputValData.getLocationData(); } public String getName() { return name; } public ProcessorOutput getOutput() { return outputValData; } public Class getProcessorClass() { return ProcessorImpl.this.getClass(); } public String getSchema() { return inputValData.getSchema(); } public void setDebug(String debugMessage) { inputValData.setDebug(debugMessage); } public void setLocationData(LocationData locationData) { inputValData.setLocationData(locationData); } public void setBreakpointKey(BreakpointKey breakpointKey) { inputValData.setBreakpointKey(breakpointKey); } public void setOutput(ProcessorOutput output) { inputValData.setOutput(output); } public void setSchema(String schema) { inputValData.setSchema(schema); } }; addInput(name, fakeInput); return fakeInput; } else { final ProcessorInput input = new ProcessorInputImpl(ProcessorImpl.this.getClass(), name); addInput(name, input); return input; } } public void addInput(String name, ProcessorInput input) { List<ProcessorInput> inputs = inputMap.get(name); if (inputs == null) { inputs = new ArrayList<ProcessorInput>(); inputMap.put(name, inputs); } // if (inputs.size() > 0) // logger.info("Processor " + getClass().getName() + " has more than 1 input called " + name); inputs.add(input); } public void deleteInput(ProcessorInput input) { deleteFromListMap(inputMap, input); } public ProcessorOutput getOutputByName(String name) { ProcessorOutput ret = (ProcessorOutput) outputMap.get(name); if (ret == null ) throw new ValidationException("Exactly one output " + name + " is required", getLocationData()); return ret; } public ProcessorOutput createOutput(String name) { throw new ValidationException("Outputs are not supported", getLocationData()); } public void addOutput(String name, ProcessorOutput output) { // NOTE: One exception to the rule that we only have one output with a given name is the TeeProcessor, which // adds multiple outputs called "data". outputMap.put(name, output); outputCount++; } protected int getOutputCount() { return outputCount; } // NOTE: As of 2009-06-26, this is never called. public void deleteOutput(ProcessorOutput output) { final Collection outputs = outputMap.values(); outputs.remove(output); // NOTE: This won't be correct with the TeeProcessor. outputCount } protected void addInputInfo(ProcessorInputOutputInfo inputInfo) { inputsInfo.add(inputInfo); } protected void removeInputInfo(ProcessorInputOutputInfo inputInfo) { inputsInfo.remove(inputInfo); } protected void addOutputInfo(ProcessorInputOutputInfo outputInfo) { outputsInfo.add(outputInfo); } protected void removeOutputInfo(ProcessorInputOutputInfo outputInfo) { outputsInfo.remove(outputInfo); } public List<ProcessorInputOutputInfo> getInputsInfo() { return inputsInfo; } public Map<String, List<ProcessorInput>> getConnectedInputs() { return Collections.unmodifiableMap(inputMap); } public ProcessorInputOutputInfo getInputInfo(String name) { for (Iterator i = inputsInfo.iterator(); i.hasNext();) { ProcessorInputOutputInfo inputInfo = (ProcessorInputOutputInfo) i.next(); if (inputInfo.getName().equals(name)) return inputInfo; } return null; } public List<ProcessorInputOutputInfo> getOutputsInfo() { return outputsInfo; } public Map<String, ProcessorOutput> getConnectedOutputs() { return Collections.unmodifiableMap(outputMap); } public ProcessorInputOutputInfo getOutputInfo(String name) { for (Iterator i = outputsInfo.iterator(); i.hasNext();) { ProcessorInputOutputInfo outputInfo = (ProcessorInputOutputInfo) i.next(); if (outputInfo.getName().equals(name)) return outputInfo; } return null; } public void checkSockets() { // FIXME: This method is never called and it cannot work correctly // right now as some processor (pipeline, aggregator) are not exposing their // interface correctly. This will be fixed when we implement the full // delegation model. throw new UnsupportedOperationException(); // Check that each connection has a corresponding socket info // for (int io = 0; io < 2; io++) { // for (Iterator i = (io == 0 ? inputMap : outputMap).keySet().iterator(); i.hasNext();) { // String inputName = (String) i.next(); // boolean found = false; // for (Iterator j = socketInfo.iterator(); j.hasNext();) { // ProcessorInputOutputInfo socketInfo = (ProcessorInputOutputInfo) j.next(); // if (socketInfo.getType() == // (io == 0 ? ProcessorInputOutputInfo.INPUT_TYPE : ProcessorInputOutputInfo.OUTPUT_TYPE) // && socketInfo.getName().equals(inputName)) { // found = true; // break; // if (!found) // throw new ValidationException("Processor does not support " + (io == 0 ? "input" : "output") + // " with name " + inputName, getLocationData()); } /** * The fundamental read method based on SAX. */ protected static void readInputAsSAX(PipelineContext context, final ProcessorInput input, ContentHandler contentHandler) { // if (input instanceof ProcessorInputImpl) { // input.getOutput().read(context, new ForwardingContentHandler(contentHandler) { // private Locator locator; // public void setDocumentLocator(Locator locator) { // this.locator = locator; // super.setDocumentLocator(locator); // public void startDocument() throws SAXException { // // Try to get the system id and set it on the input // if (locator != null && locator.getSystemId() != null) { //// System.out.println("Got system id: " + locator.getSystemId()); // ((ProcessorInputImpl) input).setSystemId(locator.getSystemId()); // super.startDocument(); // } else { input.getOutput().read(context, contentHandler); } protected void readInputAsSAX(PipelineContext context, String inputName, ContentHandler contentHandler) { readInputAsSAX(context, getInputByName(inputName), contentHandler); } protected Document readInputAsDOM(PipelineContext context, ProcessorInput input) { final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler(); final DOMResult domResult = new DOMResult(XMLUtils.createDocument()); identity.setResult(domResult); readInputAsSAX(context, input, identity); return (Document) domResult.getNode(); } protected org.dom4j.Document readInputAsDOM4J(PipelineContext context, ProcessorInput input) { LocationSAXContentHandler ch = new LocationSAXContentHandler(); readInputAsSAX(context, input, ch); return ch.getDocument(); } protected DocumentInfo readInputAsTinyTree(PipelineContext context, ProcessorInput input) { final TinyBuilder treeBuilder = new TinyBuilder(); final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler(); identity.setResult(treeBuilder); readInputAsSAX(context, input, identity); return (DocumentInfo) treeBuilder.getCurrentRoot(); } protected Document readInputAsDOM(PipelineContext context, String inputName) { return readInputAsDOM(context, getInputByName(inputName)); } protected org.dom4j.Document readInputAsDOM4J(PipelineContext context, String inputName) { return readInputAsDOM4J(context, getInputByName(inputName)); } protected Document readCacheInputAsDOM(PipelineContext context, String inputName) { return (Document) readCacheInputAsObject(context, getInputByName(inputName), new CacheableInputReader() { public Object read(PipelineContext context, ProcessorInput input) { return readInputAsDOM(context, input); } }); } protected org.dom4j.Document readCacheInputAsDOM4J(PipelineContext context, String inputName) { return (org.dom4j.Document) readCacheInputAsObject(context, getInputByName(inputName), new CacheableInputReader() { public Object read(PipelineContext context, ProcessorInput input) { return readInputAsDOM4J(context, input); } }); } protected DocumentInfo readCacheInputAsTinyTree(PipelineContext context, String inputName) { return (DocumentInfo) readCacheInputAsObject(context, getInputByName(inputName), new CacheableInputReader() { public Object read(PipelineContext context, ProcessorInput input) { return readInputAsTinyTree(context, input); } }); } /** * To be used in the readImpl implementation of a processor when an object * is created based on an input (an the object only depends on the input). * * @param input The input the object depends on * @param reader The code constructing the object based on the input * @return The object returned by the reader (either directly returned, * or from the cache) */ protected Object readCacheInputAsObject(PipelineContext context, ProcessorInput input, CacheableInputReader reader) { // Get associated output ProcessorOutput output = input.getOutput(); String debugInfo = logger.isDebugEnabled() ? "[" + output.getName() + ", " + output.getProcessorClass() + ", " + input.getName() + ", " + input.getProcessorClass() + "]" : null; if (output instanceof Cacheable) { // Get cache instance final Cache cache = ObjectCache.instance(); // Check in cache first KeyValidity keyValidity = getInputKeyValidity(context, input); if (keyValidity != null) { final Object inputObject = cache.findValid(context, keyValidity.key, keyValidity.validity); if (inputObject != null) { // Return cached object if (logger.isDebugEnabled()) logger.debug("Cache " + debugInfo + ": source cacheable and found for key '" + keyValidity.key + "'. FOUND object: " + inputObject); reader.foundInCache(); return inputObject; } } // Result was not found in cache, read result // final long startTime = System.nanoTime(); if (logger.isDebugEnabled()) logger.debug("Cache " + debugInfo + ": READING."); final Object result = reader.read(context, input); // Cache new result if possible, asking again for KeyValidity if needed if (keyValidity == null) keyValidity = getInputKeyValidity(context, input); if (keyValidity != null) { if (logger.isDebugEnabled()) logger.debug("Cache " + debugInfo + ": source cacheable for key '" + keyValidity.key + "'. STORING object:" + result); cache.add(context, keyValidity.key, keyValidity.validity, result); // System.out.println("Cache cost: " + (System.nanoTime() - startTime)); reader.storedInCache(); } return result; } else { if (logger.isDebugEnabled()) logger.debug("Cache " + debugInfo + ": source never cacheable. READING."); // Never read from cache return reader.read(context, input); } } protected Object getCachedInputAsObject(PipelineContext pipelineContext, ProcessorInput processorInput) { // Get associated output final ProcessorOutput output = processorInput.getOutput(); if (output instanceof Cacheable) { // Get cache instance final Cache cache = ObjectCache.instance(); // Check cache final KeyValidity keyValidity = getInputKeyValidity(pipelineContext, processorInput); if (keyValidity != null) { return cache.findValid(pipelineContext, keyValidity.key, keyValidity.validity); } else { return null; } } else { return null; } } private void addSelfAsParent(PipelineContext context) { Stack<ProcessorImpl> parents = (Stack<ProcessorImpl>) context.getAttribute(PipelineContext.PARENT_PROCESSORS); if (parents == null) { parents = new Stack<ProcessorImpl>(); context.setAttribute(PipelineContext.PARENT_PROCESSORS, parents); } parents.push(this); } private void removeSelfAsParent(PipelineContext context) { Stack parents = (Stack) context.getAttribute(PipelineContext.PARENT_PROCESSORS); if (parents.peek() != this) throw new ValidationException("Current processor should be on top of the stack", getLocationData()); parents.pop(); } /** * For use in processor that contain other processors. * Consider the current processor as the parent of the processors on which * we call read/start. */ protected void executeChildren(PipelineContext context, Runnable runnable) { addSelfAsParent(context); try { runnable.run(); } finally { removeSelfAsParent(context); } } /** * For use in processor that contain other processors. * Consider the current processor as a child or at the same level of the * processors on which we call read/start. */ protected static void executeParents(PipelineContext context, Runnable runnable) { final Stack<ProcessorImpl> parents = (Stack<ProcessorImpl>) context.getAttribute(PipelineContext.PARENT_PROCESSORS); final ProcessorImpl thisPipelineProcessor = parents.peek(); thisPipelineProcessor.removeSelfAsParent(context); try { runnable.run(); } finally { thisPipelineProcessor.addSelfAsParent(context); } } protected static Object getParentState(final PipelineContext context) { final Stack<ProcessorImpl> parents = (Stack<ProcessorImpl>) context.getAttribute(PipelineContext.PARENT_PROCESSORS); final ProcessorImpl parent = parents.peek(); final Object[] result = new Object[1]; executeParents(context, new Runnable() { public void run() { result[0] = parent.getState(context); } }); return result[0]; } /** * This method is used to retrieve the state information set with setState(). * * This method may be called from start() and ProcessorOutput.readImpl(). * * @param context current PipelineContext object * @return state object set by the caller of setState() */ public Object getState(PipelineContext context) { final Object state = context.getAttribute(getProcessorKey(context)); if (state == null) { throw new OXFException("No state in context"); } return state; } /** * This method is used by processor implementations to store state information tied to the * current execution of the current processor, across processor initialization as well as reads * of all the processor's outputs. * * This method should be called from the reset() method. * * @param context current PipelineContext object * @param state user-defined object containing state information */ protected void setState(PipelineContext context, Object state) { context.setAttribute(getProcessorKey(context), state); } protected boolean hasState(PipelineContext context) { return context.getAttribute(getProcessorKey(context)) != null; } /** * Returns a key that should be used to store the state of the processor in the context. * * This method must be called in ProcessorOutput.readImpl() or start() of the processors before read/start is * called on other processors. (The key returned by getProcessorKey can be used after read/start is called.) */ protected ProcessorKey getProcessorKey(PipelineContext context) { final Stack<ProcessorImpl> parents = (Stack<ProcessorImpl>) context.getAttribute(PipelineContext.PARENT_PROCESSORS); return new ProcessorKey(parents); } public class ProcessorKey { private int hash = 0; private List<ProcessorImpl> processors; public ProcessorKey(Stack<ProcessorImpl> parents) { processors = (parents == null ? new ArrayList<ProcessorImpl>() : new ArrayList<ProcessorImpl>(parents)); processors.add(ProcessorImpl.this); // NOTE: Use get() which appears to be faster (profiling) than using an iterator in such a bottleneck for (int i = 0; i < processors.size(); i++) { Object processor = processors.get(i); hash += processor.hashCode() * 31; } } public int hashCode() { return hash; } private List<ProcessorImpl> getProcessors() { return processors; } public boolean equals(Object other) { final List<ProcessorImpl> otherProcessors = ((ProcessorKey) other).getProcessors(); int processorsSize = processors.size(); if (processorsSize != otherProcessors.size()) return false; // NOTE: Use get() which appears to be faster (profiling) than using an iterator in such a bottleneck for (int i = 0; i < processorsSize; i++) { if (processors.get(i) != otherProcessors.get(i)) return false; } // Iterator j = ((ProcessorKey) other).getProcessors().iterator(); // for (Iterator i = processors.iterator(); i.hasNext();) { // if (!j.hasNext()) // return false; // if (i.next() != j.next()) // return false; return true; // return other instanceof ProcessorKey // ? CollectionUtils.isEqualCollection(getProcessors(), ((ProcessorKey) other).getProcessors()) // : false; } public String toString() { FastStringBuffer result = null; for (Processor processor: processors) { if (result == null) { result = new FastStringBuffer(hash + ": ["); } else { result.append(", "); } result.append(Integer.toString(processor.hashCode())); result.append(": "); result.append(processor.getClass().getName()); } result.append("]"); return result.toString(); } } public void start(PipelineContext pipelineContext) { throw new ValidationException("Start not supported; processor implemented by '" + getClass().getName() + "'", locationData); } public void reset(PipelineContext pipelineContext) { // nop } /** * Utility methods to remove an item from a map of lists. */ private void deleteFromListMap(Map map, Object toRemove) { for (Iterator i = map.keySet().iterator(); i.hasNext();) { List list = (List) map.get(i.next()); for (Iterator j = list.iterator(); j.hasNext();) { Object current = j.next(); if (current == toRemove) { j.remove(); } } if (list.size() == 0) { i.remove(); } } } /** * Check if the given URI is referring to a processor input. */ public static boolean isProcessorInputScheme(String uri) { // NOTE: The check on the hash is for backward compatibility return uri.startsWith(" || (uri.startsWith(PROCESSOR_INPUT_SCHEME) && !uri.startsWith(PROCESSOR_INPUT_SCHEME + "/")) || (uri.startsWith(PROCESSOR_INPUT_SCHEME_OLD) && !uri.startsWith(PROCESSOR_INPUT_SCHEME_OLD + "/")); } /** * Return the input name if the URI is referring to a processor input, null otherwise. */ public static String getProcessorInputSchemeInputName(String uri) { if (uri.startsWith(" // NOTE: The check on the hash is for backward compatibility return uri.substring(1); } else if (uri.startsWith(PROCESSOR_INPUT_SCHEME) && !uri.startsWith(PROCESSOR_INPUT_SCHEME + "/")) { return uri.substring(PROCESSOR_INPUT_SCHEME.length()); } else if (uri.startsWith(PROCESSOR_INPUT_SCHEME_OLD) && !uri.startsWith(PROCESSOR_INPUT_SCHEME_OLD + "/")) { return uri.substring(PROCESSOR_INPUT_SCHEME_OLD.length()); } else { return null; } } /** * Basic implementation of ProcessorInput. */ public static class ProcessorInputImpl implements ProcessorInput { private ProcessorOutput output; private String id; private Class clazz; private String name; private String schema; private String debugMessage; private LocationData locationData; private String systemId; private BreakpointKey breakpointKey; public ProcessorInputImpl(Class clazz, String name) { this.clazz = clazz; this.name = name; } public ProcessorOutput getOutput() { return output; } public void setOutput(ProcessorOutput output) { this.output = output; } public Class getProcessorClass() { return clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getDebugMessage() { return debugMessage; } public void setLocationData(LocationData locationData) { this.locationData = locationData; } public LocationData getLocationData() { return locationData; } public void setDebug(String debugMessage) { this.debugMessage = debugMessage; } public String getSystemId() { return systemId; } public void setSystemId(String systemId) { this.systemId = systemId; } public void setBreakpointKey(BreakpointKey breakpointKey) { this.breakpointKey = breakpointKey; } } /** * Basic implementation of ProcessorOutput. */ public abstract static class ProcessorOutputImpl implements ProcessorOutput, Cacheable { private ProcessorInput input; private String id; private Class clazz; private String name; private String schema; private String debugMessage; private LocationData locationData; private BreakpointKey breakpointKey; public ProcessorOutputImpl(Class clazz, String name) { this.clazz = clazz; this.name = name; } public void setInput(ProcessorInput input) { this.input = input; } public ProcessorInput getInput() { return input; } public Class getProcessorClass() { return clazz; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public String getDebugMessage() { return debugMessage; } public LocationData getLocationData() { return locationData; } public void setDebug(String debugMessage) { this.debugMessage = debugMessage; } public void setLocationData(LocationData locationData) { this.locationData = locationData; } public void setBreakpointKey(BreakpointKey breakpointKey) { this.breakpointKey = breakpointKey; } protected abstract void readImpl(PipelineContext pipelineContext, ContentHandler contentHandler); protected OutputCacheKey getKeyImpl(PipelineContext pipelineContext) { return null; } protected Object getValidityImpl(PipelineContext pipelineContext) { return null; } /** * All the methods implemented here should never be called. */ private abstract class ProcessorFilter implements ProcessorOutput, Cacheable { public void setInput(ProcessorInput processorInput) { } public ProcessorInput getInput() { return null; } public void setSchema(String schema) { } public String getSchema() { return null; } public Class getProcessorClass() { return null; } public String getId() { return null; } public String getName() { return null; } public void setDebug(String debugMessage) { } public String getDebugMessage() { return null; } public void setLocationData(LocationData locationData) { } public LocationData getLocationData() { return null; } public void setBreakpointKey(BreakpointKey breakpointKey) { } public void read(PipelineContext context, ContentHandler ch) { throw new OXFException("This method should never be called!!!"); } } /** * Constructor takes: (1) the input and output of a processor and (2) a * "previousOutput". It connects the input to the previousOutput and * when read, reads the output. * * Semantic: creates an output that is just like previousOutput on which * a processor is applies. */ private class ConcreteProcessorFilter extends ProcessorFilter { private ProcessorOutput processorOutput; private ProcessorOutput previousProcessorOutput; private class ForwarderProcessorOutput extends ProcessorFilter { public void read(PipelineContext context, ContentHandler contentHandler) { previousProcessorOutput.read(context, contentHandler); } public OutputCacheKey getKey(PipelineContext context) { return previousProcessorOutput instanceof Cacheable ? ((Cacheable) previousProcessorOutput).getKey(context) : null; } public Object getValidity(PipelineContext context) { return previousProcessorOutput instanceof Cacheable ? ((Cacheable) previousProcessorOutput).getValidity(context) : null; } } public ConcreteProcessorFilter(ProcessorInput processorInput, ProcessorOutput processorOutput, final ProcessorOutput previousOutput) { this.processorOutput = processorOutput; this.previousProcessorOutput = previousOutput; processorInput.setOutput(new ForwarderProcessorOutput()); } public void read(PipelineContext context, ContentHandler contentHandler) { processorOutput.read(context, contentHandler); } public OutputCacheKey getKey(PipelineContext context) { return processorOutput instanceof Cacheable ? ((Cacheable) processorOutput).getKey(context) : null; } public Object getValidity(PipelineContext context) { return processorOutput instanceof Cacheable ? ((Cacheable) processorOutput).getValidity(context) : null; } } private ProcessorFilter createFilter() { // Get inspector instance // Final filter (i.e. at the top, executed last) ProcessorFilter filter = new ProcessorFilter() { public void read(PipelineContext context, ContentHandler contentHandler) { // Read the current processor output readImpl(context, contentHandler); } public OutputCacheKey getKey(PipelineContext context) { return getKeyImpl(context); } public Object getValidity(PipelineContext context) { return getValidityImpl(context); } }; // Handle debug if (getDebugMessage() != null || (getInput() != null && getInput().getDebugMessage() != null)) { ProcessorFactory debugProcessorFactory = ProcessorFactoryRegistry.lookup(XMLConstants.DEBUG_PROCESSOR_QNAME); if (debugProcessorFactory == null) throw new OXFException("Cannot find debug processor factory for QName: " + XMLConstants.DEBUG_PROCESSOR_QNAME); for (int i = 0; i < 2; i++) { String debugMessage = i == 0 ? getDebugMessage() : getInput() == null ? null : getInput().getDebugMessage(); LocationData debugLocationData = i == 0 ? getLocationData() : getInput() == null ? null : getInput().getLocationData(); if (debugMessage != null) { Processor debugProcessor = debugProcessorFactory.createInstance(); debugProcessor.createInput(INPUT_DATA); debugProcessor.createOutput(OUTPUT_DATA); // Create config document for Debug processor final org.dom4j.Document debugConfigDocument; { debugConfigDocument = new NonLazyUserDataDocument(); Element configElement = debugConfigDocument.addElement("config"); configElement.addElement("message").addText(debugMessage); if (debugLocationData != null) { Element systemIdElement = configElement.addElement("system-id"); if (debugLocationData.getSystemID() != null) systemIdElement.addText(debugLocationData.getSystemID()); configElement.addElement("line").addText(Integer.toString(debugLocationData.getLine())); configElement.addElement("column").addText(Integer.toString(debugLocationData.getCol())); } } final DOMGenerator dg = new DOMGenerator ( debugConfigDocument, "debug filter" , DOMGenerator.ZeroValidity, DOMGenerator.DefaultContext ); PipelineUtils.connect( dg, "data", debugProcessor, "config"); final ProcessorOutput dbgOut = debugProcessor.getOutputByName( OUTPUT_DATA ); final ProcessorInput dbgIn = debugProcessor.getInputByName( INPUT_DATA ); filter = new ConcreteProcessorFilter( dbgIn, dbgOut, filter ); } } } // The PropertySet can be null during properties initialization. This should be one of the // rare places where this should be tested on. PropertySet propertySet = Properties.instance().getPropertySet(); // Create and hook-up output validation processor if needed Boolean isOutputValidation = (propertySet == null) ? null : propertySet.getBoolean(USER_VALIDATION_FLAG, true); if (isOutputValidation != null && isOutputValidation.booleanValue() && getSchema() != null) { Processor outputValidator = new MSVValidationProcessor(getSchema()); // Create data input and output ProcessorInput input = outputValidator.createInput(INPUT_DATA); ProcessorOutput output = outputValidator.createOutput(OUTPUT_DATA); // Create and connect config input Processor resourceGenerator = PipelineUtils.createURLGenerator(getSchema()); PipelineUtils.connect(resourceGenerator, OUTPUT_DATA, outputValidator, MSVValidationProcessor.INPUT_SCHEMA); PipelineUtils.connect(MSVValidationProcessor.NO_DECORATION_CONFIG, OUTPUT_DATA, outputValidator, INPUT_CONFIG); filter = new ConcreteProcessorFilter(input, output, filter); } // Hook-up input validation processor if needed Boolean isInputValidation = isOutputValidation; if (isInputValidation != null && isInputValidation.booleanValue() && getInput() != null && getInput().getSchema() != null) { Processor inputValidator = new MSVValidationProcessor(getInput().getSchema()); // Create data input and output ProcessorInput input = inputValidator.createInput(INPUT_DATA); ProcessorOutput output = inputValidator.createOutput(OUTPUT_DATA); // Create and connect config input Processor resourceGenerator = PipelineUtils.createURLGenerator(getInput().getSchema()); PipelineUtils.connect(resourceGenerator, OUTPUT_DATA, inputValidator, MSVValidationProcessor.INPUT_SCHEMA); PipelineUtils.connect(MSVValidationProcessor.NO_DECORATION_CONFIG, OUTPUT_DATA, inputValidator, INPUT_CONFIG); filter = new ConcreteProcessorFilter(input, output, filter); } // Perform basic inspection of SAX events Boolean isSAXInspection = (propertySet == null) ? null : propertySet.getBoolean(SAX_INSPECTION_FLAG, false); if (isSAXInspection != null && isSAXInspection.booleanValue()) { final ProcessorFilter previousFilter = filter; filter = new ProcessorFilter() { public void read(PipelineContext context, ContentHandler contentHandler) { InspectingContentHandler inspectingContentHandler = new InspectingContentHandler(contentHandler); previousFilter.read(context, inspectingContentHandler); } public OutputCacheKey getKey(PipelineContext context) { return previousFilter.getKey(context); } public Object getValidity(PipelineContext context) { return previousFilter.getValidity(context); } }; } // Hookup inspector // if (useInspector) { // InspectorProcessor inspectorProcessor = new InspectorProcessor(); // inspectorProcessor.createInput(INPUT_DATA); // inspectorProcessor.createOutput(OUTPUT_DATA); // inspectorProcessor.setJndiName("inspector"); // inspectorProcessor.setProcessorInput(_input); // inspectorProcessor.setProcessorOutput(_output); // filter = new ConcreteProcessorFilter(inspectorProcessor.getInputByName(INPUT_DATA), // inspectorProcessor.getOutputByName(OUTPUT_DATA), // filter); // Hookup profiler // if (useProfiler) { // ProfilerProcessor profilerProcessor = new ProfilerProcessor(); // profilerProcessor.createInput(INPUT_DATA); // profilerProcessor.createOutput(OUTPUT_DATA); // profilerProcessor.setJndiName("profiler"); // profilerProcessor.setProcessorInput(_input); // profilerProcessor.setProcessorOutput(_output); // filter = new ConcreteProcessorFilter(profilerProcessor.getInputByName(INPUT_DATA), // profilerProcessor.getOutputByName(OUTPUT_DATA), // filter); // Handle breakpoints // if (get) { // Disable inspector for the filter chain. Its state will be restored at the end // of the chain before calling readImp(). // if (useInspector) { // inspectorRun.setEnabled(false); return filter; } /** * NOTE: We should never use processor instance variables. Here, the creation may not be thread safe in that * the filter may be initialized several times. This should not be a real problem, and the execution should not * be problematic either. It may be safer to synchronize getFilter(). */ ProcessorFilter filter = null; private ProcessorFilter getFilter() { if (filter == null) filter = createFilter(); return filter; } public final void read(PipelineContext context, ContentHandler contentHandler) { final Trace trc = context.getTrace(); final TraceInfo tinf; if (trc == null) { tinf = null; } else { final String sysID; final int line; if (breakpointKey == null) { final Class cls = getClass(); sysID = cls.getName() + " " + this + " " + getName() + " " + getId(); line = -1; } else { sysID = breakpointKey.getSystemId(); line = breakpointKey.getLine(); } tinf = new TraceInfo(sysID, line); trc.add(tinf); } try { getFilter().read(context, contentHandler); } catch (AbstractMethodError e) { logger.error(e); } catch (Exception e) { throw ValidationException.wrapException(e, getLocationData()); } finally { if (tinf != null) tinf.end = System.currentTimeMillis(); } } public final OutputCacheKey getKey(PipelineContext context) { return getFilter().getKey(context); // if (result == null) { // System.out.print("."); // return result; } public final Object getValidity(PipelineContext context) { return getFilter().getValidity(context); } public final KeyValidity getKeyValidityImpl(PipelineContext context) { final OutputCacheKey outputCacheKey = getKeyImpl(context); if (outputCacheKey == null) return null; final Object outputCacheValidity = getValidityImpl(context); if (outputCacheValidity == null) return null; return new KeyValidity(outputCacheKey, outputCacheValidity); } } protected static OutputCacheKey getInputKey(PipelineContext context, ProcessorInput input) { final ProcessorOutput output = input.getOutput(); return (output instanceof Cacheable) ? ((Cacheable) output).getKey(context) : null; } protected static Object getInputValidity(PipelineContext context, ProcessorInput input) { final ProcessorOutput output = input.getOutput(); return (output instanceof Cacheable) ? ((Cacheable) output).getValidity(context) : null; } /** * Subclasses can use this utility method when implementing the getKey * and getValidity methods to make sure that they don't read the whole * config (if we don't already have it) just to return a key/validity. */ protected boolean isInputInCache(PipelineContext context, ProcessorInput input) { final KeyValidity keyValidity = getInputKeyValidity(context, input); if (keyValidity == null) return false; return ObjectCache.instance().findValid(context, keyValidity.key, keyValidity.validity) != null; } protected boolean isInputInCache(PipelineContext context, String inputName) { return isInputInCache(context, getInputByName(inputName)); } protected boolean isInputInCache(PipelineContext context, KeyValidity keyValidity) { return ObjectCache.instance().findValid(context, keyValidity.key, keyValidity.validity) != null; } /** * Subclasses can use this utility method to obtain the key and validity associated with an * input when implementing the getKey and getValidity methods. * * @return a KeyValidity object containing non-null key and validity, or null */ protected KeyValidity getInputKeyValidity(PipelineContext context, ProcessorInput input) { final OutputCacheKey outputCacheKey = getInputKey(context, input); if (outputCacheKey == null) return null; final InputCacheKey inputCacheKey = new InputCacheKey(input, outputCacheKey); final Object inputValidity = getInputValidity(context, input); if (inputValidity == null) return null; return new KeyValidity(inputCacheKey, inputValidity); } protected KeyValidity getInputKeyValidity(PipelineContext context, String inputName) { return getInputKeyValidity(context, getInputByName(inputName)); } /** * Implementation of a caching transformer output that assumes that an output simply depends on * all the inputs plus optional local information. * * It is possible to implement local key and validity information as well, that represent data * not coming from an XML input. If any input is connected to an output that is not cacheable, * a null key is returned. * * Use DigestTransformerOutputImpl whenever possible. */ public abstract class CacheableTransformerOutputImpl extends ProcessorOutputImpl { public CacheableTransformerOutputImpl(Class clazz, String name) { super(clazz, name); } /** * Processor outputs that use the local key/validity feature must * override this method and return true. */ protected boolean supportsLocalKeyValidity() { return false; } protected CacheKey getLocalKey(PipelineContext pipelineContext) { throw new UnsupportedOperationException(); } protected Object getLocalValidity(PipelineContext pipelineContext) { throw new UnsupportedOperationException(); } public OutputCacheKey getKeyImpl(PipelineContext pipelineContext) { // NOTE: This implementation assumes that there is only one input with a given name // Create input information final Set entrySet = getConnectedInputs().entrySet(); final int keyCount = entrySet.size() + (supportsLocalKeyValidity() ? 1 : 0); final CacheKey[] outputKeys = new CacheKey[keyCount]; int keyIndex = 0; for (Iterator i = entrySet.iterator(); i.hasNext();) { final Map.Entry currentEntry = (Map.Entry) i.next(); final List currentInputs = (List) currentEntry.getValue(); // int inputIndex = 0; // for (Iterator j = currentInputs.iterator(); j.hasNext(); inputIndex++) { for (Iterator j = currentInputs.iterator(); j.hasNext();) { // if (inputIndex > 0) // logger.info("CacheableTransformerOutputImpl: processor " + getProcessorClass().getName() + " has more than 1 input called " + getName()); final OutputCacheKey outputKey = getInputKey(pipelineContext, (ProcessorInput) j.next()); if (outputKey == null) return null; outputKeys[keyIndex++] = outputKey; } } // Add local key if needed if (supportsLocalKeyValidity()) { CacheKey localKey = getLocalKey(pipelineContext); if (localKey == null) return null; outputKeys[keyIndex++] = localKey; } // Concatenate current processor info and input info final Class processorClass = getProcessorClass(); final String outputName = getName(); return new CompoundOutputCacheKey(processorClass, outputName, outputKeys); } public Object getValidityImpl(PipelineContext pipelineContext) { final List<Object> validityObjects = new ArrayList<Object>(); final Map inputsMap = getConnectedInputs(); for (Iterator i = inputsMap.keySet().iterator(); i.hasNext();) { final List currentInputs = (List) inputsMap.get(i.next()); for (Iterator j = currentInputs.iterator(); j.hasNext();) { final Object validity = getInputValidity(pipelineContext, (ProcessorInput) j.next()); if (validity == null) return null; validityObjects.add(validity); } } // Add local validity if needed if (supportsLocalKeyValidity()) { final Object localValidity = getLocalValidity(pipelineContext); if (localValidity == null) return null; validityObjects.add(localValidity); } return validityObjects; } } /** * Implementation of a caching transformer output that assumes that an output simply depends on * all the inputs plus optional local information that can be digested. */ public abstract class DigestTransformerOutputImpl extends CacheableTransformerOutputImpl { private final Long DEFAULT_VALIDITY = new Long(0); public DigestTransformerOutputImpl(Class clazz, String name) { super(clazz, name); } protected final boolean supportsLocalKeyValidity() { return true; } protected CacheKey getLocalKey(PipelineContext pipelineContext) { for (Iterator i = inputMap.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); if (!isInputInCache(pipelineContext, key))// NOTE: We don't really support multiple inputs with the same name. return null; } return getFilledOutState(pipelineContext).key; } protected final Object getLocalValidity(PipelineContext pipelineContext) { for (Iterator i = inputMap.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); if (!isInputInCache(pipelineContext, key))// NOTE: We don't really support multiple inputs with the same name. return null; } return getFilledOutState(pipelineContext).validity; } /** * Fill-out user data into the state, if needed. Return caching information. * * @param pipelineContext the current PipelineContext * @param digestState state set during processor start() or reset() * @return false if private information is known that requires disabling caching, true otherwise */ protected abstract boolean fillOutState(PipelineContext pipelineContext, DigestState digestState); /** * Compute a digest of the internal document on which the output depends. * * @param digestState state set during processor start() or reset() * @return the digest */ protected abstract byte[] computeDigest(PipelineContext pipelineContext, DigestState digestState); protected final DigestState getFilledOutState(PipelineContext pipelineContext) { // This is called from both readImpl and getLocalValidity. Based on the assumption that // a getKeyImpl will be followed soon by a readImpl if it fails, we compute key, // validity, and user-defined data. DigestState state = (DigestState) getState(pipelineContext); // Create request document boolean allowCaching = fillOutState(pipelineContext, state); // Compute key and validity if possible if ((state.validity == null || state.key == null) && allowCaching) { // Compute digest if (state.digest == null) { state.digest = computeDigest(pipelineContext, state); } // Compute local key if (state.key == null) { state.key = new InternalCacheKey(ProcessorImpl.this, "requestHash", new String(state.digest)); } // Compute local validity if (state.validity == null) { state.validity = DEFAULT_VALIDITY; // HACK so we don't recurse at the next line OutputCacheKey outputCacheKey = getKeyImpl(pipelineContext); if (outputCacheKey != null) { Cache cache = ObjectCache.instance(); DigestValidity digestValidity = (DigestValidity) cache.findValid(pipelineContext, outputCacheKey, DEFAULT_VALIDITY); if (digestValidity != null && Arrays.equals(state.digest, digestValidity.digest)) { state.validity = digestValidity.lastModified; } else { Long currentValidity = new Long(System.currentTimeMillis()); cache.add(pipelineContext, outputCacheKey, DEFAULT_VALIDITY, new DigestValidity(state.digest, currentValidity)); state.validity = currentValidity; } } else { state.validity = null; // HACK restore } } } return state; } } /** * Cache an object associated with a given processor output. * * @param pipelineContext current PipelineContext * @param processorOutput output to associate with * @param keyName key for the object to cache * @param creator creator for the object * @return created object if caching was possible, null otherwise */ protected Object getCacheOutputObject(PipelineContext pipelineContext, ProcessorOutputImpl processorOutput, String keyName, OutputObjectCreator creator) { final KeyValidity outputKeyValidity = processorOutput.getKeyValidityImpl(pipelineContext); if (outputKeyValidity != null) { // Output is cacheable // Get cache instance final Cache cache = ObjectCache.instance(); // Check in cache first final CacheKey internalCacheKey = new InternalCacheKey(this, "outputKey", keyName); final CacheKey compoundCacheKey = new CompoundOutputCacheKey(this.getClass(), processorOutput.getName(), new CacheKey[] { outputKeyValidity.key, internalCacheKey } ); final List<Object> compoundValidities = new ArrayList<Object>(); compoundValidities.add(outputKeyValidity.validity); compoundValidities.add(new Long(0)); final Object cachedObject = cache.findValid(pipelineContext, compoundCacheKey, compoundValidities); if (cachedObject != null) { // Found it creator.foundInCache(); return cachedObject; } else { // Not found, call method to create object final Object readObject = creator.create(pipelineContext, processorOutput); cache.add(pipelineContext, compoundCacheKey, compoundValidities, readObject); return readObject; } } else { creator.unableToCache(); return null; } } /** * Get a cached object associated with a given processor output. * * @param pipelineContext current PipelineContext * @param processorOutput output to associate with * @param keyName key for the object to cache * @return cached object if object found, null otherwise */ protected Object getOutputObject(PipelineContext pipelineContext, ProcessorOutputImpl processorOutput, String keyName) { final KeyValidity outputKeyValidityImpl = processorOutput.getKeyValidityImpl(pipelineContext); if (outputKeyValidityImpl != null) { // Output is cacheable // Get cache instance final Cache cache = ObjectCache.instance(); // Check in cache first final CacheKey internalCacheKey = new InternalCacheKey(this, "outputKey", keyName); final CacheKey compoundCacheKey = new CompoundOutputCacheKey(this.getClass(), processorOutput.getName(), new CacheKey[] { outputKeyValidityImpl.key, internalCacheKey } ); final List<Object> compoundValidities = new ArrayList<Object>(); compoundValidities.add(outputKeyValidityImpl.validity); compoundValidities.add(new Long(0)); return cache.findValid(pipelineContext, compoundCacheKey, compoundValidities); } else { return null; } } protected Object getOutputObject(PipelineContext pipelineContext, ProcessorOutputImpl processorOutput, String keyName, KeyValidity outputKeyValidityImpl) { if (outputKeyValidityImpl != null) { // Output is cacheable // Get cache instance final Cache cache = ObjectCache.instance(); // Check in cache first final CacheKey internalCacheKey = new InternalCacheKey(this, "outputKey", keyName); final CacheKey compoundCacheKey = new CompoundOutputCacheKey(this.getClass(), processorOutput.getName(), new CacheKey[] { outputKeyValidityImpl.key, internalCacheKey } ); final List<Object> compoundValidities = new ArrayList<Object>(); compoundValidities.add(outputKeyValidityImpl.validity); compoundValidities.add(new Long(0)); return cache.findValid(pipelineContext, compoundCacheKey, compoundValidities); } else { return null; } } /** * Find the last modified timestamp of a particular input. * * @param pipelineContext pipeline context * @param input input to check * @param inputMustBeInCache if true, also return 0 if the input is not currently in cache * @return timestamp, <= 0 if unknown */ protected long findInputLastModified(PipelineContext pipelineContext, ProcessorInput input, boolean inputMustBeInCache) { final long lastModified; { final KeyValidity keyValidity = getInputKeyValidity(pipelineContext, input); if (keyValidity == null || inputMustBeInCache && !isInputInCache(pipelineContext, keyValidity)) { lastModified = 0; } else { lastModified = (keyValidity.validity != null) ? findLastModified(keyValidity.validity) : 0; } } if (logger.isDebugEnabled()) logger.debug("Last modified: " + lastModified); return lastModified; } /** * Recursively find the last modified timestamp of a validity object. Supported types are Long and List<Long>. The * latest timestamp is returned. * * @param validity validity object * @return timestamp, <= 0 if unknown */ protected static long findLastModified(Object validity) { if (validity instanceof Long) { return ((Long) validity).longValue(); } else if (validity instanceof List) { final List list = (List) validity; long latest = 0; for (Iterator i = list.iterator(); i.hasNext();) { final Object o = i.next(); latest = Math.max(latest, findLastModified(o)); } return latest; } else { return 0; } } private static class DigestValidity { public DigestValidity(byte[] digest, Long lastModified) { this.digest = digest; this.lastModified = lastModified; } public byte[] digest; public Long lastModified; } protected static class DigestState { public byte[] digest; public CacheKey key; public Object validity; } public static class KeyValidity { public KeyValidity(CacheKey key, Object validity) { this.key = key; this.validity = validity; } public CacheKey key; public Object validity; } }
package com.izforge.izpack.panels; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import com.izforge.izpack.*; import com.izforge.izpack.gui.*; import com.izforge.izpack.installer.*; import com.izforge.izpack.util.*; import com.izforge.izpack.util.os.*; import net.n3.nanoxml.*; /** * This class implements a panel for the creation of shortcuts. * The panel prompts the user to select a program group for shortcuts, accept * the creation of desktop shortcuts and actually creates the shortcuts. * * <h4>Important</h4> * It is neccesary that the installation has been completed before this panel * is called. To successfully create shortcuts this panel needs to have the * following in place: <br><br> * <ul> * <li>the launcher files that the shortcuts point to must exist * <li>it must be known which packs are installed * <li>where the launcher for the uninstaller is located * </ul> * It is ok to present other panels after this one, as long as these * conditions are met. * * @see com.izforge.izpack.util.os.ShellLink * @see com.izforge.izpack.util.os.Alias * * @version 0.0.1 / 2/26/02 * @author Elmar Grom */ // !!! To Do ! // - see if I can't get multiple instances of the shortcut to work // - need a clean way to get pack name public class ShortcutPanel extends IzPanel implements ActionListener, ListSelectionListener { // Constant Definitions private static final String LOCATION_APPLICATIONS = "applications"; private static final String LOCATION_START_MENU = "startMenu"; private static final String SEPARATOR_LINE = " private static final String TEXT_FILE_NAME = "Shortcuts.txt"; /** The name of the XML file that specifies the shortcuts */ private static final String SPEC_FILE_NAME = "shortcutSpec.xml"; // spec file section keys private static final String SPEC_KEY_NOT_SUPPORTED = "notSupported"; private static final String SPEC_KEY_PROGRAM_GROUP = "programGroup"; private static final String SPEC_KEY_SHORTCUT = "shortcut"; private static final String SPEC_KEY_PACKS = "createForPack"; // spec file key attributes private static final String SPEC_ATTRIBUTE_DEFAULT_GROUP = "defaultName"; private static final String SPEC_ATTRIBUTE_LOCATION = "location"; private static final String SPEC_ATTRIBUTE_NAME = "name"; private static final String SPEC_ATTRIBUTE_SUBGROUP = "subgroup"; private static final String SPEC_ATTRIBUTE_DESCRIPTION = "description"; private static final String SPEC_ATTRIBUTE_TARGET = "target"; private static final String SPEC_ATTRIBUTE_COMMAND = "commandLine"; private static final String SPEC_ATTRIBUTE_ICON = "iconFile"; private static final String SPEC_ATTRIBUTE_ICON_INDEX = "iconIndex"; private static final String SPEC_ATTRIBUTE_WORKING_DIR = "workingDirectory"; private static final String SPEC_ATTRIBUTE_INITIAL_STATE = "initialState"; private static final String SPEC_ATTRIBUTE_DESKTOP = "desktop"; private static final String SPEC_ATTRIBUTE_APPLICATIONS = "applications"; private static final String SPEC_ATTRIBUTE_START_MENU = "startMenu"; private static final String SPEC_ATTRIBUTE_STARTUP = "startup"; private static final String SPEC_ATTRIBUTE_PROGRAM_GROUP = "programGroup"; // spec file attribute values private static final String SPEC_VALUE_APPLICATIONS = "applications"; private static final String SPEC_VALUE_START_MENU = "startMenu"; private static final String SPEC_VALUE_NO_SHOW = "noShow"; private static final String SPEC_VALUE_NORMAL = "normal"; private static final String SPEC_VALUE_MAXIMIZED = "maximized"; private static final String SPEC_VALUE_MINIMIZED = "minimized"; // automatic script section keys private static final String AUTO_KEY_PROGRAM_GROUP = "programGroup"; private static final String AUTO_KEY_SHORTCUT = "shortcut"; // automatic script keys attributes private static final String AUTO_ATTRIBUTE_NAME = "name"; private static final String AUTO_ATTRIBUTE_GROUP = "group"; private static final String AUTO_ATTRIBUTE_TYPE = "type"; private static final String AUTO_ATTRIBUTE_COMMAND = "commandLine"; private static final String AUTO_ATTRIBUTE_DESCRIPTION = "description"; private static final String AUTO_ATTRIBUTE_ICON = "icon"; private static final String AUTO_ATTRIBUTE_ICON_INDEX = "iconIndex"; private static final String AUTO_ATTRIBUTE_INITIAL_STATE = "initialState"; private static final String AUTO_ATTRIBUTE_TARGET = "target"; private static final String AUTO_ATTRIBUTE_WORKING_DIR = "workingDirectory"; // Variable Declarations /** UI element to label the list of existing program groups */ private JLabel listLabel; /** UI element to present the list of existing program groups for selection */ private JList groupList; /** UI element for listing the intended shortcut targets */ private JList targetList; /** UI element to present the default name for the program group and to support editing of this name. */ private JTextField programGroup; /** UI element to allow the user to revert to the default name of the program group */ private HighlightJButton defaultButton; /** UI element to start the process of creating shortcuts */ private HighlightJButton createButton; /** UI element to allow the user to save a text file with the shortcut information */ private HighlightJButton saveButton; /** UI element to allow the user to decide if shortcuts should be placed on the desktop or not. */ private JCheckBox allowDesktopShortcut; /** UI element instruct this panel to create shortcuts for the current user only */ private JRadioButton currentUser; /** UI element instruct this panel to create shortcuts for all users */ private JRadioButton allUsers; /** The layout for this panel */ private GridBagLayout layout; /** The contraints object to use whan creating the layout */ private GridBagConstraints constraints; /** The default name to use for the program group. This comes from the XML specification. */ private String suggestedProgramGroup; /** The name chosen by the user for the program group, */ private String groupName; /** The location for placign the program group. This is the same as the location (type) of a shortcut, only that it applies to the program group. Note that there are only two locations that make sense as location for a program group: <br> <ul> <li>applications <li>start manu </ul> */ private int groupLocation; /** The parsed result from reading the XML specification from the file */ private XMLElement spec; /** Set to <code>true</code> by <code>analyzeShortcutSpec()</code> if there are any desktop shortcuts to create.*/ private boolean hasDesktopShortcuts = false; /** the one shortcut instance for reuse in many locations */ private Shortcut shortcut; /** A list of <code>ShortcutData</code> objects. Each object is the complete specification for one shortcut that must be created. */ private Vector shortcuts = new Vector (); /** Holds a list of all the shortcut files that have been created. <b>Note:</b> this variable contains valid data only after <code>createShortcuts()</code> has been called. This list is created so that the files can be added to the uninstaller. */ private Vector files = new Vector (); /** If <code>true</code> it indicates that there are shortcuts to create. The value is set by <code>analyzeShortcutSpec()</code> */ private boolean shortcutsToCreate = false; /** If <code>true</code> it indicates that the spec file is existing and could be read. */ private boolean haveShortcutSpec = false; /** This is set to true if the shortcut spec instructs to simulate running on an operating system that is not supported. */ private boolean simulteNotSupported = false; /** Specifies wether the shortcuts creation has been done or not. */ private boolean shortcutsCreationDone = false; /** * Constructor. * * @param parent reference to the application frame * @param installData shared information about the installation */ public ShortcutPanel (InstallerFrame parent, InstallData installData) { super (parent, installData); // read the XML file try { readShortcutSpec (); } catch (Throwable exception) { System.out.println ("could not read shortcut spec!"); exception.printStackTrace (); } layout = new GridBagLayout (); constraints = new GridBagConstraints (); setLayout(layout); // Create the UI elements try { shortcut = (Shortcut)(TargetFactory.getInstance ().makeObject ("com.izforge.izpack.util.os.Shortcut")); shortcut.initialize (shortcut.APPLICATIONS, "-"); } catch (Throwable exception) { System.out.println ("could not create shortcut instance"); exception.printStackTrace (); } } /** * This method represents the <code>ActionListener</code> interface, invoked * when an action occurs. * * @param event the action event. */ public void actionPerformed (ActionEvent event) { Object eventSource = event.getSource (); // create shortcut for the current user was selected // refresh the list of program groups accordingly and // reset the program group to the default setting. if (eventSource.equals (currentUser)) { groupList.setListData (shortcut.getProgramGroups (Shortcut.CURRENT_USER)); programGroup.setText (suggestedProgramGroup); shortcut.setUserType (Shortcut.CURRENT_USER); } // create shortcut for all users was selected // refresh the list of program groups accordingly and // reset the program group to the default setting. else if (eventSource.equals (allUsers)) { groupList.setListData (shortcut.getProgramGroups (Shortcut.ALL_USERS)); programGroup.setText (suggestedProgramGroup); shortcut.setUserType (Shortcut.ALL_USERS); } // The create button was pressed. // go ahead and create the shortcut(s) else if (eventSource.equals (createButton)) { try { groupName = programGroup.getText (); } catch (Throwable exception) { groupName = ""; } createShortcuts (); // add files and directories to the uninstaller addToUninstaller (); // Disables the createButton createButton.setEnabled(false); // when finished unlock the next button and lock // the previous button //parent.unlockNextButton (); parent.lockPrevButton (); } // The reset button was pressed. // - clear the selection in the list box, because the // selection is no longer valid // - refill the program group edit control with the // suggested program group name else if (eventSource.equals (defaultButton)) { groupList.getSelectionModel ().clearSelection (); programGroup.setText (suggestedProgramGroup); } // the save button was pressed. This is a request to // save shortcut information to a text file. else if (eventSource.equals (saveButton)) { saveToFile (); // add the file to the uninstaller addToUninstaller (); } } public boolean isValidated () { return (true); } /** * Called when the panel is shown to the user. */ public void panelActivate () { analyzeShortcutSpec (); if (shortcutsToCreate) { if (shortcut.supported () && !simulteNotSupported) { //parent.lockNextButton (); buildUI (shortcut.getProgramGroups (ShellLink.CURRENT_USER), true); // always start out with the current user } else { buildAlternateUI (); parent.unlockNextButton (); parent.lockPrevButton (); } } else { parent.skipPanel (); } } /** * This method is called by the <code>groupList</code> when the user makes * a selection. It updates the content of the <code>programGroup</code> * with the result of the selection. * * @param event the list selection event */ public void valueChanged (ListSelectionEvent event) { if (programGroup == null) { return; } String value = ""; try { value = (String)groupList.getSelectedValue (); } catch (ClassCastException exception) {} if (value == null) { value = ""; } programGroup.setText (value); } /** * Reads the XML specification for the shortcuts to create. The result is * stored in spec. * * @exception Exception for any problems in reading the specification */ private void readShortcutSpec () throws Exception { // open an input stream InputStream input = null; try { input = parent.getResource (SPEC_FILE_NAME); } catch (Exception exception) { haveShortcutSpec = false; return; } if (input == null) { haveShortcutSpec = false; return; } // initialize the parser StdXMLParser parser = new StdXMLParser (); parser.setBuilder (new StdXMLBuilder ()); parser.setValidator (new NonValidator ()); parser.setReader (new StdXMLReader (input)); // get the data spec = (XMLElement) parser.parse (); // close the stream input.close (); haveShortcutSpec = true; } /** * This method analyzes the specifications for creating shortcuts. * */ private void analyzeShortcutSpec () { if (!haveShortcutSpec) { shortcutsToCreate = false; return; } // find out if we should simulate a not supported // scenario XMLElement support = spec.getFirstChildNamed (SPEC_KEY_NOT_SUPPORTED); if (support != null) { simulteNotSupported = true; } // find out in which program group the shortcuts should // be placed and where this program group should be // located XMLElement group = spec.getFirstChildNamed (SPEC_KEY_PROGRAM_GROUP); String location = null; hasDesktopShortcuts = false; if (group != null) { suggestedProgramGroup = group.getAttribute (SPEC_ATTRIBUTE_DEFAULT_GROUP, ""); location = group.getAttribute (SPEC_ATTRIBUTE_LOCATION, SPEC_VALUE_APPLICATIONS); } else { suggestedProgramGroup = ""; location = SPEC_VALUE_APPLICATIONS; } if (location.equals (SPEC_VALUE_APPLICATIONS)) { groupLocation = Shortcut.APPLICATIONS; } else if (location.equals (SPEC_VALUE_START_MENU)) { groupLocation = Shortcut.START_MENU; } // create a list of all shortcuts that need to be // created, containing all details about each shortcut VariableSubstitutor substitutor = new VariableSubstitutor (idata.getVariableValueMap ()); String temp; Vector shortcutSpecs = spec.getChildrenNamed (SPEC_KEY_SHORTCUT); XMLElement shortcutSpec; ShortcutData data; for (int i = 0; i < shortcutSpecs.size (); i++) { shortcutSpec = (XMLElement)shortcutSpecs.elementAt (i); data = new ShortcutData (); data.addToGroup = false; data.name = shortcutSpec.getAttribute (SPEC_ATTRIBUTE_NAME); data.subgroup = shortcutSpec.getAttribute (SPEC_ATTRIBUTE_SUBGROUP); data.description = shortcutSpec.getAttribute (SPEC_ATTRIBUTE_DESCRIPTION, ""); temp = fixSeparatorChar (shortcutSpec.getAttribute (SPEC_ATTRIBUTE_TARGET, "")); data.target = substitutor.substitute (temp, null); temp = shortcutSpec.getAttribute (SPEC_ATTRIBUTE_COMMAND, ""); data.commandLine = substitutor.substitute (temp, null); temp = fixSeparatorChar (shortcutSpec.getAttribute (SPEC_ATTRIBUTE_ICON, "")); data.iconFile = substitutor.substitute (temp, null); data.iconIndex = Integer.parseInt (shortcutSpec.getAttribute (SPEC_ATTRIBUTE_ICON_INDEX, "0")); temp = fixSeparatorChar (shortcutSpec.getAttribute (SPEC_ATTRIBUTE_WORKING_DIR, "")); data.workingDirectory = substitutor.substitute (temp, null); String initialState = shortcutSpec.getAttribute (SPEC_ATTRIBUTE_INITIAL_STATE, ""); if (initialState.equals (SPEC_VALUE_NO_SHOW)) { data.initialState = Shortcut.HIDE; } else if (initialState.equals (SPEC_VALUE_NORMAL)) { data.initialState = Shortcut.NORMAL; } else if (initialState.equals (SPEC_VALUE_MAXIMIZED)) { data.initialState = Shortcut.MAXIMIZED; } else if (initialState.equals (SPEC_VALUE_MINIMIZED)) { data.initialState = Shortcut.MINIMIZED; } else { data.initialState = Shortcut.NORMAL; } // if the minimal data requirements are met to create // the shortcut, create one entry each for each of // the requested types. // Eventually this will cause the creation of one // shortcut in each of the associated locations. // without a name we can not create a shortcut if (data.name == null) { continue; } // without a target we can not create a shortcut if (data.target == null) { continue; } // the shortcut is not actually required for any of the selected packs Vector forPacks = shortcutSpec.getChildrenNamed (SPEC_KEY_PACKS); if (!shortcutRequiredFor (forPacks)) { continue; } // This section is executed if we don't skip. // For each of the categories set the type and if // the link should be placed in the program group, // then clone the data set to obtain an independent // instance and add this to the list of shortcuts // to be created. In this way, we will set up an // identical copy for each of the locations at which // a shortcut should be placed. Therefore you must // not use 'else if' statements! { if (attributeIsTrue (shortcutSpec, SPEC_ATTRIBUTE_DESKTOP)) { hasDesktopShortcuts = true; data.type = Shortcut.DESKTOP; shortcuts.add (data.clone ()); } if (attributeIsTrue (shortcutSpec, SPEC_ATTRIBUTE_APPLICATIONS)) { data.type = Shortcut.APPLICATIONS; shortcuts.add (data.clone ()); } if (attributeIsTrue (shortcutSpec, SPEC_ATTRIBUTE_START_MENU)) { data.type = Shortcut.START_MENU; shortcuts.add (data.clone ()); } if (attributeIsTrue (shortcutSpec, SPEC_ATTRIBUTE_STARTUP)) { data.type = Shortcut.START_UP; shortcuts.add (data.clone ()); } if (attributeIsTrue (shortcutSpec, SPEC_ATTRIBUTE_PROGRAM_GROUP)) { data.addToGroup = true; data.type = Shortcut.APPLICATIONS; shortcuts.add (data.clone ()); } } } // signal if there are any shortcuts to create if (shortcuts.size () > 0) { shortcutsToCreate = true; } } /** * Creates all shortcuts based on the information in <code>shortcuts</code>. */ private void createShortcuts () { ShortcutData data; for (int i = 0; i < shortcuts.size (); i++) { data = (ShortcutData)shortcuts.elementAt (i); try { groupName = groupName + data.subgroup; shortcut.setLinkName (data.name); shortcut.setLinkType (data.type); shortcut.setArguments (data.commandLine); shortcut.setDescription (data.description); shortcut.setIconLocation (data.iconFile, data.iconIndex); shortcut.setShowCommand (data.initialState); shortcut.setTargetPath (data.target); shortcut.setWorkingDirectory (data.workingDirectory); if (data.addToGroup) { shortcut.setProgramGroup (groupName); } else { shortcut.setProgramGroup (""); } try { // save the shortcut only if it is either not on // the desktop or if it is on the desktop and // the user has signalled that it is ok to place // shortcuts on the desktop. if ( (data.type != Shortcut.DESKTOP) || ((data.type == Shortcut.DESKTOP) && allowDesktopShortcut.isSelected ()) ) { // save the shortcut shortcut.save (); // add the file and directory name to the file list String fileName = shortcut.getFileName (); String directoryName = shortcut.getDirectoryCreated (); files.add (fileName); if (!(directoryName == null)) { files.add (directoryName); } } } catch (Exception exception) { } } catch (Throwable exception) { continue; } } //parent.unlockNextButton(); shortcutsCreationDone = true; } /** * Verifies if the shortcut is required for any of the packs listed. The * shortcut is required for a pack in the list if that pack is actually * selected for installation. * <br><br> * <b>Note:</b><br> * If the list of selected packs is empty then <code>true</code> is always * returnd. The same is true if the <code>packs</code> list is empty. * * @param packs a <code>Vector</code> of <code>String</code>s. Each of * the strings denotes a pack for which the schortcut * should be created if the pack is actually installed. * * @return <code>true</code> if the shortcut is required for at least * on pack in the list, otherwise returns <code>false</code>. */ private boolean shortcutRequiredFor (Vector packs) { String selected; String required; if (packs.size () == 0) { return (true); } for (int i = 0; i < idata.selectedPacks.size (); i++) { selected = ((Pack)idata.selectedPacks.get (i)).name; for (int k = 0; k < packs.size (); k++) { required = (String)((XMLElement)packs.elementAt (k)).getAttribute (SPEC_ATTRIBUTE_NAME, ""); if (selected.equals (required)) { return (true); } } } return (false); } /** * Determines if the named attribute in true. True is represented by any of * the following strings and is not case sensitive. <br> * <ul> * <li>yes * <li>1 * <li>true * <li>on * </ul><br> * Every other string, including the empty string as well as the non-existence * of the attribute will cuase <code>false</code> to be returned. * * @param element the <code>XMLElement</code> to search for the attribute. * @param name the name of the attribute to test. * * @return <code>true</code> if the attribute value equals one of the * pre-defined strings, <code>false</code> otherwise. */ private boolean attributeIsTrue (XMLElement element, String name) { String value = element.getAttribute (name, "").toUpperCase (); if (value.equals ("YES")) { return (true); } else if (value.equals ("TRUE")) { return (true); } else if (value.equals ("ON")) { return (true); } else if (value.equals ("1")) { return (true); } return (false); } /** * Replaces any ocurrence of '/' or '\' in a path string with the correct * version for the operating system. * * @param path a system path * * @return a path string that uniformely uses the proper version of the * separator character. */ private String fixSeparatorChar (String path) { String newPath = path.replace ('/', File.separatorChar); newPath = newPath.replace ('\\', File.separatorChar); return (newPath); } /** * This method creates the UI for this panel. * * @param groups A <code>Vector</code> that contains * <code>Strings</code> with all the names of the * existing program groups. These will be placed * in the <code>groupList</code>. * @param currentUserList if <code>true</code> it indicates that the * list of groups is valid for the current user, * otherwise it is considered valid for all users. */ private void buildUI (Vector groups, boolean currentUserList) { layout = new GridBagLayout (); constraints = new GridBagConstraints (); setLayout(layout); // label a the top of the panel, that gives the // basic instructions listLabel = new JLabel (parent.langpack.getString ("ShortcutPanel.regular.list"), JLabel.LEADING); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets = new Insets (5, 5, 5, 5); constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.WEST; layout.addLayoutComponent (listLabel, constraints); add (listLabel); // list box to list all of the existing program groups // at the intended destination groupList = new JList (groups); groupList.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); groupList.getSelectionModel ().addListSelectionListener (this); JScrollPane scrollPane = new JScrollPane (groupList); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.fill = GridBagConstraints.BOTH; layout.addLayoutComponent (scrollPane, constraints); add (scrollPane); // radio buttons to select current user or all users. if (shortcut.multipleUsers ()) { JPanel usersPanel = new JPanel (new GridLayout (2, 1)); ButtonGroup usersGroup = new ButtonGroup (); currentUser = new JRadioButton (parent.langpack.getString ("ShortcutPanel.regular.currentUser"), currentUserList); currentUser.addActionListener (this); usersGroup.add (currentUser); usersPanel.add (currentUser); allUsers = new JRadioButton (parent.langpack.getString ("ShortcutPanel.regular.allUsers"), !currentUserList); allUsers.addActionListener (this); usersGroup.add (allUsers); usersPanel.add (allUsers); TitledBorder border = new TitledBorder (new EmptyBorder(2, 2, 2, 2), parent.langpack.getString ("ShortcutPanel.regular.userIntro")); usersPanel.setBorder (border); constraints.gridx = 1; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.fill = GridBagConstraints.NONE; layout.addLayoutComponent (usersPanel, constraints); add (usersPanel); } // edit box that contains the suggested program group // name, which can be modfied or substituted from the // list by the user programGroup = new JTextField (suggestedProgramGroup, 40); constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.fill = GridBagConstraints.HORIZONTAL; layout.addLayoutComponent (programGroup, constraints); add (programGroup); // reset button that allows the user to revert to the // original suggestion for the program group defaultButton = new HighlightJButton ( parent.langpack.getString ("ShortcutPanel.regular.default"), idata.buttonsHColor); defaultButton.addActionListener (this); constraints.gridx = 1; constraints.gridy = 2; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.fill = GridBagConstraints.NONE; layout.addLayoutComponent (defaultButton, constraints); add (defaultButton); // check box to allow the user to decide if a desktop // shortcut should be created. // this should only be created if needed and requested // in the definition file. allowDesktopShortcut = new JCheckBox (parent.langpack.getString ("ShortcutPanel.regular.desktop"), true); constraints.gridx = 0; constraints.gridy = 3; constraints.gridwidth = 1; constraints.gridheight = 1; if (hasDesktopShortcuts) { layout.addLayoutComponent (allowDesktopShortcut, constraints); add (allowDesktopShortcut); } // button to initiate the creation of the shortcuts createButton = new HighlightJButton ( parent.langpack.getString ("ShortcutPanel.regular.create"), idata.buttonsHColor); createButton.addActionListener (this); constraints.gridx = 0; constraints.gridy = 4; constraints.gridwidth = 1; constraints.gridheight = 1; layout.addLayoutComponent (createButton, constraints); add (createButton); } /** * This method creates an alternative UI for this panel. This UI can be * used when the creation of shortcuts is not supported on the target system. * It displays an apology for the inability to create shortcuts on this * system, along with information about the intended targets. In addition, * there is a button that allows the user to save more complete information * in a text file. Based on this information the user might be able to create * the necessary shortcut him or herself. At least there will be information * about how to launch the application. */ private void buildAlternateUI () { layout = new GridBagLayout (); constraints = new GridBagConstraints (); setLayout(layout); // static text a the top of the panel, that apologizes // about the fact that we can not create shortcuts on // this particular target OS. MultiLineLabel apologyLabel = new MultiLineLabel (parent.langpack.getString ("ShortcutPanel.alternate.apology"), 0, 0); constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets = new Insets (5, 5, 5, 5); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.WEST; layout.addLayoutComponent (apologyLabel, constraints); add (apologyLabel); // label that explains the significance ot the list box MultiLineLabel listLabel = new MultiLineLabel (parent.langpack.getString ("ShortcutPanel.alternate.targetsLabel"), 0, 0); constraints.gridx = 0; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; layout.addLayoutComponent (listLabel, constraints); add (listLabel); // list box to list all of the intended shortcut targets Vector targets = new Vector (); for (int i = 0; i < shortcuts.size (); i++) { targets.add (((ShortcutData)shortcuts.elementAt (i)).target); } targetList = new JList (targets); JScrollPane scrollPane = new JScrollPane (targetList); constraints.gridx = 0; constraints.gridy = 2; constraints.fill = GridBagConstraints.BOTH; layout.addLayoutComponent (scrollPane, constraints); add (scrollPane); // static text that explains about the text file MultiLineLabel fileExplanation = new MultiLineLabel (parent.langpack.getString ("ShortcutPanel.alternate.textFileExplanation"), 0, 0); constraints.gridx = 0; constraints.gridy = 3; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; layout.addLayoutComponent (fileExplanation, constraints); add (fileExplanation); // button to save the text file saveButton = new HighlightJButton( parent.langpack.getString ("ShortcutPanel.alternate.saveButton"), idata.buttonsHColor); saveButton.addActionListener (this); constraints.gridx = 0; constraints.gridy = 4; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.CENTER; layout.addLayoutComponent (saveButton, constraints); add (saveButton); } /** * Overriding the superclass implementation. This method returns the size of * the container. * * @return the size of the container */ public Dimension getSize () { Dimension size = getParent ().getSize (); Insets insets = getInsets (); Border border = getBorder (); Insets borderInsets = new Insets (0, 0, 0, 0); if (border != null) { borderInsets = border.getBorderInsets (this); } size.height = size.height - insets.top - insets.bottom - borderInsets.top - borderInsets.bottom - 50; size.width = size.width - insets.left - insets.right - borderInsets.left - borderInsets.right - 50; return (size); } /** * This method saves all shortcut information to a text file. */ private void saveToFile () { File file = null; // open a file chooser dialog to get a path / file name JFileChooser fileDialog = new JFileChooser (idata.getInstallPath ()); fileDialog.setSelectedFile (new File (TEXT_FILE_NAME)); if(fileDialog.showSaveDialog (this) == JFileChooser.APPROVE_OPTION) { file = fileDialog.getSelectedFile (); } else { return; } // save to the file FileWriter output = null; StringBuffer buffer = new StringBuffer (); String header = parent.langpack.getString ("ShortcutPanel.textFile.header"); String newline = System.getProperty ("line.separator", "\n"); try { output = new FileWriter (file); } catch (Throwable exception) { // !!! show an error dialog return; } // break the header down into multiple lines based // on '\n' line breaks. int nextIndex = 0; int currentIndex = 0; do { nextIndex = header.indexOf ("\\n", currentIndex); if (nextIndex > -1) { buffer.append (header.substring (currentIndex, nextIndex)); buffer.append (newline); currentIndex = nextIndex + 2; } else { buffer.append (header.substring (currentIndex, header.length ())); buffer.append (newline); } } while (nextIndex > -1); buffer.append (SEPARATOR_LINE); buffer.append (newline); buffer.append (newline); for (int i = 0; i < shortcuts.size (); i++) { ShortcutData data = (ShortcutData)shortcuts.elementAt (i); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.name")); buffer.append (data.name); buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.location")); switch (data.type) { case Shortcut.DESKTOP : { buffer.append (parent.langpack.getString ("ShortcutPanel.location.desktop")); break; } case Shortcut.APPLICATIONS : { buffer.append (parent.langpack.getString ("ShortcutPanel.location.applications")); break; } case Shortcut.START_MENU : { buffer.append (parent.langpack.getString ("ShortcutPanel.location.startMenu")); break; } case Shortcut.START_UP : { buffer.append (parent.langpack.getString ("ShortcutPanel.location.startup")); break; } } buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.description")); buffer.append (data.description); buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.target")); buffer.append (data.target); buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.command")); buffer.append (data.commandLine); buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.iconName")); buffer.append (data.iconFile); buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.iconIndex")); buffer.append (data.iconIndex); buffer.append (newline); buffer.append (parent.langpack.getString ("ShortcutPanel.textFile.work")); buffer.append (data.workingDirectory); buffer.append (newline); buffer.append (newline); buffer.append (SEPARATOR_LINE); buffer.append (newline); buffer.append (newline); } try { output.write (buffer.toString ()); } catch (Throwable exception) { } finally { try { output.flush (); output.close (); files.add (file.getPath ()); } catch (Throwable exception) { // not really anything I can do here, maybe should show a dialog that // tells the user that data might not have been saved completely!? } } } /** * Adds all files and directories to the uninstaller. */ private void addToUninstaller () { UninstallData uninstallData = UninstallData.getInstance (); for (int i = 0; i < files.size (); i++) { uninstallData.addFile ((String)files.elementAt (i)); } } /** * Adds iformation about the shortcuts that have been created during the * installation to the XML tree. * * @param panelRoot the root of the XML tree */ public void makeXMLData (XMLElement panelRoot) { // if there are no shortcuts to create, shortcuts are // not supported, or we should simulate that they are // not supported, then we have nothing to add. Just // return if (!shortcutsToCreate || !shortcut.supported () || !shortcutsCreationDone || simulteNotSupported ) { return; } ShortcutData data; XMLElement dataElement; // add the item that defines the name of the program group dataElement = new XMLElement (AUTO_KEY_PROGRAM_GROUP); dataElement.setAttribute (AUTO_ATTRIBUTE_NAME, groupName); panelRoot.addChild (dataElement); // add the details for each of the shortcuts for (int i = 0; i < shortcuts.size (); i++) { data = (ShortcutData)shortcuts.elementAt (i); dataElement = new XMLElement (AUTO_KEY_SHORTCUT); dataElement.setAttribute (AUTO_ATTRIBUTE_NAME, data.name); dataElement.setAttribute (AUTO_ATTRIBUTE_GROUP, new Boolean (data.addToGroup).toString ()); dataElement.setAttribute (AUTO_ATTRIBUTE_TYPE, Integer.toString (data.type)); dataElement.setAttribute (AUTO_ATTRIBUTE_COMMAND, data.commandLine); dataElement.setAttribute (AUTO_ATTRIBUTE_DESCRIPTION, data.description); dataElement.setAttribute (AUTO_ATTRIBUTE_ICON, data.iconFile); dataElement.setAttribute (AUTO_ATTRIBUTE_ICON_INDEX, Integer.toString (data.iconIndex)); dataElement.setAttribute (AUTO_ATTRIBUTE_INITIAL_STATE, Integer.toString (data.initialState)); dataElement.setAttribute (AUTO_ATTRIBUTE_TARGET, data.target); dataElement.setAttribute (AUTO_ATTRIBUTE_WORKING_DIR, data.workingDirectory); // add the shortcut only if it is either not on // the desktop or if it is on the desktop and // the user has signalled that it is ok to place // shortcuts on the desktop. if ( (data.type != Shortcut.DESKTOP) || ((data.type == Shortcut.DESKTOP) && allowDesktopShortcut.isSelected ()) ) { panelRoot.addChild (dataElement); } } } /** * Creates shortcuts based on teh information in <code>panelRoot</code> * without UI. * * @param panelRoot the root of the XML tree */ public void runAutomated (XMLElement panelRoot) { // if shortcuts are not supported, then we can not // create shortcuts, even if there was any install // data. Just return. if (!shortcut.supported ()) { return; } shortcuts = new Vector (); Vector shortcutElements; ShortcutData data; XMLElement dataElement; // set the name of the program group dataElement = panelRoot.getFirstChildNamed (AUTO_KEY_PROGRAM_GROUP); groupName = dataElement.getAttribute (AUTO_ATTRIBUTE_NAME); if (groupName == null) { groupName = ""; } // add the details for each of the shortcuts shortcutElements = panelRoot.getChildrenNamed (AUTO_KEY_SHORTCUT); for (int i = 0; i < shortcutElements.size (); i++) { data = new ShortcutData (); dataElement = (XMLElement)shortcutElements.elementAt (i); data.name = dataElement.getAttribute (AUTO_ATTRIBUTE_NAME); data.addToGroup = Boolean.valueOf (dataElement.getAttribute (AUTO_ATTRIBUTE_GROUP)).booleanValue (); data.type = Integer.valueOf (dataElement.getAttribute (AUTO_ATTRIBUTE_TYPE)).intValue (); data.commandLine = dataElement.getAttribute (AUTO_ATTRIBUTE_COMMAND); data.description = dataElement.getAttribute (AUTO_ATTRIBUTE_DESCRIPTION); data.iconFile = dataElement.getAttribute (AUTO_ATTRIBUTE_ICON); data.iconIndex = Integer.valueOf (dataElement.getAttribute (AUTO_ATTRIBUTE_ICON_INDEX)).intValue (); data.initialState = Integer.valueOf (dataElement.getAttribute (AUTO_ATTRIBUTE_INITIAL_STATE)).intValue (); data.target = dataElement.getAttribute (AUTO_ATTRIBUTE_TARGET); data.workingDirectory = dataElement.getAttribute (AUTO_ATTRIBUTE_WORKING_DIR); shortcuts.add (data); } createShortcuts (); } }
package uk.ac.ebi.gxa.statistics; import java.io.Serializable; /** * Serializable representation of an Atlas Experiment for the purpose of ConciseSet storage */ public class Experiment implements Serializable { private static final long serialVersionUID = 5513628423830801336L; private String accession; private long experimentId; // Used to store minimum pVal when retrieving ranked lists of experiments sorted (ASC) by pValue/tStat ranks wrt to a specific ef(-efv) combination PvalTstatRank pValTstatRank; // Attribute for which pValue and tStatRank were found e.g. when obtaining a list of experiments to display on the gene page private transient Attribute highestRankAttribute; public Experiment(final String accession, final Long experimentId) { this.accession = accession.intern(); this.experimentId = experimentId; } public String getAccession() { return accession; } public void setAccession(final String accession) { this.accession = accession.intern(); } public long getExperimentId() { return experimentId; } public PvalTstatRank getpValTStatRank() { return pValTstatRank; } public void setPvalTstatRank(PvalTstatRank pValTstatRank) { this.pValTstatRank = pValTstatRank; } public Attribute getHighestRankAttribute() { return highestRankAttribute; } public void setHighestRankAttribute(Attribute highestRankAttribute) { this.highestRankAttribute = highestRankAttribute; } @Override public String toString() { return "experimentId: " + experimentId + "; accession: " + accession + "; highestRankAttribute: " + highestRankAttribute; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Experiment that = (Experiment) o; if (accession == null || !accession.equals(that.accession) || experimentId != experimentId) { return false; } return true; } @Override public int hashCode() { int result = accession != null ? accession.hashCode() : 0; result = 31 * result + Long.valueOf(experimentId).hashCode(); return result; } }
package br.com.caelum.parsac.modelo; import java.util.List; import br.com.caelum.parsac.util.SecaoConverter; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; @XStreamAlias("secao") @XStreamConverter(SecaoConverter.class) public class Secao { private int numero; private String titulo; private String explicacao; private List<Exercicio> exercicios; public Secao() { } public Secao(int numero, String titulo, String explicacao, List<Exercicio> exercicios) { this.numero = numero; this.titulo = titulo; this.explicacao = explicacao; this.exercicios = exercicios; } public int getNumero() { return numero; } public String getTitulo() { return titulo; } public String getExplicacao() { return explicacao; } public List<Exercicio> getExercicios() { return exercicios; } public void setNumero(int numero) { this.numero = numero; } public void setTitulo(String titulo) { this.titulo = titulo; } public void setExplicacao(String explicacao) { this.explicacao = explicacao; } public void setExercicios(List<Exercicio> exercicios) { this.exercicios = exercicios; } public String toString() { return "Seção " + this.numero + ": " + this.titulo + "\n" + this.explicacao + "\n\n" + this.exercicios; } }
package com.akiban.http; import com.akiban.server.service.Service; import com.akiban.server.service.config.ConfigurationService; import com.google.inject.Inject; import org.eclipse.jetty.util.security.Constraint; import org.eclipse.jetty.security.ConstraintMapping; import org.eclipse.jetty.security.ConstraintSecurityHandler; import org.eclipse.jetty.security.JDBCLoginService; import org.eclipse.jetty.security.SecurityHandler; import org.eclipse.jetty.security.authentication.BasicAuthenticator; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerCollection; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.eclipse.jetty.util.thread.QueuedThreadPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.logging.LogManager; public final class HttpConductorImpl implements HttpConductor, Service { private static final Logger logger = LoggerFactory.getLogger(HttpConductorImpl.class); private static final String PORT_PROPERTY = "akserver.http.port"; private static final String SSL_PROPERTY = "akserver.http.ssl"; private static final String LOGIN_PROPERTY = "akserver.http.login"; private static final String REST_ROLE = "rest-user"; private static final String LOGIN_REALM = "AkServer"; private static final String JDBC_REALM_RESOURCE = "jdbcRealm.properties"; private final ConfigurationService configurationService; private final Object lock = new Object(); private HandlerCollection handlerCollection; private Server server; private Set<String> registeredPaths; private volatile int port = -1; // Need reference to prevent GC and setting loss private final java.util.logging.Logger jerseyLogging; @Inject public HttpConductorImpl(ConfigurationService configurationService, com.akiban.sql.embedded.EmbeddedJDBCService jdbcService) { this.configurationService = configurationService; jerseyLogging = java.util.logging.Logger.getLogger("com.sun.jersey"); jerseyLogging.setLevel(java.util.logging.Level.OFF); } @Override public void registerHandler(ContextHandler handler) { String contextBase = getContextPathPrefix(handler.getContextPath()); synchronized (lock) { if (registeredPaths == null) registeredPaths = new HashSet<>(); if (!registeredPaths.add(contextBase)) throw new IllegalPathRequest("context already reserved: " + contextBase); handlerCollection.addHandler(handler); if (!handler.isStarted()) { try { handler.start(); } catch (Exception e) { throw new HttpConductorException(e); } } } } @Override public int getPort() { return port; } @Override public void unregisterHandler(ContextHandler handler) { String contextBase = getContextPathPrefix(handler.getContextPath()); synchronized (lock) { if (registeredPaths == null || (!registeredPaths.remove(contextBase))) { logger.warn("Path not registered (for " + handler + "): " + contextBase); } else { handlerCollection.removeHandler(handler); if (!handler.isStopped()) { // As of the current version of jetty, HandlerCollection#removeHandler stops the handler -- so // this block won't get executed. This is really here for future-proofing, in case that auto-stop // goes away for some reason. try { handler.stop(); } catch (Exception e) { throw new HttpConductorException(e); } } } } } @Override public void start() { String portProperty = configurationService.getProperty(PORT_PROPERTY); String sslProperty = configurationService.getProperty(SSL_PROPERTY); String loginProperty = configurationService.getProperty(LOGIN_PROPERTY); int portLocal; boolean ssl, login; try { portLocal = Integer.parseInt(portProperty); } catch (NumberFormatException e) { logger.error("bad port descriptor: " + portProperty); throw e; } ssl = Boolean.parseBoolean(sslProperty); login = Boolean.parseBoolean(loginProperty); logger.info("Starting {} service on port {}", ssl ? "HTTPS" : "HTTP", portProperty); Server localServer = new Server(); SelectChannelConnector connector; if (!ssl) { connector = new SelectChannelConnector(); } else { // Share keystore configuration with PSQL. SslContextFactory sslFactory = new SslContextFactory(); sslFactory.setKeyStorePath(System.getProperty("javax.net.ssl.keyStore")); sslFactory.setKeyStorePassword(System.getProperty("javax.net.ssl.keyStorePassword")); connector = new SslSelectChannelConnector(sslFactory); } connector.setPort(portLocal); connector.setThreadPool(new QueuedThreadPool(200)); connector.setAcceptors(4); connector.setMaxIdleTime(300000); connector.setAcceptQueueSize(12000); connector.setLowResourcesConnections(25000); localServer.setConnectors(new Connector[]{connector}); HandlerCollection localHandlerCollection = new HandlerCollection(true); try { if (!login) { localServer.setHandler(localHandlerCollection); } else { Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, REST_ROLE); constraint.setAuthenticate(true); ConstraintMapping cm = new ConstraintMapping();
package com.collective.celos; import java.text.ParseException; import java.util.Date; import java.util.SortedSet; import java.util.TreeSet; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.quartz.CronExpression; import com.fasterxml.jackson.databind.node.ObjectNode; public class CronSchedule implements Schedule { private final static String CRON_CONFIG_PROPERTY = "cron_config"; private CronExpression cronExpression; public CronSchedule(ObjectNode properties) { String cronConfig = properties.get(CRON_CONFIG_PROPERTY).asText(); try { CronExpression.validateExpression(cronConfig); cronExpression = new CronExpression(cronConfig); cronExpression.setTimeZone(DateTimeZone.UTC.toTimeZone()); } catch (ParseException e) { throw new IllegalArgumentException("Error in cron expression", e); } } public String getCronExpression() { return cronExpression.getCronExpression(); } @Override public SortedSet<ScheduledTime> getScheduledTimes(ScheduledTime start, ScheduledTime end) { Date startDT = start.getDateTime().toDate(); SortedSet<ScheduledTime> scheduledTimes = new TreeSet<ScheduledTime>(); if (cronExpression.isSatisfiedBy(startDT) && start.getDateTime().isBefore(end.getDateTime())) { scheduledTimes.add(start); } DateTime candidateTime = start.getDateTime(); while((candidateTime = getNextDateTime(candidateTime)) != null && candidateTime.isBefore(end.getDateTime())) { scheduledTimes.add(new ScheduledTime(candidateTime)); } return scheduledTimes; } private DateTime getNextDateTime(DateTime candidateTime) { Date date = cronExpression.getNextValidTimeAfter(candidateTime.toDate()); if (date != null) { return new DateTime(date).withZone(DateTimeZone.UTC); } return null; } }
package com.crowdin.cli.commands; import com.crowdin.cli.BaseCli; import com.crowdin.cli.client.BranchClient; import com.crowdin.cli.client.ProjectClient; import com.crowdin.cli.client.ProjectWrapper; import com.crowdin.cli.client.TranslationsClient; import com.crowdin.cli.properties.CliProperties; import com.crowdin.cli.properties.FileBean; import com.crowdin.cli.properties.PropertiesBean; import com.crowdin.cli.utils.*; import com.crowdin.cli.utils.console.ConsoleSpinner; import com.crowdin.cli.utils.console.ConsoleUtils; import com.crowdin.cli.utils.console.ExecutionStatus; import com.crowdin.cli.utils.file.FileReader; import com.crowdin.cli.utils.file.FileUtil; import com.crowdin.cli.utils.tree.DrawTree; import com.crowdin.client.CrowdinRequestBuilder; import com.crowdin.client.api.*; import com.crowdin.common.Settings; import com.crowdin.common.models.*; import com.crowdin.common.request.*; import com.crowdin.common.response.Page; import com.crowdin.common.response.SimpleResponse; import com.crowdin.util.CrowdinHttpClient; import com.crowdin.util.ObjectMapperUtil; import com.crowdin.util.PaginationUtil; import com.crowdin.util.ResponseUtil; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.cli.CommandLine; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.util.Strings; import javax.ws.rs.core.Response; import java.io.*; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipException; import static com.crowdin.cli.properties.CliProperties.*; import static com.crowdin.cli.utils.MessageSource.Messages.*; import static com.crowdin.cli.utils.console.ExecutionStatus.ERROR; import static com.crowdin.cli.utils.console.ExecutionStatus.OK; public class Commands extends BaseCli { private String branch = null; private HashMap<String, Object> cliConfig = new HashMap<>(); private CrowdinCliOptions cliOptions = new CrowdinCliOptions(); private CliProperties cliProperties = new CliProperties(); private File configFile = null; private Settings settings = null; private CommandUtils commandUtils = new CommandUtils(); private boolean dryrun = false; private FileReader fileReader = new FileReader(); private boolean help = false; private File identity = null; private HashMap<String, Object> identityCliConfig = null; private boolean isDebug = false; private boolean isVerbose = false; private String language = null; private ProjectWrapper projectInfo = null; private PropertiesBean propertiesBean = new PropertiesBean(); private boolean version = false; private boolean noProgress = false; private boolean skipGenerateDescription = false; private void initialize(String resultCmd, CommandLine commandLine) { this.removeUnsupportedCharsetProperties(); if (notNeedInitialisation(resultCmd, commandLine)) { return; } try { PropertiesBean configFromParameters = commandUtils.makeConfigFromParameters(commandLine, this.propertiesBean); if (configFromParameters != null) { this.propertiesBean = configFromParameters; } else { try { this.configFile = Stream.of(commandLine.getOptionValue(CrowdinCliOptions.CONFIG_LONG), "crowdin.yml", "crowdin.yaml") .filter(StringUtils::isNoneEmpty) .map(File::new) .filter(File::isFile) .findFirst() .orElseThrow(() -> new RuntimeException(RESOURCE_BUNDLE.getString("configuration_file_empty"))); this.cliConfig = this.fileReader.readCliConfig(this.configFile); this.propertiesBean = this.cliProperties.loadProperties(this.cliConfig); if (this.identity != null && this.identity.isFile()) { this.propertiesBean = this.readIdentityProperties(this.propertiesBean); } } catch (Exception e) { throw new RuntimeException(RESOURCE_BUNDLE.getString("error_loading_config"), e); } } this.propertiesBean.setBaseUrl(commandUtils.getBaseUrl(this.propertiesBean)); this.settings = Settings.withBaseUrl(this.propertiesBean.getApiToken(), this.propertiesBean.getBaseUrl()); this.propertiesBean.setBasePath(commandUtils.getBasePath(this.propertiesBean.getBasePath(), this.configFile, this.isDebug)); if (configFromParameters == null && StringUtils.isNoneEmpty(commandLine.getOptionValue("base-path"))) { propertiesBean.setBasePath(commandLine.getOptionValue("base-path")); } this.propertiesBean = cliProperties.validateProperties(propertiesBean); } catch (Exception e) { throw new RuntimeException(RESOURCE_BUNDLE.getString("initialisation_failed"), e); } } private ProjectWrapper getProjectInfo() { if (projectInfo == null) { ConsoleSpinner.start(FETCHING_PROJECT_INFO.getString(), this.noProgress); projectInfo = new ProjectClient(this.settings).getProjectInfo(this.propertiesBean.getProjectId(), this.isDebug); ConsoleSpinner.stop(OK); } return projectInfo; } private PlaceholderUtil getPlaceholderUtil() { ProjectWrapper proj = getProjectInfo(); return new PlaceholderUtil(proj.getSupportedLanguages(), proj.getProjectLanguages(), propertiesBean.getBasePath()); } private boolean notNeedInitialisation(String resultCmd, CommandLine commandLine) { return resultCmd.startsWith(HELP) || (GENERATE.equals(resultCmd) || INIT.equals(resultCmd)) || "".equals(resultCmd) || commandLine.hasOption(CrowdinCliOptions.HELP_LONG) || commandLine.hasOption(CrowdinCliOptions.HELP_SHORT); } private void removeUnsupportedCharsetProperties() { try { String stdoutEncoding = System.getProperties().getProperty("sun.stdout.encoding"); if (stdoutEncoding != null && !stdoutEncoding.isEmpty()) { java.nio.charset.Charset.forName(stdoutEncoding); } } catch (UnsupportedCharsetException e) { System.getProperties().remove("sun.stdout.encoding"); } } private PropertiesBean readIdentityProperties(PropertiesBean propertiesBean) { try { this.identityCliConfig = this.fileReader.readCliConfig(this.identity); } catch (Exception e) { System.out.println(RESOURCE_BUNDLE.getString("error_reading_configuration_file") + " '" + this.identity.getAbsolutePath() + "'"); if (this.isDebug) { e.printStackTrace(); } ConsoleUtils.exitError(); } if (this.identityCliConfig != null) { if (this.identityCliConfig.get("project_idr_env") != null) { String projectIdEnv = this.identityCliConfig.get("project_id_env").toString(); String projectId = System.getenv(projectIdEnv); if (StringUtils.isNotEmpty(projectId)) { propertiesBean.setProjectId(projectId); } } if (this.identityCliConfig.get("api_token_env") != null) { String apiTokenEnv = this.identityCliConfig.get("api_token_env").toString(); String apiToken = System.getenv(apiTokenEnv); if (StringUtils.isNotEmpty(apiToken)) { propertiesBean.setApiToken(apiToken); } } if (this.identityCliConfig.get("base_path_env") != null) { String basePathEnv = this.identityCliConfig.get("base_path_env").toString(); String basePath = System.getenv(basePathEnv); if (StringUtils.isNotEmpty(basePath)) { propertiesBean.setBasePath(basePath); } } if (this.identityCliConfig.get("base_url_env") != null) { String baseUrlEnv = this.identityCliConfig.get("base_url_env").toString(); String baseUrl = System.getenv(baseUrlEnv); if (StringUtils.isNotEmpty(baseUrl)) { propertiesBean.setBaseUrl(baseUrl); } } if (this.identityCliConfig.get("project_id") != null) { propertiesBean.setProjectId(this.identityCliConfig.get("project_id").toString()); } if (this.identityCliConfig.get("api_token") != null) { propertiesBean.setApiToken(this.identityCliConfig.get("api_token").toString()); } if (this.identityCliConfig.get("base_path") != null) { propertiesBean.setBasePath(this.identityCliConfig.get("base_path").toString()); } if (this.identityCliConfig.get("base_url") != null) { propertiesBean.setBaseUrl(this.identityCliConfig.get("base_url").toString()); } } return propertiesBean; } public void run(String resultCmd, CommandLine commandLine) { if (commandLine == null) { System.out.println(RESOURCE_BUNDLE.getString("commandline_null")); ConsoleUtils.exitError(); } if (resultCmd == null) { System.out.println(RESOURCE_BUNDLE.getString("command_not_found")); ConsoleUtils.exitError(); } this.branch = this.commandUtils.getBranch(commandLine); this.language = this.commandUtils.getLanguage(commandLine); this.identity = this.commandUtils.getIdentityFile(commandLine); this.isDebug = commandLine.hasOption(CrowdinCliOptions.DEBUG_LONG); this.isVerbose = commandLine.hasOption(CrowdinCliOptions.VERBOSE_LONG) || commandLine.hasOption(CrowdinCliOptions.VERBOSE_SHORT); this.dryrun = commandLine.hasOption(CrowdinCliOptions.DRY_RUN_LONG); this.help = commandLine.hasOption(HELP) || commandLine.hasOption(HELP_SHORT); this.version = commandLine.hasOption(CrowdinCliOptions.VERSION_LONG); this.noProgress = commandLine.hasOption(CrowdinCliOptions.NO_PROGRESS); this.skipGenerateDescription = commandLine.hasOption(CrowdinCliOptions.SKIP_GENERATE_DESCRIPTION); this.initialize(resultCmd, commandLine); if (this.help) { this.help(resultCmd); return; } switch (resultCmd) { case UPLOAD: case UPLOAD_SOURCES: case PUSH: boolean isAutoUpdate = commandLine.getOptionValue(COMMAND_NO_AUTO_UPDATE) == null; if (this.dryrun) { this.dryrunSources(commandLine); } else { this.uploadSources(isAutoUpdate); } break; case UPLOAD_TRANSLATIONS: boolean isImportDuplicates = commandLine.hasOption(CrowdinCliOptions.IMPORT_DUPLICATES); boolean isImportEqSuggestions = commandLine.hasOption(CrowdinCliOptions.IMPORT_EQ_SUGGESTIONS); boolean isAutoApproveImported = commandLine.hasOption(CrowdinCliOptions.AUTO_APPROVE_IMPORTED); this.uploadTranslation(isImportDuplicates, isImportEqSuggestions, isAutoApproveImported); break; case DOWNLOAD: case DOWNLOAD_TRANSLATIONS: case PULL: boolean ignoreMatch = commandLine.hasOption(IGNORE_MATCH); if (this.dryrun) { this.dryrunTranslation(commandLine); } else { this.downloadTranslation(ignoreMatch); } break; case LIST: this.help(resultCmd); break; case LIST_PROJECT: this.dryrunProject(commandLine); break; case LIST_SOURCES: this.dryrunSources(commandLine); break; case LIST_TRANSLATIONS: this.dryrunTranslation(commandLine); break; case LINT: this.lint(); break; case INIT: case GENERATE: String config = null; if (commandLine.getOptionValue(DESTINATION_LONG) != null && !commandLine.getOptionValue(DESTINATION_LONG).isEmpty()) { config = commandLine.getOptionValue(DESTINATION_LONG); } else if (commandLine.getOptionValue(DESTINATION_SHORT) != null && !commandLine.getOptionValue(DESTINATION_SHORT).isEmpty()) { config = commandLine.getOptionValue(DESTINATION_SHORT); } this.generate(config); break; case HELP: boolean p = commandLine.hasOption(HELP_P); if (p) { System.out.println(UPLOAD); System.out.println(DOWNLOAD); System.out.println(LIST); System.out.println(LINT); System.out.println(GENERATE); System.out.println(HELP); } else { this.help(resultCmd); } break; case HELP_HELP: case HELP_UPLOAD: case HELP_UPLOAD_SOURCES: case HELP_UPLOAD_TRANSLATIONS: case HELP_DOWNLOAD: case HELP_GENERATE: case HELP_LIST: case HELP_LIST_PROJECT: case HELP_LIST_SOURCES: case HELP_LIST_TRANSLATIONS: case HELP_LINT: this.help(resultCmd); break; default: if (this.version) { System.out.println("Crowdin CLI version is " + Utils.getAppVersion()); } else { StringBuilder wrongArgs = new StringBuilder(); for (String wrongCmd : commandLine.getArgList()) { wrongArgs.append(wrongCmd).append(" "); } if (!"".equalsIgnoreCase(wrongArgs.toString().trim())) { System.out.println("Command '" + wrongArgs.toString().trim() + "' not found"); } this.help(HELP); } break; } } private void generate(String path) { File skeleton; if (path != null && !path.isEmpty()) { skeleton = new File(path); } else { skeleton = new File("crowdin.yml"); } Path destination = Paths.get(skeleton.toURI()); System.out.println(RESOURCE_BUNDLE.getString("command_generate_description") + " '" + destination + "'"); if (Files.exists(destination)) { System.out.println(ExecutionStatus.SKIPPED.getIcon() + "File '" + destination + "' already exists."); return; } try { if (skipGenerateDescription) { InputStream is = Commands.class.getResourceAsStream("/crowdin.yml"); Files.copy(is, destination); return; } InputStream is = Commands.class.getResourceAsStream("/crowdin.yml"); Files.copy(is, destination); List<String> dummyConfig = new ArrayList<>(); Scanner in = new Scanner(skeleton); while (in.hasNextLine()) dummyConfig.add(in.nextLine()); System.out.println(GENERATE_HELP_MESSAGE.getString()); Scanner consoleScanner = new Scanner(System.in); for (String param : Arrays.asList(API_TOKEN, PROJECT_ID, BASE_PATH, BASE_URL)) { System.out.print(param.replaceAll("_", " ") + " : "); String userInput = consoleScanner.nextLine(); ListIterator<String> dummyConfigIterator = dummyConfig.listIterator(); while (dummyConfigIterator.hasNext()) { String defaultLine = dummyConfigIterator.next(); if (defaultLine.contains(param)) { String lineWithUserInput = defaultLine.replaceFirst(": \"*\"", String.format(": \"%s\"", userInput)); dummyConfigIterator.set(lineWithUserInput); Files.write(destination, dummyConfig); break; } } } } catch (Exception ex) { System.out.println(RESOURCE_BUNDLE.getString("error_generate")); if (this.isDebug) { ex.printStackTrace(); } } } private Branch createBranch(String name) { try { Response createBranchResponse = new BranchesApi(settings) .createBranch(Long.toString(this.getProjectInfo().getProject().getId()), new BranchPayload(name)) .execute(); Branch branch = ResponseUtil.getResponceBody(createBranchResponse, new TypeReference<SimpleResponse<Branch>>() { }).getEntity(); if (this.isVerbose) { System.out.println(createBranchResponse.getHeaders()); System.out.println(ResponseUtil.getResponceBody(createBranchResponse)); } System.out.println(OK.withIcon(RESOURCE_BUNDLE.getString("creating_branch") + " '" + name + "'")); return branch; } catch (Exception e) { System.out.println(ERROR.withIcon(RESOURCE_BUNDLE.getString("creating_branch") + " '" + name + "'")); System.out.println(e.getMessage()); if (this.isDebug) { e.printStackTrace(); } ConsoleUtils.exitError(); } return null; } private void uploadSources(boolean autoUpdate) { Boolean preserveHierarchy = this.propertiesBean.getPreserveHierarchy(); List<FileBean> files = this.propertiesBean.getFiles(); boolean noFiles = true; Optional<Long> branchId = getOrCreateBranchId(); for (FileBean file : files) { if (file.getSource() == null || file.getSource().isEmpty() || file.getTranslation() == null || file.getTranslation().isEmpty()) { continue; } List<String> sources = this.commandUtils.getSourcesWithoutIgnores(file, this.propertiesBean, getPlaceholderUtil()); if (!sources.isEmpty()) { noFiles = false; } String commonPath = ""; if (!preserveHierarchy) { commonPath = this.commandUtils.getCommonPath(sources, this.propertiesBean); } final String finalCommonPath = commonPath; final ProjectWrapper projectInfo = getProjectInfo(); List<Runnable> tasks = sources.stream() .map(source -> (Runnable) () -> { File sourceFile = new File(source); if (!sourceFile.isFile()) { return; } boolean isDest = file.getDest() != null && !file.getDest().isEmpty() && !this.commandUtils.isSourceContainsPattern(file.getSource()); Pair<String, Long> preservePathToParentId = this.commandUtils.preserveHierarchy(file, sourceFile.getAbsolutePath(), finalCommonPath, this.propertiesBean, this.branch, this.settings, projectInfo.getProject().getId(), this.isVerbose); String preservePath = preservePathToParentId.getLeft(); Long parentId = preservePathToParentId.getRight(); String fName; if (isDest) { fName = new File(file.getDest()).getName(); } else { fName = sourceFile.getName(); } preservePath = preservePath + Utils.PATH_SEPARATOR + fName; preservePath = preservePath.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); if (preservePath.startsWith(Utils.PATH_SEPARATOR)) { preservePath = preservePath.replaceFirst(Utils.PATH_SEPARATOR_REGEX, ""); } preservePath = preservePath.replaceAll(Utils.PATH_SEPARATOR_REGEX, "/"); FilePayload filePayload = new FilePayload(); filePayload.setDirectoryId(parentId); filePayload.setTitle(preservePath); filePayload.setType(file.getType()); branchId.ifPresent(filePayload::setBranchId); ImportOptions importOptions; if (source.endsWith(".xml")) { XmlFileImportOptions xmlFileImportOptions = new XmlFileImportOptions(); xmlFileImportOptions.setContentSegmentation(unboxingBoolean(file.getContentSegmentation())); xmlFileImportOptions.setTranslateAttributes(unboxingBoolean(file.getTranslateAttributes())); xmlFileImportOptions.setTranslateContent(unboxingBoolean(file.getTranslateContent())); xmlFileImportOptions.setTranslatableElements(file.getTranslatableElements()); importOptions = xmlFileImportOptions; } else { SpreadsheetFileImportOptions spreadsheetFileImportOptions = new SpreadsheetFileImportOptions(); spreadsheetFileImportOptions.setImportTranslations(true); spreadsheetFileImportOptions.setFirstLineContainsHeader(unboxingBoolean(file.getFirstLineContainsHeader())); spreadsheetFileImportOptions.setScheme(getSchemeObject(file)); importOptions = spreadsheetFileImportOptions; } filePayload.setImportOptions(importOptions); ExportOptions exportOptions = null; String translationWithReplacedAsterisk = null; if (Strings.isNotEmpty(sourceFile.getAbsolutePath()) && file.getTranslation() != null && !file.getTranslation().isEmpty()) { String translations = file.getTranslation(); if (translations.contains("**")) { translationWithReplacedAsterisk = this.commandUtils.replaceDoubleAsteriskInTranslation(file.getTranslation(), sourceFile.getAbsolutePath(), file.getSource(), this.propertiesBean); } if (translationWithReplacedAsterisk != null) { if (translationWithReplacedAsterisk.contains("\\")) { translationWithReplacedAsterisk = translationWithReplacedAsterisk.replaceAll(Utils.PATH_SEPARATOR_REGEX, "/"); translationWithReplacedAsterisk = translationWithReplacedAsterisk.replaceAll("/+", "/"); } GeneralFileExportOptions generalFileExportOptions = new GeneralFileExportOptions(); generalFileExportOptions.setExportPattern(translationWithReplacedAsterisk); exportOptions = generalFileExportOptions; } else { String pattern = file.getTranslation(); if (pattern != null && pattern.contains("\\")) { pattern = pattern.replaceAll(Utils.PATH_SEPARATOR_REGEX, "/"); pattern = pattern.replaceAll("/+", "/"); } GeneralFileExportOptions generalFileExportOptions = new GeneralFileExportOptions(); generalFileExportOptions.setExportPattern(pattern); exportOptions = generalFileExportOptions; } } filePayload.setExportOptions(exportOptions); Response response; try { Long storageId = createStorage(sourceFile); filePayload.setStorageId(storageId); filePayload.setName(preservePath); FilesApi filesApi = new FilesApi(settings); if (autoUpdate) { response = EntityUtils.find( projectInfo.getFiles(), filePayload.getName(), filePayload.getDirectoryId(), FileEntity::getName, FileEntity::getDirectoryId) .map(fileEntity -> { String fileId = fileEntity.getId().toString(); String projectId = projectInfo.getProjectId(); Map<String, Integer> schemeObject = getSchemeObject(file); String updateOption = getUpdateOption(file); Integer escapeQuotes = (int) file.getEscapeQuotes(); RevisionPayload revisionPayload = new RevisionPayload(storageId, schemeObject, file.getFirstLineContainsHeader(), updateOption, escapeQuotes); return new RevisionsApi(this.settings).createRevision(projectId, fileId, revisionPayload).execute(); }).orElseGet(() -> uploadFile(filePayload, filesApi)); } else { response = uploadFile(filePayload, filesApi); } System.out.println(OK.withIcon(RESOURCE_BUNDLE.getString("uploading_file") + " '" + preservePath + "'")); } catch (Exception e) { System.out.println(ERROR.withIcon(RESOURCE_BUNDLE.getString("uploading_file") + " '" + preservePath + "'")); System.out.println("message : " + e.getMessage()); if (this.isDebug) { e.printStackTrace(); } return; } if (this.isVerbose && response != null) { System.out.println(response.getHeaders()); System.out.println(ResponseUtil.getResponceBody(response)); } }) .collect(Collectors.toList()); ConcurrencyUtil.executeAndWait(tasks); } if (noFiles) { System.out.println("Error: No source files to upload.\n" + "Check your configuration file to ensure that they contain valid directives."); ConsoleUtils.exitError(); } } private String getUpdateOption(FileBean file) { String fileUpdateOption = file.getUpdateOption(); if (fileUpdateOption == null || fileUpdateOption.isEmpty()) { return null; } return fileUpdateOption; } private Response uploadFile(FilePayload filePayload, FilesApi filesApi) { String projectId = this.getProjectInfo().getProject().getId().toString(); return filesApi .createFile(projectId, filePayload) .execute(); } private Map<String, Integer> getSchemeObject(FileBean file) { String fileScheme = file.getScheme(); if (fileScheme == null || fileScheme.isEmpty()) { return null; } String[] schemePart = fileScheme.split(","); Map<String, Integer> scheme = new HashMap<>(); for (int i = 0; i < schemePart.length; i++) { scheme.put(schemePart[i], i); } return scheme; } private boolean unboxingBoolean(Boolean booleanValue) { return booleanValue == null ? false : booleanValue; } private void uploadTranslation(boolean importDuplicates, boolean importEqSuggestions, boolean autoApproveImported) { String projectId = getProjectInfo().getProject().getId().toString(); List<FileBean> files = propertiesBean.getFiles(); List<FileEntity> projectFiles = PaginationUtil.unpaged(new FilesApi(settings).getProjectFiles(projectId, Pageable.unpaged())); Map<Long, String> filesFullPath = commandUtils.getFilesFullPath(projectFiles, settings, getProjectInfo().getProject().getId()); final ProjectWrapper projectInfo = getProjectInfo(); for (FileBean file : files) { for (Language languageEntity : projectInfo.getSupportedLanguages()) { if (language != null && !language.isEmpty() && languageEntity != null && !language.equals(languageEntity.getId())) { continue; } String lng = (this.language == null || this.language.isEmpty()) ? languageEntity.getId() : this.language; List<String> sourcesWithoutIgnores = commandUtils.getSourcesWithoutIgnores(file, propertiesBean, getPlaceholderUtil()); String[] common = new String[sourcesWithoutIgnores.size()]; common = sourcesWithoutIgnores.toArray(common); String commonPath = Utils.replaceBasePath(Utils.commonPath(sourcesWithoutIgnores.toArray(common)), propertiesBean); if (Utils.isWindows()) { if (commonPath.contains("\\")) { commonPath = commonPath.replaceAll("\\\\", "/"); commonPath = commonPath.replaceAll("/+", "/"); } } final String finalCommonPath = commonPath; List<Runnable> tasks = sourcesWithoutIgnores.stream() .map(sourcesWithoutIgnore -> (Runnable) () -> { File sourcesWithoutIgnoreFile = new File(sourcesWithoutIgnore); List<String> translations = commandUtils.getTranslations(lng, sourcesWithoutIgnore, file, projectInfo, propertiesBean, "translations", getPlaceholderUtil()); Map<String, String> mapping = commandUtils.doLanguagesMapping(projectInfo, propertiesBean, languageEntity.getId(), getPlaceholderUtil()); List<File> translationFiles = new ArrayList<>(); for (String translation : translations) { translation = Utils.PATH_SEPARATOR + translation; translation = translation.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); String mappedTranslations = translation; if (Utils.isWindows() && translation.contains("\\")) { translation = translation.replaceAll("\\\\+", "/").replaceAll(" {2}\\+", "/"); } if (mapping != null && (mapping.get(translation) != null || mapping.get("/" + translation) != null)) { mappedTranslations = mapping.get(translation); } mappedTranslations = propertiesBean.getBasePath() + Utils.PATH_SEPARATOR + mappedTranslations; mappedTranslations = mappedTranslations.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); translationFiles.add(new File(mappedTranslations)); } for (File translationFile : translationFiles) { if (!translationFile.isFile()) { System.out.println("Translation file '" + translationFile.getAbsolutePath() + "' does not exist"); continue; } if (!sourcesWithoutIgnoreFile.isFile()) { System.out.println("Source file '" + Utils.replaceBasePath(sourcesWithoutIgnoreFile.getAbsolutePath(), propertiesBean) + "' does not exist"); continue; } String translationSrc = Utils.replaceBasePath(sourcesWithoutIgnoreFile.getAbsolutePath(), propertiesBean); if (Utils.isWindows()) { if (translationSrc.contains("\\")) { translationSrc = translationSrc.replaceAll("\\\\", "/"); translationSrc = translationSrc.replaceAll("/+", "/"); } } if (!propertiesBean.getPreserveHierarchy() && translationSrc.startsWith(finalCommonPath)) { translationSrc = translationSrc.replaceFirst(finalCommonPath, ""); } if (Utils.isWindows() && translationSrc.contains("/")) { translationSrc = translationSrc.replaceAll("/", Utils.PATH_SEPARATOR_REGEX); } if (Utils.isWindows()) { translationSrc = translationSrc.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/"); } if (translationSrc.startsWith("/")) { translationSrc = translationSrc.replaceFirst("/", ""); } boolean isDest = file.getDest() != null && !file.getDest().isEmpty() && !this.commandUtils.isSourceContainsPattern(file.getSource()); if (isDest) { translationSrc = file.getDest(); if (!propertiesBean.getPreserveHierarchy()) { if (translationSrc.lastIndexOf(Utils.PATH_SEPARATOR) != -1) { translationSrc = translationSrc.substring(translationSrc.lastIndexOf(Utils.PATH_SEPARATOR)); } translationSrc = translationSrc.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); } if (Utils.isWindows()) { translationSrc = translationSrc.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/"); } if (translationSrc.startsWith("/")) { translationSrc = translationSrc.replaceFirst("/", ""); } } String translationSrcFinal = translationSrc; Optional<FileEntity> projectFileOrNone = EntityUtils.find(projectFiles, o -> filesFullPath.get(o.getId()).equalsIgnoreCase(translationSrcFinal)); if (!projectFileOrNone.isPresent()) { System.out.println("source '" + translationSrcFinal + "' does not exist in the project"); continue; } try { System.out.println(OK.withIcon("Uploading translation file '" + Utils.replaceBasePath(translationFile.getAbsolutePath(), propertiesBean) + "'")); Long storageId = createStorage(translationFile); TranslationsClient translationsClient = new TranslationsClient(settings, projectId); translationsClient.uploadTranslations( languageEntity.getId(), projectFileOrNone.get().getId(), importDuplicates, importEqSuggestions, autoApproveImported, storageId ); } catch (Exception e) { System.out.println("message : " + e.getMessage()); if (isDebug) { e.printStackTrace(); } } } }) .collect(Collectors.toList()); ConcurrencyUtil.executeAndWait(tasks); } } } private Optional<Long> getOrCreateBranchId() { if (this.branch == null || this.branch.isEmpty()) return Optional.empty(); Optional<Long> existBranch = new BranchClient(this.settings).getProjectBranchByName(this.getProjectInfo().getProject().getId(), branch) .map(Branch::getId); if (existBranch.isPresent()) { return existBranch; } else { return Optional.ofNullable(this.createBranch(branch)).map(Branch::getId); } } private Long createStorage(File uploadData) { return new StorageApi(settings) .uploadFile(uploadData) .getResponseEntity() .getEntity() .getId(); } private void download(String languageCode, boolean ignoreMatch) { Language languageEntity = getProjectInfo().getProjectLanguages() .stream() .filter(language -> language.getId().equals(languageCode)) .findAny() .orElseThrow(() -> new RuntimeException("language '" + languageCode + "' does not exist in the project")); Long projectId = this.getProjectInfo().getProject().getId(); Optional<Branch> branchOrNull = Optional.ofNullable(this.branch) .flatMap(branchName -> new BranchClient(this.settings).getProjectBranchByName(projectId, branchName)); TranslationsClient translationsClient = new TranslationsClient(this.settings, projectId.toString()); System.out.println(RESOURCE_BUNDLE.getString("build_archive") + " for '" + languageCode + "'"); Translation translationBuild = null; try { ConsoleSpinner.start(BUILDING_TRANSLATION.getString(), this.noProgress); translationBuild = translationsClient.startBuildingTranslation(branchOrNull.map(b -> b.getId()), languageEntity.getId()); while (!translationBuild.getStatus().equalsIgnoreCase("finished")) { Thread.sleep(100); translationBuild = translationsClient.checkBuildingStatus(translationBuild.getId().toString()); } ConsoleSpinner.stop(OK); } catch (Exception e) { ConsoleSpinner.stop(ExecutionStatus.ERROR); System.out.println(e.getMessage()); if (isDebug) { e.printStackTrace(); } ConsoleUtils.exitError(); } if (isVerbose) { System.out.println(ObjectMapperUtil.getEntityAsString(translationBuild)); } String fileName = languageCode + ".zip"; String basePath = propertiesBean.getBasePath(); String baseTempDir; if (basePath.endsWith(Utils.PATH_SEPARATOR)) { baseTempDir = basePath + System.currentTimeMillis(); } else { baseTempDir = basePath + Utils.PATH_SEPARATOR + System.currentTimeMillis(); } String downloadedZipArchivePath = propertiesBean.getBasePath() != null && !propertiesBean.getBasePath().endsWith(Utils.PATH_SEPARATOR) ? propertiesBean.getBasePath() + Utils.PATH_SEPARATOR + fileName : propertiesBean.getBasePath() + fileName; File downloadedZipArchive = new File(downloadedZipArchivePath); try { ConsoleSpinner.start(DOWNLOADING_TRANSLATION.getString(), this.noProgress); FileRaw fileRaw = translationsClient.getFileRaw(translationBuild.getId().toString()); InputStream download = CrowdinHttpClient.download(fileRaw.getUrl()); FileUtil.writeToFile(download, downloadedZipArchivePath); ConsoleSpinner.stop(OK); if (isVerbose) { System.out.println(ObjectMapperUtil.getEntityAsString(fileRaw)); } } catch (IOException e) { System.out.println(ERROR_DURING_FILE_WRITE.getString()); if (isDebug) { e.printStackTrace(); } } catch (Exception e) { ConsoleSpinner.stop(ExecutionStatus.ERROR); System.out.println(e.getMessage()); ConsoleUtils.exitError(); } try { List<String> downloadedFiles = commandUtils.getListOfFileFromArchive(downloadedZipArchive, isDebug); List<String> downloadedFilesProc = new ArrayList<>(); for (String downloadedFile : downloadedFiles) { if (Utils.isWindows()) { downloadedFile = downloadedFile.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/"); } downloadedFilesProc.add(downloadedFile); } List<String> files = new ArrayList<>(); Map<String, String> mapping = commandUtils.doLanguagesMapping(getProjectInfo(), propertiesBean, languageCode, getPlaceholderUtil()); List<String> translations = this.list(TRANSLATIONS, "download"); for (String translation : translations) { translation = translation.replaceAll("/+", "/"); if (!files.contains(translation)) { if (translation.contains(Utils.PATH_SEPARATOR_REGEX)) { translation = translation.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", "/"); } else if (translation.contains(Utils.PATH_SEPARATOR)) { translation = translation.replaceAll(Utils.PATH_SEPARATOR + Utils.PATH_SEPARATOR, "/"); } translation = translation.replaceAll("/+", "/"); files.add(translation); } } List<String> sources = this.list(SOURCES, null); String commonPath; String[] common = new String[sources.size()]; common = sources.toArray(common); commonPath = Utils.commonPath(common); commonPath = Utils.replaceBasePath(commonPath, propertiesBean); if (commonPath.contains("\\")) { commonPath = commonPath.replaceAll("\\\\+", "/"); } commandUtils.sortFilesName(downloadedFilesProc); commandUtils.extractFiles(downloadedFilesProc, files, baseTempDir, ignoreMatch, downloadedZipArchive, mapping, isDebug, this.branch, propertiesBean, commonPath); commandUtils.renameMappingFiles(mapping, baseTempDir, propertiesBean, commonPath); FileUtils.deleteDirectory(new File(baseTempDir)); downloadedZipArchive.delete(); } catch (ZipException e) { System.out.println(RESOURCE_BUNDLE.getString("error_open_zip")); if (isDebug) { e.printStackTrace(); } } catch (Exception e) { System.out.println(RESOURCE_BUNDLE.getString("error_extracting_files")); if (isDebug) { e.printStackTrace(); } } } private void downloadTranslation(boolean ignoreMatch) { if (language != null) { this.download(language, ignoreMatch); } else { List<Language> projectLanguages = getProjectInfo().getProjectLanguages(); for (Language projectLanguage : projectLanguages) { if (projectLanguage != null && projectLanguage.getId() != null) { this.download(projectLanguage.getId(), ignoreMatch); } } } } public List<String> list(String subcommand, String command) { List<String> result = new ArrayList<>(); if (subcommand != null && !subcommand.isEmpty()) { switch (subcommand) { case PROJECT: { Long branchId = null; if (branch != null) { CrowdinRequestBuilder<Page<Branch>> branches = new BranchesApi(settings).getBranches(getProjectInfo().getProjectId(), null); Optional<Branch> branchOp = PaginationUtil.unpaged(branches).stream() .filter(br -> br.getName().equalsIgnoreCase(branch)) .findFirst(); if (branchOp.isPresent()) { branchId = branchOp.get().getId(); } } result = commandUtils.projectList(getProjectInfo().getFiles(), getProjectInfo().getDirectories(), branchId); break; } case SOURCES: { List<FileBean> files = propertiesBean.getFiles(); for (FileBean file : files) { result.addAll(commandUtils.getSourcesWithoutIgnores(file, propertiesBean, getPlaceholderUtil())); } break; } case TRANSLATIONS: { List<FileBean> files = propertiesBean.getFiles(); for (FileBean file : files) { List<String> translations = commandUtils.getTranslations(null, null, file, this.getProjectInfo(), propertiesBean, command, getPlaceholderUtil()); result.addAll(translations); } break; } } } return result; } public void help(String resultCmd) { if (null != resultCmd) { switch (resultCmd) { case "": cliOptions.cmdGeneralOptions(); break; case HELP: cliOptions.cmdHelpOptions(); break; case UPLOAD: case HELP_UPLOAD: cliOptions.cmdUploadOptions(); break; case UPLOAD_SOURCES: case HELP_UPLOAD_SOURCES: cliOptions.cmdUploadSourcesOptions(); break; case UPLOAD_TRANSLATIONS: case HELP_UPLOAD_TRANSLATIONS: cliOptions.cmdUploadTranslationsOptions(); break; case DOWNLOAD: case HELP_DOWNLOAD: cliOptions.cmdDownloadOptions(); break; case LIST: case HELP_LIST: cliOptions.cmdListOptions(); break; case LINT: case HELP_LINT: cliOptions.cmdLintOptions(); break; case LIST_PROJECT: case HELP_LIST_PROJECT: cliOptions.cmdListProjectOptions(); break; case LIST_SOURCES: case HELP_LIST_SOURCES: cliOptions.cmdListSourcesOptions(); break; case LIST_TRANSLATIONS: case HELP_LIST_TRANSLATIONS: cliOptions.cmdListTranslationsIOptions(); break; case GENERATE: case HELP_GENERATE: cliOptions.cmdGenerateOptions(); break; } } } private void dryrunSources(CommandLine commandLine) { List<String> files = this.list(SOURCES, "sources"); if (files.size() < 1) { ConsoleUtils.exitError(); } commandUtils.sortFilesName(files); String commonPath = ""; if (!propertiesBean.getPreserveHierarchy()) { commonPath = commandUtils.getCommonPath(files, propertiesBean); } if (commandLine.hasOption(COMMAND_TREE)) { DrawTree drawTree = new DrawTree(); List filesTree = new ArrayList(); for (String file : files) { if (propertiesBean.getPreserveHierarchy()) { filesTree.add(Utils.replaceBasePath(file, propertiesBean)); } else { StringBuilder resultFiles = new StringBuilder(); StringBuilder f = new StringBuilder(); String path = Utils.replaceBasePath(file, propertiesBean); if (Utils.isWindows()) { if (path.contains("\\")) { path = path.replaceAll("\\\\", "/"); path = path.replaceAll("/+", "/"); } if (commonPath.contains("\\")) { commonPath = commonPath.replaceAll("\\\\", "/"); commonPath = commonPath.replaceAll("/+", "/"); } } if (path.startsWith(commonPath)) { path = path.replaceFirst(commonPath, ""); } else if (path.startsWith("/" + commonPath)) { path = path.replaceFirst("/" + commonPath, ""); } if (Utils.isWindows() && path.contains("/")) { path = path.replaceAll("/", Utils.PATH_SEPARATOR_REGEX); } if (path.startsWith(Utils.PATH_SEPARATOR)) { path = path.replaceFirst(Utils.PATH_SEPARATOR_REGEX, ""); } String[] nodes = path.split(Utils.PATH_SEPARATOR_REGEX); for (String node : nodes) { if (node != null && !node.isEmpty()) { f.append(node).append(Utils.PATH_SEPARATOR); String preservePath = propertiesBean.getBasePath() + Utils.PATH_SEPARATOR + commonPath + Utils.PATH_SEPARATOR + f; preservePath = preservePath.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); File treeFile = new File(preservePath); if (treeFile.isDirectory()) { resultFiles.append(node).append(Utils.PATH_SEPARATOR); } else { resultFiles.append(node); } } } filesTree.add(resultFiles.toString()); } } if (branch != null) { System.out.println(branch); } int ident = propertiesBean.getPreserveHierarchy() ? -1 : 0; drawTree.draw(filesTree, ident); } else { String src; for (String file : files) { if (propertiesBean.getPreserveHierarchy()) { src = Utils.replaceBasePath(file, propertiesBean); if (branch != null && !branch.isEmpty()) { src = Utils.PATH_SEPARATOR + branch + Utils.PATH_SEPARATOR + src; } src = src.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); System.out.println(src); } else { src = Utils.replaceBasePath(file, propertiesBean); if (Utils.isWindows()) { if (src.contains("\\")) { src = src.replaceAll("\\\\", "/"); src = src.replaceAll("/+", "/"); } if (commonPath.contains("\\")) { commonPath = commonPath.replaceAll("\\\\", "/"); commonPath = commonPath.replaceAll("/+", "/"); } } if (src.startsWith(commonPath)) { src = src.replaceFirst(commonPath, ""); } else if (src.startsWith("/" + commonPath)) { src = src.replaceFirst("/" + commonPath, ""); } if (Utils.isWindows() && src.contains("/")) { src = src.replaceAll("/", Utils.PATH_SEPARATOR_REGEX); } if (branch != null && !branch.isEmpty()) { src = branch + Utils.PATH_SEPARATOR + src; } src = src.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); System.out.println(src); } } } } private void dryrunTranslation(CommandLine commandLine) { Set<String> translations = new HashSet<>(); List<Language> projectLanguages = getProjectInfo().getProjectLanguages(); Map<String, String> mappingTranslations = new HashMap<>(); for (Language projectLanguage : projectLanguages) { if (projectLanguage != null && projectLanguage.getId() != null) { // JSONObject languageInfo = commandUtils.getLanguageInfo(projectLanguage.getName(), supportedLanguages); String projectLanguageId = projectLanguage.getId(); mappingTranslations.putAll(commandUtils.doLanguagesMapping(getProjectInfo(), propertiesBean, projectLanguageId, getPlaceholderUtil())); } } String commonPath; String[] common = new String[mappingTranslations.values().size()]; common = mappingTranslations.values().toArray(common); commonPath = Utils.commonPath(common); for (Map.Entry<String, String> mappingTranslation : mappingTranslations.entrySet()) { String s = mappingTranslation.getValue().replaceAll("/+", Utils.PATH_SEPARATOR_REGEX); if (!propertiesBean.getPreserveHierarchy()) { if (s.startsWith(commonPath)) { s = s.replaceFirst(commonPath, ""); } } translations.add(s); } List<String> files = new ArrayList<>(translations); commandUtils.sortFilesName(files); if (commandLine.hasOption(COMMAND_TREE)) { DrawTree drawTree = new DrawTree(); int ident = -1; drawTree.draw(files, ident); } else { for (String file : files) { System.out.println(file); } } } private void dryrunProject(CommandLine commandLine) { List<String> files = this.list(PROJECT, "project"); List<String> filesWin = new ArrayList<>(); for (String file : files) { file = file.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX); filesWin.add(file); } commandUtils.sortFilesName(files); commandUtils.sortFilesName(filesWin); if (commandLine.hasOption(COMMAND_TREE)) { DrawTree drawTree = new DrawTree(); int ident = -1; drawTree.draw(filesWin, ident); } else { for (String file : files) { System.out.println(file.replaceAll(Utils.PATH_SEPARATOR_REGEX + "+", Utils.PATH_SEPARATOR_REGEX)); } } } private void lint() { if (cliConfig == null) { System.out.println(RESOURCE_BUNDLE.getString("configuration_file_empty")); ConsoleUtils.exitError(); } else { CliProperties cliProperties = new CliProperties(); PropertiesBean propertiesBean = cliProperties.loadProperties(cliConfig); PropertiesBean propertiesBeanIdentity = null; if (identityCliConfig != null) { propertiesBeanIdentity = cliProperties.loadProperties(identityCliConfig); } if (propertiesBean == null && propertiesBeanIdentity == null) { System.out.println(RESOURCE_BUNDLE.getString("configuration_file_empty")); ConsoleUtils.exitError(); } if (propertiesBean == null || propertiesBean.getProjectId() == null) { if (propertiesBeanIdentity == null || propertiesBeanIdentity.getProjectId() == null) { System.out.println(RESOURCE_BUNDLE.getString("error_missed_project_id")); ConsoleUtils.exitError(); } } if (propertiesBean == null || propertiesBean.getApiToken() == null) { if (propertiesBeanIdentity == null || propertiesBeanIdentity.getApiToken() == null) { System.out.println(RESOURCE_BUNDLE.getString("error_missed_api_token")); ConsoleUtils.exitError(); } } if (propertiesBean == null || propertiesBean.getBaseUrl() == null) { if (propertiesBeanIdentity == null || propertiesBeanIdentity.getBaseUrl() == null) { String baseUrl = Utils.getBaseUrl(); if (baseUrl == null || baseUrl.isEmpty()) { System.out.println(RESOURCE_BUNDLE.getString("missed_base_url")); ConsoleUtils.exitError(); } } } String basePath = null; if (propertiesBean == null || propertiesBean.getBasePath() == null) { if (propertiesBeanIdentity != null && propertiesBeanIdentity.getBasePath() != null) { basePath = propertiesBeanIdentity.getBasePath(); } } else { basePath = propertiesBean.getBasePath(); } if (basePath != null && !basePath.isEmpty()) { File base = new File(basePath); if (!base.exists()) { System.out.println(RESOURCE_BUNDLE.getString("bad_base_path")); ConsoleUtils.exitError(); } } if (propertiesBean == null) { System.out.println(MISSING_PROPERTY_BEAN.getString()); } else { if (propertiesBean.getFiles() == null) { System.out.println(RESOURCE_BUNDLE.getString("error_missed_section_files")); ConsoleUtils.exitError(); } else if (propertiesBean.getFiles().isEmpty()) { System.out.println(RESOURCE_BUNDLE.getString("empty_section_file")); ConsoleUtils.exitError(); } else { for (FileBean fileBean : propertiesBean.getFiles()) { if (fileBean.getSource() == null || fileBean.getSource().isEmpty()) { System.out.println(RESOURCE_BUNDLE.getString("error_empty_section_source_or_translation")); ConsoleUtils.exitError(); } if (fileBean.getTranslation() == null || fileBean.getTranslation().isEmpty()) { System.out.println(RESOURCE_BUNDLE.getString("error_empty_section_source_or_translation")); ConsoleUtils.exitError(); } } } } } System.out.println(RESOURCE_BUNDLE.getString("configuration_ok")); } }
package com.cx.plugin.utils; import com.cx.restclient.configuration.CxScanConfig; import com.cx.restclient.dto.ScanResults; import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.zip.ZipArchiver; import org.slf4j.Logger; import org.whitesource.fs.FSAConfigProperties; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.Arrays; import java.util.List; import static com.cx.plugin.CxScanPlugin.SOURCES_ZIP_NAME; public abstract class CxPluginUtils { public static void printLogo(Logger log) { // Designed by Gal Nussbaum <gal.nussbaum@checkmarx.com> log.info( " \n" + " CxCxCxCxCxCxCxCxCxCxCxC \n" + " CxCxCxCxCxCxCxCxCxCxCxCxCx \n" + " CxCxCxCxCxCxCxCxCxCxCxCxCxCx \n" + " CxCxCx CxCxCxCx \n" + " CxCxCx CxCxCxCx \n" + " CxCxCx CxCxCx CxCxCxCxC \n" + " CxCxCx xCxCxCx .CxCxCxCxCx \n" + " CxCxCx xCxCxCxCxCxCxCxCx \n" + " CxCxCx xCxCxCxCxCxCx \n" + " CxCxCx CxCxCxCxCx CxCxCx \n" + " CxCxCx xCxCxC CxCxCx \n" + " CxCxCx CxCxCx \n" + " CxCxCxCxCxCxCxCxCxCxCxCxCxCx \n" + " CxCxCxCxCxCxCxCxCxCxCxCxCx \n" + " CxCxCxCxCxCxCxCxCxCxCx \n" + " \n" + " C H E C K M A R X \n" ); } public static void printConfiguration(CxScanConfig config, String[] osaIgnoreScopes, String pluginVersion, Logger log) { log.info(" log.info("Maven plugin version: " + pluginVersion); log.info("Username: " + config.getUsername()); log.info("URL: " + config.getUrl()); log.info("Project name: " + config.getProjectName()); log.info("outputDirectory: " + config.getReportsDir()); log.info("Deny project creation: " + config.getDenyProject()); //todo check log.info("Scan timeout in minutes: " + (config.getSastScanTimeoutInMinutes() <= 0 ? "" : config.getSastScanTimeoutInMinutes())); log.info("Full team path: " + config.getTeamPath()); log.info("Preset: " + config.getPresetName()); log.info("Is incremental scan: " + config.getIncremental()); log.info("Folder exclusions: " + (config.getSastFolderExclusions())); log.info("Is synchronous scan: " + config.getSynchronous()); log.info("Generate PDF report: " + config.getGeneratePDFReport()); log.info("Policy violations enabled: " + config.getEnablePolicyViolations()); log.info("CxSAST thresholds enabled: " + config.getSastThresholdsEnabled()); if (config.getSastThresholdsEnabled()) { log.info("CxSAST high threshold: " + (config.getSastHighThreshold() == null ? "[No Threshold]" : config.getSastHighThreshold())); log.info("CxSAST medium threshold: " + (config.getSastMediumThreshold() == null ? "[No Threshold]" : config.getSastMediumThreshold())); log.info("CxSAST low threshold: " + (config.getSastLowThreshold() == null ? "[No Threshold]" : config.getSastLowThreshold())); } log.info("CxOSA enabled: " + config.getOsaEnabled()); if (config.getOsaEnabled()) { log.info("osaIgnoreScopes: " + Arrays.toString(osaIgnoreScopes)); log.info("CxOSA thresholds enabled: " + config.getOsaThresholdsEnabled()); if (config.getOsaThresholdsEnabled()) { log.info("CxOSA high threshold: " + (config.getOsaHighThreshold() == null ? "[No Threshold]" : config.getOsaHighThreshold())); log.info("CxOSA medium threshold: " + (config.getOsaMediumThreshold() == null ? "[No Threshold]" : config.getOsaMediumThreshold())); log.info("CxOSA low threshold: " + (config.getOsaLowThreshold() == null ? "[No Threshold]" : config.getOsaLowThreshold())); } } log.info(" //todo check log.info("fileExclusions: " + Arrays.toString(fileExclusions)); } public static void assertBuildFailure(String thDescription, ScanResults ret) throws MojoFailureException { StringBuilder builder = new StringBuilder(); builder.append("*****The Build Failed for the Following Reasons: *****"); appendError(ret.getGeneralException(), builder); appendError(ret.getSastCreateException(), builder); appendError(ret.getSastWaitException(), builder); appendError(ret.getOsaCreateException(), builder); appendError(ret.getOsaWaitException(), builder); String[] lines = thDescription.split("\\n"); for (String s : lines) { builder.append(s); } builder.append(" throw new MojoFailureException(builder.toString()); } private static StringBuilder appendError(Exception ex, StringBuilder builder) { if (ex != null) { builder.append(ex.getMessage()).append("\\n"); } return builder; } public static Integer resolveInt(String value, Logger log) { Integer inti = null; if (!StringUtils.isEmpty(value)) { try { inti = Integer.parseInt(value); } catch (NumberFormatException ex) { log.warn("failed to parse integer value: " + value); } } return inti; } public static File zipSources(List<MavenProject> projects, ZipArchiver zipArchiver, File outputDirectory, Logger log) throws MojoExecutionException { for (MavenProject p : projects) { MavenProject subProject = getProject(p); if ("pom".equals(subProject.getPackaging())) { continue; } String prefix = subProject.getName() + "\\"; //add sources List compileSourceRoots = subProject.getCompileSourceRoots(); File sourceDir = subProject.getBasedir();//todo check if java not exist (source not exist) for (Object c : compileSourceRoots) { sourceDir = new File((String) c); if (sourceDir.exists()) { zipArchiver.addDirectory(sourceDir, prefix); } } //add webapp sources File[] webappDir = sourceDir.getParentFile().listFiles(new FilenameFilter() { public boolean accept(File directory, String fileName) { return fileName.endsWith("webapp"); } }); if (webappDir.length > 0 && webappDir[0].exists()) { zipArchiver.addDirectory(webappDir[0], prefix); } //add resources List reSourceRoots = subProject.getResources(); for (Object c : reSourceRoots) { Resource resource = (Resource) c; File resourceDir = new File(resource.getDirectory()); if (resourceDir.exists()) { zipArchiver.addDirectory(resourceDir, prefix); } } //add scripts List scriptSourceRoots = subProject.getScriptSourceRoots(); for (Object c : scriptSourceRoots) { File scriptDir = new File((String) c); if (scriptDir.exists()) { zipArchiver.addDirectory(scriptDir, prefix); } } } zipArchiver.setDestFile(new File(outputDirectory, SOURCES_ZIP_NAME + ".zip")); try { zipArchiver.createArchive(); log.info("Sources zip location: " + outputDirectory + File.separator + SOURCES_ZIP_NAME + ".zip"); } catch (IOException e) { throw new MojoExecutionException("Failed to zip sources: ", e); } return new File(outputDirectory, SOURCES_ZIP_NAME + ".zip"); } private static MavenProject getProject(MavenProject p) { if (p.getExecutionProject() != null) { return p.getExecutionProject(); } return p; } public static FSAConfigProperties generateOSAScanConfiguration(String scanFolder, String[] osaIgnoreScopes, String dummyFilename) { FSAConfigProperties ret = new FSAConfigProperties(); ret.put("includes", dummyFilename); if (osaIgnoreScopes != null && osaIgnoreScopes.length > 0) { ret.put("maven.ignoredScopes", StringUtils.join(",", osaIgnoreScopes)); } ret.put("d", scanFolder); return ret; } }
package com.doctor.esper.event; import java.math.BigDecimal; import com.alibaba.fastjson.JSON; public class Withdrawal { private String account; private BigDecimal amount; public Withdrawal(String account, BigDecimal amount) { this.account = account; this.amount = amount; } public String getAccount() { return account; } public BigDecimal getAmount() { return amount; } public void setAccount(String account) { this.account = account; } public void setAmount(BigDecimal amount) { this.amount = amount; } @Override public String toString() { return JSON.toJSONString(this); } }
package com.easypost.model; import com.easypost.exception.EasyPostException; import com.easypost.net.EasyPostResource; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public final class CarrierAccount extends EasyPostResource { private String id; private String object; private String type; private Fields fields; private boolean clone; private String readable; private String description; private String reference; private String billingType; private Map<String, Object> credentials; private Map<String, Object> testCredentials; /** * Create a carrier account. * * @param params parameters to create. * @return created CarrierAccount object. * @throws EasyPostException when the request fails. */ public static CarrierAccount create(final Map<String, Object> params) throws EasyPostException { return create(params, null); } /** * Create a carrier account. * * @param params parameters to create. * @param apiKey API key to use in request (overrides default API key). * @return created CarrierAccount object. * @throws EasyPostException when the request fails. */ public static CarrierAccount create(final Map<String, Object> params, final String apiKey) throws EasyPostException { Map<String, Object> wrappedParams = new HashMap<String, Object>(); wrappedParams.put("carrier_account", params); return request(RequestMethod.POST, classURL(CarrierAccount.class), wrappedParams, CarrierAccount.class, apiKey); } /** * Retrieve a carrier account from the API. * * @param id id of the carrier account. * @return CarrierAccount object. * @throws EasyPostException when the request fails. */ public static CarrierAccount retrieve(final String id) throws EasyPostException { return retrieve(id, null); } /** * Retrieve a carrier account from the API. * * @param id id of the carrier account. * @param apiKey API key to use in request (overrides default API key). * @return CarrierAccount object. * @throws EasyPostException when the request fails. */ public static CarrierAccount retrieve(final String id, final String apiKey) throws EasyPostException { return request(RequestMethod.GET, instanceURL(CarrierAccount.class, id), null, CarrierAccount.class, apiKey); } /** * List all carrier accounts. * * @return List of CarrierAccount objects. * @throws EasyPostException when the request fails. */ public static List<CarrierAccount> all() throws EasyPostException { return all(null, null); } /** * List all carrier accounts. * * @param params filters to apply to the list. * @return List of CarrierAccount objects. * @throws EasyPostException when the request fails. */ public static List<CarrierAccount> all(final Map<String, Object> params) throws EasyPostException { return all(params, null); } /** * List all carrier accounts. * * @param params filters to apply to the list. * @param apiKey API key to use in request (overrides default API key). * @return List of CarrierAccount objects. * @throws EasyPostException when the request fails. */ public static List<CarrierAccount> all(final Map<String, Object> params, final String apiKey) throws EasyPostException { CarrierAccount[] response = request(RequestMethod.GET, classURL(CarrierAccount.class), params, CarrierAccount[].class, apiKey); return Arrays.asList(response); } /** * Get ID of the carrier account. * * @return ID of the carrier account. */ public String getId() { return id; } /** * Set ID of the carrier account. * * @param id ID of the carrier account. */ public void setId(final String id) { this.id = id; } /** * Get readable name of the carrier account. * * @return readable name of the carrier account. */ public String getReadable() { return readable; } /** * Set readable name of the carrier account. * * @param readable readable name of the carrier account. */ public void setReadable(final String readable) { this.readable = readable; } /** * Get description of the carrier account. * * @return description of the carrier account. */ public String getDescription() { return description; } /** * Set description of the carrier account. * * @param description description of the carrier account. */ public void setDescription(final String description) { this.description = description; } /** * Get reference of the carrier account. * * @return reference of the carrier account. */ public String getReference() { return reference; } /** * Set reference of the carrier account. * * @param reference reference of the carrier account. */ public void setReference(final String reference) { this.reference = reference; } /** * Set billing type of the carrier account. * * @param billingType billing type of the carrier account. */ public void setBillingType(final String billingType) { this.billingType = billingType; } /** * Get billing type of the carrier account. * * @return billing type of the carrier account. */ public String getBillingType() { return billingType; } /** * Get credentials of the carrier account. * * @return credentials of the carrier account. */ public Map<String, Object> getCredentials() { return credentials; } /** * Set credentials of the carrier account. * * @param credentials credentials of the carrier account. */ public void setCredentials(final Map<String, Object> credentials) { this.credentials = credentials; } /** * Get object type of the carrier account. * * @return object type of the carrier account. */ public String getObject() { return object; } /** * Set object type of the carrier account. * * @param object object type of the carrier account. */ public void setObject(String object) { this.object = object; } /** * Get type of the carrier account. * * @return type of the carrier account. */ public String getType() { return type; } /** * Set type of the carrier account. * * @param type type of the carrier account. */ public void setType(String type) { this.type = type; } /** * Get fields of the carrier account. * * @return fields of the carrier account. */ public Fields getFields() { return fields; } /** * Set fields of the carrier account. * * @param fields fields of the carrier account. */ public void setFields(Fields fields) { this.fields = fields; } /** * Get whether the carrier account is a clone. * * @return True if carrier account is a clone, false otherwise. */ public boolean isClone() { return clone; } /** * Set whether the carrier account is a clone. * * @param clone True if carrier account is a clone, false otherwise. */ public void setClone(boolean clone) { this.clone = clone; } /** * Get test credentials of the carrier account. * * @return test credentials of the carrier account. */ public Map<String, Object> getTestCredentials() { return testCredentials; } /** * Set test credentials of the carrier account. * * @param testCredentials test credentials of the carrier account. */ public void setTestCredentials(Map<String, Object> testCredentials) { this.testCredentials = testCredentials; } /** * Update this carrier account. * * @param params parameters to update. * @return updated carrier account. * @throws EasyPostException when the request fails. */ public CarrierAccount update(final Map<String, Object> params) throws EasyPostException { return this.update(params, null); } /** * Update this carrier account. * * @param params parameters to update. * @param apiKey API key to use in request (overrides default API key). * @return updated CarrierAccount object. * @throws EasyPostException when the request fails. */ public CarrierAccount update(final Map<String, Object> params, final String apiKey) throws EasyPostException { Map<String, Object> wrappedParams = new HashMap<String, Object>(); wrappedParams.put("carrier_account", params); CarrierAccount response = request(RequestMethod.PUT, instanceURL(CarrierAccount.class, this.getId()), wrappedParams, CarrierAccount.class, apiKey); this.merge(this, response); return this; } /** * Delete this carrier account. * * @throws EasyPostException when the request fails. */ public void delete() throws EasyPostException { this.delete(null); } /** * Delete this carrier account. * * @param apiKey API key to use in request (overrides default API key). * @throws EasyPostException when the request fails. */ public void delete(final String apiKey) throws EasyPostException { request(RequestMethod.DELETE, instanceURL(CarrierAccount.class, this.getId()), null, CarrierAccount.class, apiKey); } }
package com.github.davidmoten.rtree; import static com.google.common.base.Optional.of; import java.util.Comparator; import rx.Observable; import rx.functions.Func1; import com.github.davidmoten.util.ImmutableStack; import com.google.common.base.Optional; import com.google.common.collect.Lists; public class RTree { private final Optional<Node> root; private final Context context; private RTree(Optional<Node> root, Context context) { this.root = root; this.context = context; } private RTree(Node root, Context context) { this(of(root), context); } public RTree() { this(Optional.<Node> absent(), Context.DEFAULT); } public RTree(int maxChildren) { this(Optional.<Node> absent(), new Context(maxChildren, new QuadraticSplitter())); } public RTree(int maxChildren, Splitter splitter) { this(Optional.<Node> absent(), new Context(maxChildren, splitter)); } public static Builder builder() { return new Builder(); } public static class Builder { private int maxChildren = 8; private Splitter splitter = new QuadraticSplitter(); private Builder() { } public Builder maxChildren(int maxChildren) { this.maxChildren = maxChildren; return this; } public Builder splitter(Splitter splitter) { this.splitter = splitter; return this; } public RTree build() { return new RTree(maxChildren, splitter); } } public RTree add(Entry entry) { if (root.isPresent()) return new RTree(root.get().add(entry, ImmutableStack.<NonLeaf> empty()), context); else return new RTree(new Leaf(Lists.newArrayList(entry), context), context); } public Observable<Entry> search(Func1<Rectangle, Boolean> criterion, Optional<Comparator<Rectangle>> comparator) { if (root.isPresent()) return Observable.create(new OnSubscribeSearch(root.get(), criterion, comparator)); else return Observable.empty(); } public static final Comparator<Rectangle> ascendingDistance( final Rectangle r) { return new Comparator<Rectangle>() { @Override public int compare(Rectangle r1, Rectangle r2) { return ((Double) r.distance(r1)).compareTo(r.distance(r2)); } }; } public static final Comparator<Rectangle> descendingDistance( final Rectangle r) { return new Comparator<Rectangle>() { @Override public int compare(Rectangle r1, Rectangle r2) { return ((Double) r.distance(r2)).compareTo(r.distance(r1)); } }; } public static Func1<Rectangle, Boolean> overlaps(final Rectangle r) { return new Func1<Rectangle, Boolean>() { @Override public Boolean call(Rectangle rectangle) { return r.overlaps(rectangle); } }; } public Observable<Entry> nearest(Rectangle r) { return search(overlaps(r), of(ascendingDistance(r))); } public Observable<Entry> furthest(Rectangle r) { return search(overlaps(r), of(descendingDistance(r))); } public Observable<Entry> search(Func1<Rectangle, Boolean> criterion) { return search(criterion, Optional.<Comparator<Rectangle>> absent()); } public Observable<Entry> search(final Rectangle r) { return search(overlaps(r)); } public Observable<Entry> search(final Rectangle r, final double maxDistance) { return search(new Func1<Rectangle, Boolean>() { @Override public Boolean call(Rectangle rectangle) { return r.distance(rectangle) <= maxDistance; } }); } public Observable<Entry> entries() { return search(new Func1<Rectangle, Boolean>() { @Override public Boolean call(Rectangle rectangle) { return true; } }); } public Visualizer visualize(int width, int height, Rectangle view, int maxDepth) { return new Visualizer(this, width, height, view); } Optional<Node> root() { return root; } }
package com.greghaskins.spectrum; import java.util.ArrayDeque; import java.util.Deque; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.RunNotifier; public class Spectrum extends Runner { /** * A generic code block with a {@link #run()} method. * */ public static interface Block { /** * Execute the code block, raising any {@code Throwable} that may occur. * * @throws Throwable */ void run() throws Throwable; } /** * Declare a test suite to describe the expected behaviors of the system in a given context. * * @param context * Description of the test context * @param block * {@link Block} with one or more calls to {@link #it(String, Block) it} that define each expected behavior * */ public static void describe(final String context, final Block block) { final Context newContext = new Context(Description.createSuiteDescription(context)); enterContext(newContext, block); } /** * Declare a test for an expected behavior of the system. * * @param behavior * Description of the expected behavior * @param block * {@link Block} that verifies the system behaves as expected and throws a {@link java.lang.Throwable Throwable} * if that expectation is not met. */ public static void it(final String behavior, final Block block) { getCurrentContext().addTest(behavior, block); } public static void beforeEach(final Block block) { getCurrentContext().addTestSetup(block); } public static void afterEach(final Block block) { getCurrentContext().addTestTeardown(block); } public static void beforeAll(final Block block) { getCurrentContext().addContextSetup(block); } public static void afterAll(final Block block) { getCurrentContext().addContextTeardown(block); } public static <T> Value<T> value(@SuppressWarnings("unused") final Class<T> type) { return new Value<T>(null); } public static <T> Value<T> value(final T startingValue) { return new Value<T>(startingValue); } public static class Value<T> { public T value; private Value(final T value) { this.value = value; } } private static final Deque<Context> globalContexts = new ArrayDeque<Context>(); static { globalContexts.push(new Context(Description.createSuiteDescription("Spectrum tests"))); } private final Description description; private final Context rootContext; public Spectrum(final Class<?> testClass) { description = Description.createSuiteDescription(testClass); rootContext = new Context(description); enterContext(rootContext, new ConstructorBlock(testClass)); } @Override public Description getDescription() { return description; } @Override public void run(final RunNotifier notifier) { rootContext.execute(notifier); } private static void enterContext(final Context context, final Block block) { getCurrentContext().addChild(context); globalContexts.push(context); try { block.run(); } catch (final Throwable e) { it("encountered an error", new FailingBlock(e)); } globalContexts.pop(); } private static Context getCurrentContext() { return globalContexts.peek(); } }
package com.jcabi.aspects.aj; import com.jcabi.aspects.Loggable; import com.jcabi.log.Logger; import java.lang.reflect.Method; import java.util.Set; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; /** * Logs method calls. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 0.7.2 */ @Aspect @SuppressWarnings("PMD.AvoidCatchingThrowable") public final class MethodLogger { /** * Currently running methods. */ private final transient Set<MethodLogger.Marker> running = new ConcurrentSkipListSet<MethodLogger.Marker>(); /** * Service that monitors. */ private final transient ScheduledExecutorService monitor = Executors.newScheduledThreadPool(1); /** * Public ctor. */ @SuppressWarnings("PMD.DoNotUseThreads") public MethodLogger() { this.monitor.scheduleWithFixedDelay( new Runnable() { @Override public void run() { for (MethodLogger.Marker marker : MethodLogger.this.running) { marker.monitor(); } } }, 1, 1, TimeUnit.SECONDS ); } @Around("((execution(public * (@com.jcabi.aspects.Loggable *).*(..)) || initialization((@com.jcabi.aspects.Loggable *).new(..))) && !execution(String *.toString()) && !execution(int *.hashCode()) && !execution(boolean *.equals(Object)))") public Object wrapClass(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); Object output; if (method.isAnnotationPresent(Loggable.class)) { output = point.proceed(); } else { output = this.wrap( point, method, method.getDeclaringClass().getAnnotation(Loggable.class) ); } return output; } @Around("(execution(* *(..)) || initialization(*.new(..))) && @annotation(com.jcabi.aspects.Loggable)") @SuppressWarnings("PMD.AvoidCatchingThrowable") public Object wrapMethod(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); return this.wrap(point, method, method.getAnnotation(Loggable.class)); } private Object wrap(final ProceedingJoinPoint point, final Method method, final Loggable annotation) throws Throwable { final long start = System.nanoTime(); final MethodLogger.Marker marker = new MethodLogger.Marker(point, annotation); this.running.add(marker); try { final Object result = point.proceed(); final Class<?> type = method.getDeclaringClass(); final int limit = annotation.limit(); int level = annotation.value(); final long nano = System.nanoTime() - start; final boolean over = nano > annotation.unit().toNanos(limit); if (MethodLogger.enabled(level, type) || over) { final StringBuilder msg = new StringBuilder(); msg.append(Mnemos.toString(point, annotation.trim())) .append(':'); if (!method.getReturnType().equals(Void.TYPE)) { msg.append(" returned ") .append(Mnemos.toString(result, annotation.trim())); } msg.append(Logger.format(" in %[nano]s", nano)); if (over) { level = Loggable.WARN; msg.append(" (too slow!)"); } MethodLogger.log( level, type, msg.toString() ); } return result; } catch (Throwable ex) { MethodLogger.log( Loggable.ERROR, method.getDeclaringClass(), Logger.format( "%s: thrown %[type]s (%s) in %[nano]s", Mnemos.toString(point, annotation.trim()), ex, Mnemos.toString(ex.getMessage(), false), System.nanoTime() - start ) ); throw ex; } finally { this.running.remove(marker); } } /** * Log one line. * @param level Level of logging * @param log Destination log * @param message Message to log */ private static void log(final int level, final Class<?> log, final String message) { if (level == Loggable.TRACE) { Logger.trace(log, message); } else if (level == Loggable.DEBUG) { Logger.debug(log, message); } else if (level == Loggable.INFO) { Logger.info(log, message); } else if (level == Loggable.WARN) { Logger.warn(log, message); } else if (level == Loggable.ERROR) { Logger.error(log, message); } } /** * Log level is enabled? * @param level Level of logging * @param log Destination log * @return TRUE if enabled */ private static boolean enabled(final int level, final Class<?> log) { boolean enabled; if (level == Loggable.TRACE) { enabled = Logger.isTraceEnabled(log); } else if (level == Loggable.DEBUG) { enabled = Logger.isDebugEnabled(log); } else if (level == Loggable.INFO) { enabled = Logger.isInfoEnabled(log); } else if (level == Loggable.WARN) { enabled = Logger.isWarnEnabled(log); } else { enabled = true; } return enabled; } /** * Marker of a running method. */ private static final class Marker implements Comparable<MethodLogger.Marker> { /** * When started. */ private final transient long start; /** * Joint point. */ private final transient ProceedingJoinPoint point; /** * Annotation. */ private final transient Loggable annotation; /** * Public ctor. * @param pnt Joint point * @param annt Annotation */ public Marker(final ProceedingJoinPoint pnt, final Loggable annt) { this.start = System.currentTimeMillis(); this.point = pnt; this.annotation = annt; } /** * Monitor it's status and log the problem, if any. */ public void monitor() { final long age = System.currentTimeMillis() - this.start; final long threshold = this.annotation.unit().toMillis( this.annotation.limit() ); if (age > threshold) { final Method method = MethodSignature.class.cast( this.point.getSignature() ).getMethod(); Logger.warn( method.getDeclaringClass(), "%s: takes more than %[ms]s (%[ms]s already)", Mnemos.toString(this.point, true), threshold, age ); } } /** * {@inheritDoc} */ @Override public int hashCode() { return this.point.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(final Object obj) { return obj == this || MethodLogger.Marker.class.cast(obj) .point.equals(this.point); } /** * {@inheritDoc} */ @Override public int compareTo(final Marker marker) { int diff; if (marker.start > this.start) { diff = 1; } else if (marker.start < this.start) { diff = -1; } else { diff = 0; } return diff; } } }
package com.minelittlepony.pony.data; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.minelittlepony.MineLittlePony; import com.minelittlepony.ducks.IRenderPony; import com.voxelmodpack.hdskins.resources.texture.IBufferedTexture; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.ITextureObject; import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.client.resources.IResource; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @Immutable public class Pony implements IPony { private static final AtomicInteger ponyCount = new AtomicInteger(); private final int ponyId = ponyCount.getAndIncrement(); private final ResourceLocation texture; private final IPonyData metadata; public Pony(ResourceLocation resource) { texture = resource; metadata = checkSkin(texture); } private IPonyData checkSkin(ResourceLocation resource) { IPonyData data = checkPonyMeta(resource); if (data != null) { return data; } BufferedImage skinImage = Preconditions.checkNotNull(getBufferedImage(resource), "bufferedImage: " + resource); return this.checkSkin(skinImage); } @Nullable private IPonyData checkPonyMeta(ResourceLocation resource) { try { IResource res = Minecraft.getMinecraft().getResourceManager().getResource(resource); if (res.hasMetadata()) { PonyData data = res.getMetadata(PonyDataSerialiser.NAME); if (data != null) { return data; } } } catch (FileNotFoundException e) { // Ignore uploaded texture } catch (IOException e) { MineLittlePony.logger.warn("Unable to read {} metadata", resource, e); } return null; } @Nullable public static BufferedImage getBufferedImage(@Nonnull ResourceLocation resource) { try { IResource skin = Minecraft.getMinecraft().getResourceManager().getResource(resource); BufferedImage skinImage = TextureUtil.readBufferedImage(skin.getInputStream()); MineLittlePony.logger.debug("Obtained skin from resource location {}", resource); return skinImage; } catch (IOException ignored) { } ITextureObject texture = Minecraft.getMinecraft().getTextureManager().getTexture(resource); if (texture instanceof IBufferedTexture) { return ((IBufferedTexture) texture).getBufferedImage(); } return null; } private IPonyData checkSkin(BufferedImage bufferedimage) { MineLittlePony.logger.debug("\tStart skin check for pony #{} with image {}.", ponyId, bufferedimage); return PonyData.parse(bufferedimage); } @Override public boolean isFlying(EntityLivingBase entity) { return !(entity.onGround || entity.isRiding() || (entity.isOnLadder() && !(entity instanceof EntityPlayer && ((EntityPlayer)entity).capabilities.isFlying)) || entity.isInWater() || entity.isPlayerSleeping()); } @Override public boolean isSwimming(EntityLivingBase entity) { return isFullySubmerged(entity) && !(entity.onGround || entity.isOnLadder()); } @Override public boolean isFullySubmerged(EntityLivingBase entity) { return entity.isInWater() && entity.getEntityWorld().getBlockState(new BlockPos(getVisualEyePosition(entity))).getMaterial() == Material.WATER; } protected Vec3d getVisualEyePosition(EntityLivingBase entity) { PonySize size = entity.isChild() ? PonySize.FOAL : metadata.getSize(); return new Vec3d(entity.posX, entity.posY + (double) entity.getEyeHeight() * size.getScaleFactor(), entity.posZ); } @Override public boolean isWearingHeadgear(EntityLivingBase entity) { ItemStack stack = entity.getItemStackFromSlot(EntityEquipmentSlot.HEAD); if (stack.isEmpty()) { return false; } Item item = stack.getItem(); return !(item instanceof ItemArmor) || ((ItemArmor) item).getEquipmentSlot() != EntityEquipmentSlot.HEAD; } @Override public PonyRace getRace(boolean ignorePony) { return metadata.getRace().getEffectiveRace(ignorePony); } @Override public ResourceLocation getTexture() { return texture; } @Override public IPonyData getMetadata() { return metadata; } @Override public boolean isRidingInteractive(EntityLivingBase entity) { return MineLittlePony.getInstance().getRenderManager().getPonyRenderer(entity.getRidingEntity()) != null; } @Override public IPony getMountedPony(EntityLivingBase entity) { Entity mount = entity.getRidingEntity(); IRenderPony<EntityLivingBase> render = MineLittlePony.getInstance().getRenderManager().getPonyRenderer(mount); return render == null ? null : render.getEntityPony((EntityLivingBase)mount); } @Override public Vec3d getAbsoluteRidingOffset(EntityLivingBase entity) { IPony ridingPony = getMountedPony(entity); if (ridingPony != null) { EntityLivingBase ridee = (EntityLivingBase)entity.getRidingEntity(); Vec3d offset = ridingPony.getMetadata().getSize().getTranformation().getRiderOffset(); float scale = ridingPony.getMetadata().getSize().getScaleFactor(); return ridingPony.getAbsoluteRidingOffset(ridee) .add(0, offset.y - ridee.height * 1/scale, 0); } return entity.getPositionVector(); } @Override public AxisAlignedBB getComputedBoundingBox(EntityLivingBase entity) { float scale = getMetadata().getSize().getScaleFactor() + 0.1F; Vec3d pos = getAbsoluteRidingOffset(entity); float width = entity.width * scale; return new AxisAlignedBB( - width, (entity.height * scale), -width, width, 0, width).offset(pos); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("texture", texture) .add("metadata", metadata) .toString(); } }
package com.ning.admin.action; import com.ning.admin.service.AdminService; import com.ning.exception.file.FileException; import com.ning.file.entity.History; import com.ning.file.entity.OrderInfo; import com.ning.file.service.FileService; import com.ning.util.properties.PropertiesUtil; import org.apache.commons.io.IOUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Action * * @author wangn * @date 2017/5/23 */ @Controller public class AdminAction { private static final String O_STATE = "ostate"; @Resource private FileService fileService; @Resource private AdminService adminService; /** * * * * @param model * @return jsp/admin.jsp */ @RequestMapping("admin") @RequiresPermissions("admin") public String admin(Model model) { model.addAttribute("orderInfoList", fileService.getOrderInfoEntityOfAll()); //User model.addAttribute("user", SecurityUtils.getSubject().getPrincipal()); return "jsp/admin.jsp"; } /** * * * @param subject * @return * @throws Exception Exception */ @RequestMapping("getOnameBysubjectOfAll") public @ResponseBody List<OrderInfo> getOnameBysubjectOfAll(String subject) throws Exception { if (subject == null || "".equals(subject)) { throw new FileException(""); } return fileService.getOnameBysubjectOfAll(subject); } /** * * * * @param model * @return jsp/subjectui.jsp */ @RequestMapping("subjectui") @RequiresPermissions("admin") public String subjectui(Model model) { //OrderInfo model.addAttribute("allOrderInfo", adminService.getOrderInfoEntity()); return "jsp/subjectui.jsp"; } /** * * * * @param hoid ID * @param model * @param session HttpSession * @return jsp/downfileui.jsp * @throws Exception Exception */ @RequestMapping("getFileList") @RequiresPermissions("admin") public String getFileList(Integer hoid, Model model, HttpSession session) throws Exception { if (hoid == null) { throw new FileException("hoid"); } //Session session.setAttribute("hoid", hoid); List<History> list = adminService.getAllUploadedByHoid(hoid); model.addAttribute("fileListByHoid", list); return "jsp/downfileui.jsp"; } /** * * * * @param response HttpServletResponse * @param session HttpSession * @throws Exception Exception */ @RequestMapping("downAllFile") @RequiresPermissions("admin") public void downAllFile(HttpServletResponse response, HttpSession session) throws Exception { List<History> fileListByHoid = adminService.findFileListByHoid((Integer) session.getAttribute("hoid")); if (fileListByHoid == null) { throw new FileException(""); } OrderInfo orderInfo = fileService.getOrderInfoEntityByOID(fileListByHoid.get(0).getHoid()); String filteredOname = PropertiesUtil.filterOutUrl(orderInfo.getOname()); String zipfilename = orderInfo.getOsubject() + "_" + filteredOname; List<String> filesname = new ArrayList<>(fileListByHoid.size()); for (History history : fileListByHoid) { filesname.add(history.getFilepath()); } response.setHeader("Content-Disposition", "attachment;filename=" + new String((zipfilename + ".zip").getBytes(), StandardCharsets.ISO_8859_1)); response.setContentType("application/octet-stream"); ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream()); for (String filename : filesname) { File file = new File(PropertiesUtil.getUpLoadFilePath() + filename); InputStream input = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(file.getName())); IOUtils.copy(input, zipOut); input.close(); } zipOut.close(); } @RequestMapping("updateDeadlineByOID") @RequiresPermissions("admin") public @ResponseBody Boolean updateDeadlineByOID(Integer oid, Date deadlineDate) throws Exception{ if (oid == null || deadlineDate == null){ throw new FileException(""); } Map<String, Object> map = new HashMap<>(2); map.put("odeadline", deadlineDate); map.put("oid", oid); adminService.updateDeadlineByOID(map); return true; } /** * * * * @param oid ID * @param key key * @param value value * @return * @throws Exception Exception */ @RequestMapping("changeKeyByOID") @RequiresPermissions("admin") public @ResponseBody Boolean changeKeyByOID(Integer oid, String key, String value) throws Exception { if (oid == null || key == null || "".equals(key) || value == null || "".equals(value)) { throw new FileException(""); } Map<String, Object> map = new HashMap<>(2); map.put("oid", oid); if (O_STATE.equals(key)) { map.put(key, Boolean.parseBoolean(value)); } else { map.put(key, value); } adminService.changeKeyByOID(map); return true; } @RequestMapping("updateOrderByOID") @RequiresPermissions("admin") public @ResponseBody Boolean updateOrderByOID(Integer oid, String osubject, String oname, String ostate, String odeadlinestr) throws Exception{ if (oid == null || osubject == null || "".equals(osubject) || oname == null || "".equals(oname) || ostate == null || "".equals(ostate) || odeadlinestr == null || "".equals(odeadlinestr)) { throw new FileException(""); } Map<String, Object> map = new HashMap<>(6); map.put("oid", oid); map.put("osubject", osubject); map.put("oname", oname); map.put("ostate", Boolean.parseBoolean(ostate)); map.put("otime", new Date()); map.put("odeadline", new Date(Long.parseLong(odeadlinestr) * 1000)); adminService.updateOrderByOID(map); return true; } /** * ID * * * @param oid ID * @return ResponseBody * @throws Exception Exception */ @RequestMapping("delOrderinfoByOID") @RequiresPermissions("admin") public @ResponseBody Boolean delOrderinfoByOID(Integer oid) throws Exception { if (oid == null) { throw new FileException(""); } adminService.delOrderInfosAndFilesByOID(oid); return true; } /** * * * * @param orderInfo * @return * @throws Exception Exception */ @RequestMapping("addOrderInfo") @RequiresPermissions("admin") public @ResponseBody Boolean addOrderInfo(OrderInfo orderInfo) throws Exception { if (orderInfo == null) { throw new FileException(""); } if (orderInfo.getOsubject() == null || "".equals(orderInfo.getOsubject())) { return false; } if (orderInfo.getOname() == null) { return false; } if (orderInfo.getOstate() == null) { return false; } if (orderInfo.getOdeadlinestr() == null){ return false; } int oid = (orderInfo.getOname().hashCode()) + (orderInfo.getOsubject().hashCode()); orderInfo.setOid(oid); orderInfo.setOtime(new Date()); orderInfo.setOdeadlineFromStr(orderInfo.getOdeadlinestr()); adminService.addOrderInfo(orderInfo); return true; } }
package com.ninty.classfile; import com.ninty.classfile.constantpool.ConstantInfo; import com.ninty.classfile.constantpool.ConstantPoolInfos; import java.nio.ByteBuffer; public class AttributeInfo { static AttributeInfo generate(ConstantPoolInfos cps, ByteBuffer bb) { String name = cps.getUtf8(bb); switch (name) { case "Code": return new AttrCode(cps, bb); case "Deprecated": return new AttrDeprecated(bb); case "Synthetic": return new AttrSynthetic(bb); case "SourceFile": return new AttrSourceFile(cps, bb); case "ConstantValue": return new AttrConstantValue(bb); case "Exceptions": return new AttrExceptions(cps, bb); case "LineNumberTable": return new AttrLineNumberTable(bb); case "LocalVariableTable": return new AttrLocalVariableTable(cps, bb); case "BootstrapMethods": return new AttrBootstrapMethods(cps, bb); case "Signature": return new Signature(cps, bb); case "RuntimeVisibleAnnotations": return new AnnotationAttr.RuntimeVisibleAnnotations(cps, bb); case "RuntimeInvisibleAnnotations": return new AnnotationAttr.RuntimeInvisibleAnnotations(cps, bb); default: return new UnkonwAttr(name, bb); } } void skip(ByteBuffer bb, int len) { bb.position(bb.position() + len); } void skipAttributeLen(ByteBuffer bb) { skip(bb, 4); } static class UnkonwAttr extends AttributeInfo { private String name; UnkonwAttr(String name, ByteBuffer bb) { this.name = name; long len = bb.getInt(); skip(bb, (int) len); } } static class AttrDeprecated extends AttributeInfo { AttrDeprecated(ByteBuffer bb) { bb.getInt(); // must be 0 } } static class AttrSynthetic extends AttributeInfo { AttrSynthetic(ByteBuffer bb) { bb.getInt(); // must be 0 } } public static class AttrSourceFile extends AttributeInfo { public String sourceFile; AttrSourceFile(ConstantPoolInfos cps, ByteBuffer bb) { skipAttributeLen(bb); sourceFile = cps.getUtf8(bb); } } public static class AttrConstantValue extends AttributeInfo { private int constantValueIndex; AttrConstantValue(ByteBuffer bb) { skipAttributeLen(bb); constantValueIndex = bb.getChar(); } public int getConstantValueIndex() { return constantValueIndex; } } static class AttrExceptions extends AttributeInfo { String[] exceptionNames; AttrExceptions(ConstantPoolInfos cps, ByteBuffer bb) { skipAttributeLen(bb); int count = bb.getChar(); exceptionNames = new String[count]; for (int i = 0; i < count; i++) { exceptionNames[i] = cps.getClassName(bb.getChar()); } } } public static class AttrLineNumberTable extends AttributeInfo { public LineNumberTable[] lineNumberTables; AttrLineNumberTable(ByteBuffer bb) { skipAttributeLen(bb); int count = bb.getChar(); lineNumberTables = new LineNumberTable[count]; for (int i = 0; i < count; i++) { lineNumberTables[i] = new LineNumberTable(bb); } } } static class AttrLocalVariableTable extends AttributeInfo { LocalVariable[] localVariables; AttrLocalVariableTable(ConstantPoolInfos cps, ByteBuffer bb) { skipAttributeLen(bb); int count = bb.getChar(); localVariables = new LocalVariable[count]; for (int i = 0; i < count; i++) { localVariables[i] = new LocalVariable(cps, bb); } } } public static class AttrCode extends AttributeInfo { public int maxStack; public int maxLocals; public byte[] codes; public ExceptionTable[] exceptionTables; private AttributeInfo[] attributeInfos; AttrCode(ConstantPoolInfos cps, ByteBuffer bb) { skipAttributeLen(bb); maxStack = bb.getChar(); maxLocals = bb.getChar(); codes = new byte[bb.getInt()]; bb.get(codes); int exceptionCount = bb.getChar(); exceptionTables = new ExceptionTable[exceptionCount]; for (int i = 0; i < exceptionCount; i++) { exceptionTables[i] = new ExceptionTable(bb); } int attrCount = bb.getChar(); attributeInfos = new AttributeInfo[attrCount]; for (int i = 0; i < attrCount; i++) { attributeInfos[i] = AttributeInfo.generate(cps, bb); } } public AttrLineNumberTable getAttrLineNumberTable() { for (AttributeInfo attr : attributeInfos) { if (attr instanceof AttrLineNumberTable) { return (AttrLineNumberTable) attr; } } return null; } } public static class LineNumberTable { public int startPC; public int lineNumber; LineNumberTable(ByteBuffer bb) { startPC = bb.getChar(); lineNumber = bb.getChar(); } } private static class LocalVariable { int startPC; int length; String name; String desc; int index; LocalVariable(ConstantPoolInfos cps, ByteBuffer bb) { startPC = bb.getChar(); length = bb.getChar(); name = cps.getUtf8(bb); desc = cps.getUtf8(bb); index = bb.getChar(); } } public static class ExceptionTable { public int startPc; public int endPc; public int handlerPc; public int catchType; ExceptionTable(ByteBuffer bb) { startPc = bb.getChar(); endPc = bb.getChar(); handlerPc = bb.getChar(); catchType = bb.getChar(); } } public static class AttrBootstrapMethods extends AttributeInfo { public BootstrapMethodInfo[] bootstarpMethods; AttrBootstrapMethods(ConstantPoolInfos cps, ByteBuffer bb) { skipAttributeLen(bb); int num = bb.getChar(); bootstarpMethods = new BootstrapMethodInfo[num]; for (int i = 0; i < num; i++) { bootstarpMethods[i] = new BootstrapMethodInfo(cps, bb); } } } public static class BootstrapMethodInfo { public int bmhIndex; public ConstantInfo[] arguments; BootstrapMethodInfo(ConstantPoolInfos cps, ByteBuffer bb) { bmhIndex = bb.getChar(); int argNum = bb.getChar(); arguments = new ConstantInfo[argNum]; for (int i = 0; i < argNum; i++) { int cpIndex = bb.getChar(); arguments[i] = cps.get(cpIndex); } } } public static class Signature extends AttributeInfo{ public String signature; Signature(ConstantPoolInfos cps, ByteBuffer bb){ skipAttributeLen(bb); int index = bb.getChar(); signature = cps.getUtf8(index); } } }
package com.noodlesandwich.streams; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.common.base.Function; import com.google.common.base.Predicate; /** * <p>A Stream is an immutable structure similar to a linked list in design. Once created, the stream cannot be altered, * and any operation performed on it will create a new stream. The only way to access the data in a stream is to * iterate over it, either by using a <em>for each</em> loop, or by retrieving the {@link #iterator() iterator} * directly, or by using the {@link #head()} or {@link #tail()} methods to access the head or the tail of the stream. * In addition, the majority of the operations provided are lazy &mdash; that is, they will not be evaluated until the * stream is iterated over or the values within the stream are accessed.</p> * * <p>Streams are designed to be used with immutable data types. As the stream itself cannot be manipulated, using only * immutable types ensures no other code will alter the underlying values within the stream once it has been created, * ensuring thread safety.</p> * * <p>The {@link Streams} class provides static methods that can be used to easily construct a Stream.</p> **/ public interface Stream<T> extends Iterable<T> { /** * Returns <code>true</code> if the stream is nil (has no elements); <code>false</code> otherwise. */ boolean isNil(); /** * Returns the head (the first element) of the stream. */ T head(); /** * Returns the stream that contains the tail (the second element onwards) of the stream. */ Stream<T> tail(); /** * Transforms all the values in the stream by applying the function to each one and creating a new stream with the * results of the function. */ <U> Stream<U> map(Function<? super T, ? extends U> function); /** * Filters the stream by applying the predicate to each element and removing those for which it returns false. */ Stream<T> filter(Predicate<? super T> predicate); /** * <p>Reduces the stream to a single object by combining each successive element of the stream with the previous * using a function. The first value is combined with the initializer provided.</p> * * <p><code>foldLeft</code> works over the stream from left to right.</p> */ <A> A foldLeft(FoldLeftFunction<A, ? super T> foldFunction, A initializer); /** * <p>Reduces the stream to a single object by combining each successive element of the stream with the previous * using a function. The first value is combined with the initializer provided.</p> * * <p><code>foldRight</code> works over the stream from right to left.</p> */ <A> A foldRight(FoldRightFunction<? super T, A> foldFunction, A initializer); /** * Returns a new stream containing the first <code>n</code> elements of this stream. */ Stream<T> take(int n); /** * Returns a new stream that skips the first <code>n</code> elements of this stream. */ Stream<T> drop(int n); /** * Returns a new stream containing the all the elements up to but not including the first element for which the * predicate returns false. */ Stream<T> takeWhile(Predicate<? super T> predicate); /** * Returns a new stream containing the all the elements after and including the first element for which the * predicate returns false. */ Stream<T> dropWhile(Predicate<? super T> predicate); /** * Concatenates two streams. */ Stream<T> concat(Stream<T> nextStream); /** * <p>Zips one stream with another stream by combining each element in one with the element in the same position of * the other. Each element of the new stream will be a {@link Pair} containing the corresponding elements in the two * streams.</p> * * <p>The stream returned will be the length of the shorter of the two streams. If one is longer than the other, any * elements after this will be ignored.</p> */ <U> Stream<Pair<T, U>> zip(Stream<U> pairedStream); /** * <p>Zips one stream with another stream by combining each element in one with the element in the same position of * the other. Each element of the new stream will be the result of applying the function to the corresponding * elements in the two streams.</p> * * <p>The stream returned will be the length of the shorter of the two streams. If one is longer than the other, any * elements after this will be ignored.</p> */ <U, V> Stream<V> zipWith(Stream<U> pairedStream, ZipWithFunction<? super T, ? super U, ? extends V> zipWithFunction); /** * Returns <code>true</code> if any element in the stream matches the predicate; <code>false</code> otherwise. If * there are no elements in the list, <code>false</code> is returned. */ boolean any(Predicate<? super T> predicate); /** * Returns <code>true</code> if all elements in the stream match the predicate; <code>false</code> otherwise. If * there are no elements in the list, <code>true</code> is returned. */ boolean all(Predicate<? super T> predicate); /** * Returns <code>true</code> if the stream contains an element which is equal to the object; <code>false</code> * otherwise. */ boolean contains(T object); /** * Strips all duplicate elements from the stream. <code>unique()</code> will always remove duplicate elements after * the first in order to guarantee a stable result. */ Stream<T> unique(); /** * <p>Unions this stream with another. This creates a stream which contains all entries found in either stream.</p> * * <p><code>union</code> is a set operation, and as such all duplicate entries will be removed in the process.</p> */ Stream<T> union(Stream<T> unionedStream); /** * <p>Intersects this stream with another. This creates a stream which contains all entries found in both * streams.</p> * * <p><code>intersect</code> is a set operation, and as such all duplicate entries will be removed in the * process.</p> */ Stream<T> intersect(Stream<T> intersectedStream); /** * Removes all entries from the stream which are found in the stream provided. */ Stream<T> except(Stream<T> exceptedStream); /** * <p>Creates a new stream containing all entries found in only one of this stream and the other stream. Any entries * found in both will be discarded.</p> * * <p><code>symmetricDifference</code> is a set operation, and as such all duplicate entries will be removed in the * process.</p> */ Stream<T> symmetricDifference(Stream<T> otherStream); /** * <p>Calculates the size of the stream.</p> * * <p><strong>Warning:</strong> As the stream does not know its size, this is potentially an expensive operation, as * it can only be found by traversing the entire stream. If the stream is infinite, this will cause a stack * overflow.</p> */ int size(); /** * <p>Reverses the stream.</p> * * <p><strong>Warning:</strong> This is potentially an expensive operation, as it can only be done by traversing the * entire stream. If the stream is very large or infinite, operations that attempt to retrieve values from the * reversed stream will never return.</p> */ Stream<T> reverse(); /** * <p>Sorts the stream using the natural ordering of the elements. If the type of the stream has no natural * ordering (i.e. it does not implement {@link Comparable}), this will throw a {@link ClassCastException}.</p> * * <p><strong>Warning:</strong> This is potentially an expensive operation, as it can only be done by traversing the * entire stream. If the stream is very large or infinite, operations that attempt to retrieve values from the * sorted stream will cause a stack overflow.</p> */ Stream<T> sort(); /** * <p>Sorts the stream using a comparator.</p> * * <p><strong>Warning:</strong> This is potentially an expensive operation, as it can only be done by traversing the * entire stream. If the stream is very large or infinite, operations that attempt to retrieve values from the * sorted stream will cause a stack overflow.</p> */ Stream<T> sort(Comparator<? super T> comparator); /** * <p>Sorts the stream using a comparable entity which can be derived from each element.</p> * * <p><strong>Warning:</strong> This is potentially an expensive operation, as it can only be done by traversing the * entire stream. If the stream is very large or infinite, operations that attempt to retrieve values from the * sorted stream will cause a stack overflow.</p> */ <U extends Comparable<U>> Stream<T> sortBy(Function<? super T, ? extends U> function); /** * <p>Sorts the stream using an entity which can be derived from each element and a comparator.</p> * * <p><strong>Warning:</strong> This is potentially an expensive operation, as it can only be done by traversing the * entire stream. If the stream is very large or infinite, operations that attempt to retrieve values from the * sorted stream will cause a stack overflow.</p> */ <U> Stream<T> sortBy(Function<? super T, ? extends U> function, Comparator<? super U> comparator); /** * <p>Groups the entities in the stream using a computed map, deriving the keys using the function provided.</p> * * <p><strong>Warning:</strong> The map returned does not fully abide by the contract. In particular, you are * advised against asking it whether it contains particular keys/values or retrieving the key set, value set or * entry set, as the results may not be correct and can change over the lifetime of the map. Because of this, the * type of the object returned by this method will probably change in the future.</p> */ <K> java.util.Map<K, Stream<T>> groupBy(Function<? super T, ? extends K> keyFunction); /** * Converts the stream to an array. */ T[] toArray(Class<T> type); /** * Converts the stream to a {@link java.util.List}. */ List<T> toList(); /** * Converts the stream to a {@link java.util.Set}. */ Set<T> toSet(); /** * Converts the stream to a {@link java.util.Map Map} using the elements as keys, and a function which derives the * value. */ <V> java.util.Map<T, V> toMap(Function<? super T, ? extends V> valueFunction); /** * Returns a one-use, forwards-only {@link Iterator} which can be used to traverse the stream. */ @Override Iterator<T> iterator(); }
package com.sleekbyte.tailor.common; import com.sleekbyte.tailor.listeners.BlankLineListener; import com.sleekbyte.tailor.listeners.BraceStyleListener; import com.sleekbyte.tailor.listeners.CommentAnalyzer; import com.sleekbyte.tailor.listeners.ConstantNamingListener; import com.sleekbyte.tailor.listeners.FileListener; import com.sleekbyte.tailor.listeners.ForceTypeCastListener; import com.sleekbyte.tailor.listeners.KPrefixListener; import com.sleekbyte.tailor.listeners.LowerCamelCaseListener; import com.sleekbyte.tailor.listeners.MultipleImportListener; import com.sleekbyte.tailor.listeners.RedundantParenthesesListener; import com.sleekbyte.tailor.listeners.SemicolonTerminatedListener; import com.sleekbyte.tailor.listeners.UpperCamelCaseListener; import com.sleekbyte.tailor.listeners.WhitespaceListener; import com.sleekbyte.tailor.utils.ArgumentParser; /** * Enum for all rules implemented in Tailor. */ public enum Rules { UPPER_CAMEL_CASE("upper-camel-case", UpperCamelCaseListener.class.getName(), "class, enum, enum value, struct, and protocol names should follow UpperCamelCase naming convention."), TERMINATING_SEMICOLON("terminating-semicolon", SemicolonTerminatedListener.class.getName(), "Statements should not be terminated by semicolons."), REDUNDANT_PARENTHESES("redundant-parentheses", RedundantParenthesesListener.class.getName(), "Control flow " + "constructs, exception handling constructs, and initializer(s) should not be enclosed in parentheses."), MULTIPLE_IMPORTS("multiple-imports", MultipleImportListener.class.getName(), "Multiple import statements should not be defined on a single line."), FUNCTION_WHITESPACE("function-whitespace", BlankLineListener.class.getName(), ""), WHITESPACE("whitespace", WhitespaceListener.class.getName(), ""), CONSTANT_NAMING("constant-naming", ConstantNamingListener.class.getName(), "Global constants should follow either UpperCamelCase or lowerCamelCase naming conventions. Local constants " + "should follow lowerCamelCase naming conventions."), CONSTANT_K_PREFIX("constant-k-prefix", KPrefixListener.class.getName(), "Flag constants with prefix k."), LOWER_CAMEL_CASE("lower-camel-case", LowerCamelCaseListener.class.getName(), "Method and variable names should follow lowerCamelCase naming convention."), BRACE_STYLE("brace-style", BraceStyleListener.class.getName(), "Definitions of constructs should follow the One True Brace (OTB) style."), FORCED_TYPE_CAST("forced-type-cast", ForceTypeCastListener.class.getName(), "Flag force cast usages."), TRAILING_WHITESPACE("trailing-whitespace", FileListener.class.getName(), "Flag spaces or tabs after the last non-whitespace character on the line until the newline."), TERMINATING_NEWLINE("file-terminating-newline", FileListener.class.getName(), "Verify that source files terminate with a single \\n character."), LEADING_WHITESPACE("file-leading-whitespace", FileListener.class.getName(), "Verify that source files begins with a non whitespace character."), COMMENT_WHITESPACE("comment-whitespace", CommentAnalyzer.class.getName(), ""), // Max Length Rules MAX_CLASS_LENGTH(ArgumentParser.MAX_CLASS_LENGTH_OPT, FileListener.class.getName(), "Enforce a line limit on the lengths of class bodies."), MAX_STRUCT_LENGTH(ArgumentParser.MAX_STRUCT_LENGTH_OPT, FileListener.class.getName(), "Enforce a line limit on the lengths of struct bodies."), MAX_CLOSURE_LENGTH(ArgumentParser.MAX_CLOSURE_LENGTH_OPT, FileListener.class.getName(), "Enforce a line limit on the lengths of closure bodies."), MAX_FUNCTION_LENGTH(ArgumentParser.MAX_FUNCTION_LENGTH_OPT, FileListener.class.getName(), "Enforce a line limit on the lengths of function bodies."), MAX_FILE_LENGTH(ArgumentParser.MAX_FILE_LENGTH_OPT, FileListener.class.getName(), "Enforce a line limit on a file."), MAX_LINE_LENGTH(ArgumentParser.MAX_LINE_LENGTH_LONG_OPT, FileListener.class.getName(), "Enforce a character limit on the length of each line."), MAX_NAME_LENGTH(ArgumentParser.MAX_NAME_LENGTH_OPT, FileListener.class.getName(), "Enforce a character limit on the length of each construct name."); private String name; private String className; private String description; Rules(String name, String className, String description) { this.name = name; this.className = className; this.description = description; } public String getName() { return this.name; } public String getClassName() { return this.className; } public String getDescription() { return this.description; } }
package com.sri.ai.praise.demo; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.LineNumberReader; import javax.swing.Action; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.SwingWorker; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.undo.CannotRedoException; import javax.swing.undo.UndoManager; import com.google.common.annotations.Beta; import com.sri.ai.expresso.api.Expression; import com.sri.ai.praise.demo.action.ClearOutputAction; import com.sri.ai.praise.demo.action.ExecuteQueryAction; import com.sri.ai.praise.demo.action.ExitAction; import com.sri.ai.praise.demo.action.ExportAction; import com.sri.ai.praise.demo.action.NewAction; import com.sri.ai.praise.demo.action.HideToolBarAction; import com.sri.ai.praise.demo.action.NewWindowAction; import com.sri.ai.praise.demo.action.OpenFileAction; import com.sri.ai.praise.demo.action.RedoAction; import com.sri.ai.praise.demo.action.SaveAction; import com.sri.ai.praise.demo.action.SaveAllAction; import com.sri.ai.praise.demo.action.SaveAsAction; import com.sri.ai.praise.demo.action.UndoAction; import com.sri.ai.praise.demo.action.ValidateAction; import com.sri.ai.praise.demo.model.Example; import com.sri.ai.praise.lbp.LBPFactory; import com.sri.ai.praise.lbp.LBPQueryEngine; import com.sri.ai.praise.model.Model; import com.sri.ai.praise.rules.ReservedWordException; import com.sri.ai.praise.rules.RuleConverter; import com.sri.ai.util.base.Pair; /** * * @author oreilly * */ @Beta public class Controller { private LBPQueryEngine queryEngine = LBPFactory.newLBPQueryEngine(); private PRAiSEDemoApp app = null; private RuleEditor activeEditor; private File currentModelFile = null; private File currentEvidenceFile = null; private UndoManager modelUndoManager = new UndoManager(); private UndoManager evidenceUndoManager = new UndoManager(); private NewAction newAction = null; private OpenFileAction openFileAction = null; private SaveAction saveAction = null; private SaveAsAction saveAsAction = null; private SaveAllAction saveAllAction = null; private ExportAction exportAction = null; private ExitAction exitAction = null; private UndoAction undoAction = null; private RedoAction redoAction = null; private ValidateAction validateAction = null; private ExecuteQueryAction executeQueryAction = null; private ClearOutputAction clearOutputAction = null; private NewWindowAction newWindowAction = null; private HideToolBarAction hideToolBarAction = null; private JFileChooser fileChooser = new JFileChooser(); public Controller(PRAiSEDemoApp app) { this.app = app; modelUndoManager.setLimit(-1); evidenceUndoManager.setLimit(-1); app.modelEditPanel.addUndoableEditListener(new UndoableEditListener() { @Override public void undoableEditHappened(UndoableEditEvent e) { modelUndoManager.undoableEditHappened(e); handleUndoRedo(modelUndoManager); } }); app.evidenceEditPanel.addUndoableEditListener(new UndoableEditListener() { @Override public void undoableEditHappened(UndoableEditEvent e) { evidenceUndoManager.undoableEditHappened(e); handleUndoRedo(evidenceUndoManager); } }); updateAppTitle(); } public void setActiveEditor(RuleEditor ae) { this.activeEditor = ae; handleUndoRedo(getActiveUndoManager()); } public void setExample(Example example) { saveAll(); currentModelFile = null; currentEvidenceFile = null; app.modelEditPanel.setText(example.getModel()); app.evidenceEditPanel.setText(example.getEvidence()); app.queryPanel.setCurrentQuery(example.getQueryToRun()); modelUndoManager.discardAllEdits(); evidenceUndoManager.discardAllEdits(); handleUndoRedo(getActiveUndoManager()); updateAppTitle(); } public void newActiveEditorContent() { saveIfRequired(activeEditor); activeEditor.setText(""); discardActiveEdits(); setOutputFile(activeEditor, null); } public void openFile() { int returnVal = fileChooser.showOpenDialog(app.toolBar.btnOpen); if (returnVal == JFileChooser.APPROVE_OPTION) { File toOpen = fileChooser.getSelectedFile(); if (toOpen.exists()) { saveIfRequired(activeEditor); try { LineNumberReader reader = new LineNumberReader(new FileReader(toOpen)); StringBuilder sb = new StringBuilder(); String line = null; while ( (line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } reader.close(); activeEditor.setText(sb.toString()); discardActiveEdits(); setOutputFile(activeEditor, toOpen); } catch (IOException ioe) { error("Unable to open file: "+toOpen.getAbsolutePath()); } } else { warning("File ["+toOpen.getAbsolutePath()+"] does not exist."); } } } public void save() { saveIfRequired(activeEditor); } public void saveAs() { saveAs(activeEditor); } public void saveAll() { saveIfRequired(app.modelEditPanel); saveIfRequired(app.evidenceEditPanel); } public void export() { // TODO information("Currently Not Implemented\n"+"See: http://code.google.com/p/aic-praise/wiki/ExportingModels for more information."); } public void exit() { if (isASaveRequired()) { int option = JOptionPane.showConfirmDialog( app.frame, "Save changes before exiting?", "Save?", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { saveIfRequired(app.modelEditPanel); saveIfRequired(app.evidenceEditPanel); } } } public void undo() { UndoManager undoManager = getActiveUndoManager(); if (undoManager.canUndo()) { try { undoManager.undo(); } catch (CannotRedoException cue) { // ignore } } handleUndoRedo(undoManager); } public void redo() { UndoManager undoManager = getActiveUndoManager(); if (undoManager.canRedo()) { try { undoManager.redo(); } catch (CannotRedoException cue) { // ignore } } handleUndoRedo(undoManager); } public void validate() { // TODO information("Validate currently not implemented"); } public void executeQuery() { executeQueryAction.setEnabled(false); SwingWorker<String, Object> queryWorker = new SwingWorker<String, Object>() { @Override public String doInBackground() { try { printlnToConsole("ABOUT TO RUN QUERY"); RuleConverter ruleConverter = new RuleConverter(); Pair<Expression, Model> parseResult = ruleConverter .parseModel("'Name'", "'Description'", app.modelEditPanel.getText() + "\n" + app.evidenceEditPanel.getText(), app.queryPanel.getCurrentQuery()); printlnToConsole("MODEL DECLARATION=\n" + parseResult.second.getModelDeclaration()); printlnToConsole("QUERY=\n" + parseResult.first); String queryUUID = queryEngine.newQueryUUID(); String belief = queryEngine.queryBeliefOfRandomVariable( queryUUID, "belief([" + parseResult.first + "])", parseResult.second.getModelDeclaration()); printlnToConsole("BELIEF=\n" + belief); app.queryPanel.setResult(belief); } catch (ReservedWordException rwe) { rwe.printStackTrace(); } catch (RuntimeException re) { re.printStackTrace(); } finally { executeQueryAction.setEnabled(true); } printlnToConsole(" return "done"; } }; queryWorker.execute(); } public void clearOutput() { app.outputPanel.clearAllOutputs(); } public void newWindow() { // TODO information("New Window currently not implemented."); } public JFrame getAppFrame() { return app.frame; } public ToolBarPanel getToolBar() { return app.toolBar; } public Action getNewAction() { if (null == newAction) { newAction = new NewAction(this); } return newAction; } public Action getOpenFileAction() { if (null == openFileAction) { openFileAction = new OpenFileAction(this); } return openFileAction; } public Action getSaveAction() { if (null == saveAction) { saveAction = new SaveAction(this); } return saveAction; } public Action getSaveAsAction() { if (null == saveAsAction) { saveAsAction = new SaveAsAction(this); } return saveAsAction; } public Action getSaveAllAction() { if (null == saveAllAction) { saveAllAction = new SaveAllAction(this); } return saveAllAction; } public Action getExportAction() { if (null == exportAction) { exportAction = new ExportAction(this); } return exportAction; } public Action getExitAction() { if (null == exitAction) { exitAction = new ExitAction(this); } return exitAction; } public Action getUndoAction() { if (null == undoAction) { undoAction = new UndoAction(this); } return undoAction; } public Action getRedoAction() { if (null == redoAction) { redoAction = new RedoAction(this); } return redoAction; } public Action getValidateAction() { if (null == validateAction) { validateAction = new ValidateAction(this); } return validateAction; } public Action getExecuteQueryAction() { if (null == executeQueryAction) { executeQueryAction = new ExecuteQueryAction(this); } return executeQueryAction; } public Action getClearOutputAction() { if (null == clearOutputAction) { clearOutputAction = new ClearOutputAction(this); } return clearOutputAction; } public Action getNewWindowAction() { if (null == newWindowAction) { newWindowAction = new NewWindowAction(this); } return newWindowAction; } public Action getHideToolBarAction() { if (null == hideToolBarAction) { hideToolBarAction = new HideToolBarAction(this); } return hideToolBarAction; } // PRIVATE private void updateAppTitle() { String title = "PRAiSE - Model["; if (currentModelFile == null) { title += "*"; } else { title += currentModelFile.getAbsolutePath(); } title += "]::Evidence["; if (currentEvidenceFile == null) { title += "*"; } else { title += currentEvidenceFile.getAbsolutePath(); } title += "]"; app.frame.setTitle(title); } private UndoManager getActiveUndoManager() { return getUndoManager(activeEditor); } private UndoManager getUndoManager(RuleEditor ruleEditor) { UndoManager undoManager = modelUndoManager; if (ruleEditor == app.evidenceEditPanel) { undoManager = evidenceUndoManager; } return undoManager; } public void setOutputFile(RuleEditor editor, File outFile) { if (editor == app.modelEditPanel) { currentModelFile = outFile; } else { currentEvidenceFile = outFile; } updateAppTitle(); } public File getOutputFile(RuleEditor ruleEditor) { File outFile = currentModelFile; if (ruleEditor == app.evidenceEditPanel) { outFile = currentEvidenceFile; } return outFile; } private void handleUndoRedo(UndoManager undoManager) { getUndoAction().setEnabled(undoManager.canUndo()); getRedoAction().setEnabled(undoManager.canRedo()); if (getActiveUndoManager().canUndo()) { getSaveAction().setEnabled(true); getSaveAsAction().setEnabled(true); } else { getSaveAction().setEnabled(false); getSaveAsAction().setEnabled(false); } if (isASaveRequired()) { getSaveAllAction().setEnabled(true); } else { getSaveAllAction().setEnabled(false); } } private boolean isASaveRequired() { return modelUndoManager.canUndo() || evidenceUndoManager.canUndo(); } private void discardActiveEdits() { discardEdits(activeEditor); } private void discardEdits(RuleEditor editor) { UndoManager um = getUndoManager(editor); um.discardAllEdits(); handleUndoRedo(um); } private void saveIfRequired(RuleEditor editor) { if (getUndoManager(editor).canUndo()) { File outFile = getOutputFile(editor); if (outFile == null) { saveAs(editor); } else { saveToFile(editor.getText(), outFile, editor); } } } private void saveAs(RuleEditor editor) { if (getUndoManager(editor).canUndo()) { File outFile = getOutputFile(editor); if (outFile != null) { fileChooser.setSelectedFile(outFile); } int returnVal = fileChooser.showSaveDialog(app.toolBar.btnSave); if (returnVal == JFileChooser.APPROVE_OPTION) { outFile = fileChooser.getSelectedFile(); saveToFile(editor.getText(), outFile, editor); } } } private void saveToFile(String text, File file, RuleEditor editor) { try { if (!file.exists()) { file.createNewFile(); } FileWriter fileWriter = new FileWriter(file); fileWriter.write(text); fileWriter.close(); discardEdits(editor); setOutputFile(editor, file); } catch (IOException ioe) { error("ERROR saving file:\n"+file.getAbsolutePath()); } } private void printlnToConsole(String msg) { System.out.println(msg); System.out.flush(); } private void error(String message) { JOptionPane.showMessageDialog(app.frame, message, "Error", JOptionPane.ERROR_MESSAGE, null); } private void warning(String message) { JOptionPane.showMessageDialog(app.frame, message, "Warning", JOptionPane.WARNING_MESSAGE, null); } private void information(String message) { JOptionPane.showMessageDialog(app.frame, message, "Information", JOptionPane.INFORMATION_MESSAGE, null); } }
package com.stripe.model; import com.stripe.net.RequestOptions; import java.util.List; import java.util.Map; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Provides a representation of a single page worth of data from the Stripe * API. * * <p>The following code will have the effect of iterating through a single page * worth of invoice data retrieve from the API: * * <p><pre> * {@code * foreach (Invoice invoice : Invoice.list(...).getData()) { * System.out.println("Current invoice = " + invoice.toString()); * } * } * </pre> * * <p>The class also provides a helper for iterating over collections that may be * longer than a single page: * * <p><pre> * {@code * foreach (Invoice invoice : Invoice.list(...).autoPagingIterable()) { * System.out.println("Current invoice = " + invoice.toString()); * } * } * </pre> */ @Getter @Setter @EqualsAndHashCode(callSuper = false) public abstract class StripeCollection<T extends HasId> extends StripeObject implements StripeCollectionInterface<T> { String object; @Getter(onMethod = @__({@Override})) List<T> data; @Getter(onMethod = @__({@Override})) Boolean hasMore; @Getter(onMethod = @__({@Override})) Long totalCount; @Getter(onMethod = @__({@Override})) String url; @Deprecated Long count; @Getter(onMethod = @__({@Override})) @Setter(onMethod = @__({@Override})) private RequestOptions requestOptions; @Getter(onMethod = @__({@Override})) @Setter(onMethod = @__({@Override})) private Map<String, Object> requestParams; public Iterable<T> autoPagingIterable() { return new PagingIterable<T>(this); } public Iterable<T> autoPagingIterable(Map<String, Object> params) { this.setRequestParams(params); return new PagingIterable<T>(this); } /** * Constructs an iterable that can be used to iterate across all objects * across all pages. As page boundaries are encountered, the next page will * be fetched automatically for continued iteration. * * @param params request parameters (will override the parameters from the initial list request) * @param options request options (will override the options from the initial list request) */ public Iterable<T> autoPagingIterable(Map<String, Object> params, RequestOptions options) { this.setRequestOptions(options); this.setRequestParams(params); return new PagingIterable<T>(this); } }
// OOO GWT Utils - utilities for creating GWT applications // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.gwt.ui; import java.util.ArrayList; import java.util.List; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FlexTable; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.threerings.gwt.util.DataModel; /** * Displays a paginated collection of UI elements. */ public abstract class PagedWidget<T> extends FlowPanel { public static final int NAV_ON_TOP = 0; public static final int NAV_ON_BOTTOM = 1; // public static final int NAV_ON_BOTH = 2; // not yet supported public PagedWidget (int resultsPerPage) { this(resultsPerPage, NAV_ON_TOP); } public PagedWidget (int resultsPerPage, int navLoc) { //setHorizontalAlignment(ALIGN_LEFT); _resultsPerPage = resultsPerPage; _navLoc = navLoc; // these will be used for navigation _next = new Button("Next"); _next.setStyleName("Button"); _next.addStyleName("NextButton"); _next.addClickHandler(new ClickHandler() { public void onClick (ClickEvent event) { displayPageFromClick(_page+1); } }); _prev = new Button("Prev"); _prev.setStyleName("Button"); _prev.addStyleName("PrevButton"); _prev.addClickHandler(new ClickHandler() { public void onClick (ClickEvent event) { displayPageFromClick(_page-1); } }); _controls = new SmartTable(0, 0); _controls.setWidth("100%"); addCustomControls(_controls); _infoCol = (_controls.getRowCount() == 0) ? 0 : _controls.getCellCount(0); _controls.getFlexCellFormatter().setStyleName(0, _infoCol, "Info"); _controls.setWidget(0, _infoCol+1, _prev, 1, "Prev"); _controls.setWidget(0, _infoCol+2, _next, 1, "Next"); if (navLoc == NAV_ON_TOP) { _controls.setStyleName("Header"); _controls.insertCell(0, 0); _infoCol++; _controls.getFlexCellFormatter().setStyleName(0, 0, "TopLeft"); _controls.getFlexCellFormatter().setStyleName(0, _controls.getCellCount(0), "TopRight"); } else { _controls.setStyleName("BareFooter"); } // show initial controls add(_controls); } /** * Returns the page we're currently displaying. */ public int getPage () { return _page; } /** * Returns the index in the complete list of the first element we're currently displaying. */ public int getOffset () { return _page * _resultsPerPage; } /** * Returns true if this panel is configured with its model. */ public boolean hasModel () { return _model != null; } /** * Configures this panel with a {@link DataModel} and kicks the data * retrieval off by requesting the specified page to be displayed. */ public void setModel (DataModel<T> model, int page) { _model = model; displayPage(page, true); } /** * Returns the model in use by this panel or null if we have no model. */ public DataModel<T> getModel () { return _model; } /** * Returns the controls in use by this panel or null if we have no model. */ public SmartTable getControls () { return _controls; } public void reloadPage () { displayPage(getPage(), true); } /** * Displays the specified page. Does nothing if we are already displaying * that page unless forceRefresh is true. */ public void displayPage (final int page, boolean forceRefresh) { if (_page == page && !forceRefresh) { return; // NOOP! } // Display the now loading widget, if necessary. configureLoadingNavi(_controls, 0, _infoCol); _page = Math.max(page, 0); final boolean overQuery = (_model.getItemCount() < 0); final int count = _resultsPerPage; final int start = _resultsPerPage * page; _model.doFetchRows(start, overQuery ? (count + 1) : count, new AsyncCallback<List<T>>() { public void onSuccess (List<T> result) { if (overQuery) { // if we requested 1 item too many, see if we got it if (result.size() < (count + 1)) { // no: this is the last batch of items, woohoo _lastItem = start + result.size(); } else { // yes: strip it before anybody else gets to see it result.remove(count); _lastItem = -1; } } else { // a valid item count should be available at this point _lastItem = _model.getItemCount(); } displayResults(start, count, result); } public void onFailure (Throwable caught) { reportFailure(caught); } }); } /** * Removes the specified item from the panel. If the item is currently being displayed, its * interface element will be removed as well. */ public void removeItem (T item) { if (_model == null) { return; // if we have no model, stop here } // remove the item from our data model _model.removeItem(item); // force a relayout of this page displayPage(_page, true); } protected void configureLoadingNavi (FlexTable controls, int row, int col) { Widget widget = getNowLoadingWidget(); if (widget != null) { controls.setWidget(row, col, widget); controls.getFlexCellFormatter().setHorizontalAlignment(row, col, HasAlignment.ALIGN_CENTER); } _next.setEnabled(false); _prev.setEnabled(false); } /** * Get the text that should be shown in the header bar between the "prev" and "next" buttons. */ protected void configureNavi (FlexTable controls, int row, int col, int start, int limit, int total) { HorizontalPanel panel = new HorizontalPanel(); panel.add(new Label("Page:")); // TODO: i18n // determine which pages we want to show int page = 1+start/_resultsPerPage; int pages; if (total < 0) { pages = page + 1; } else { pages = total/_resultsPerPage + (total%_resultsPerPage == 0 ? 0 : 1); } List<Integer> shown = new ArrayList<Integer>(); shown.add(1); for (int ii = Math.max(2, Math.min(page-2, pages-5)); ii <= Math.min(pages-1, Math.max(page+2, 6)); ii++) { shown.add(ii); } if (pages != 1) { shown.add(pages); } // now display those as "Page: _1_ ... _3_ _4_ 5 _6_ _7_ ... _10_" int ppage = 0; for (Integer cpage : shown) { if (cpage - ppage > 1) { panel.add(createPageLabel("...", null)); } if (cpage == page) { panel.add(createPageLabel(""+page, "Current")); } else { panel.add(createPageLinkLabel(cpage)); } ppage = cpage; } if (total < 0) { panel.add(createPageLabel("...", null)); } controls.setWidget(row, col, panel); controls.getFlexCellFormatter().setHorizontalAlignment(row, col, HasAlignment.ALIGN_CENTER); } /** * Return true if the navigation should appear. The default only shows the navigation if there * is at least one item. */ protected boolean displayNavi (int items) { return (items != 0); } protected Label createPageLinkLabel (final int page) { Label label = createPageLabel(""+page, "Link"); label.addClickHandler(new ClickHandler() { public void onClick (ClickEvent event) { displayPageFromClick(page-1); } }); return label; } protected Label createPageLabel (String text, String optStyle) { Label label = new Label(text); label.setStyleName("Page"); if (optStyle != null) { label.addStyleName(optStyle); } return label; } protected void displayResults (int start, int count, List<T> list) { clear(); if (_navLoc != NAV_ON_BOTTOM && displayNavi(_lastItem)) { add(_controls); } add((list.size() == 0) ? createEmptyContents() : createContents(start, count, list)); if (_navLoc != NAV_ON_TOP && displayNavi(_lastItem)) { add(_controls); } else { Widget cap = new Label(""); cap.addStyleName("EndCap"); add(cap); } _prev.setEnabled(start > 0); _next.setEnabled(_lastItem < 0 || start + count < _lastItem); if (_lastItem != 0) { int shown = Math.max(list.size(), count); configureNavi(_controls, 0, _infoCol, start, shown, _lastItem); } else { _controls.setHTML(0, _infoCol, "&nbsp;"); } } protected abstract Widget createContents (int start, int count, List<T> list); /** * Called when the user clicks a forward or back button. */ protected void displayPageFromClick (int page) { displayPage(page, false); } protected Widget createEmptyContents () { Label label = new Label(getEmptyMessage()); label.setStyleName("Empty"); return label; } protected void addCustomControls (FlexTable controls) { } /** * Returns the widget that should be displayed in place of the page list when navigating * between pages. By default this returns null, indicating this should not happen; subclasses * can override this to display the widget. */ protected Widget getNowLoadingWidget () { return null; } /** * Report a service failure. */ protected void reportFailure (Throwable caught) { java.util.logging.Logger.getLogger("PagedWidget").warning("Failure to page: " + caught); // if (_model instanceof ServiceBackedDataModel<?,?>) { // ((ServiceBackedDataModel<?,?>)_model).reportFailure(caught); // } else { // // TODO?! } protected abstract String getEmptyMessage (); protected int _navLoc; protected SmartTable _controls; protected int _infoCol; protected Button _next, _prev; protected DataModel<T> _model; protected int _lastItem; protected int _page; protected int _resultsPerPage; }
package com.yahoo.sketches.quantiles; import static com.yahoo.sketches.Util.ceilingPowerOf2; import static com.yahoo.sketches.Util.isPowerOf2; import static com.yahoo.sketches.quantiles.PreambleUtil.COMPACT_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.EMPTY_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.ORDERED_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.READ_ONLY_FLAG_MASK; import static com.yahoo.sketches.quantiles.PreambleUtil.extractFlags; import com.yahoo.memory.Memory; import com.yahoo.sketches.Family; import com.yahoo.sketches.SketchesArgumentException; /** * Utility class for quantiles sketches. * * <p>This class contains a highly specialized sort called blockyTandemMergeSort(). * It also contains methods that are used while building histograms and other common * functions.</p> * * @author Lee Rhodes */ final class Util { private Util() {} /** * The java line separator character as a String. */ static final String LS = System.getProperty("line.separator"); /** * The tab character */ static final char TAB = '\t'; /** * Computes the Komologorov-Smirnov Statistic between two quantiles sketches. * @param sketch1 Input DoubleSketch 1 * @param sketch2 Input DoubleSketch 2 * @param tgtConf Target confidence threshold * @return Boolean indicating whether the two sketches were likely generated from the same * underlying distribution. */ public static boolean computeKSStatistic(final DoublesSketch sketch1, final DoublesSketch sketch2, final double tgtConf) { final DoublesAuxiliary p = sketch1.constructAuxiliary(); final DoublesAuxiliary q = sketch2.constructAuxiliary(); final double[] pSamplesArr = p.auxSamplesArr_; final double[] qSamplesArr = q.auxSamplesArr_; final long[] pCumWtsArr = p.auxCumWtsArr_; final long[] qCumWtsArr = q.auxCumWtsArr_; final int pSamplesArrLen = pSamplesArr.length; final int qSamplesArrLen = qSamplesArr.length; final double n1 = sketch1.getN(); final double n2 = sketch2.getN(); final double confScale = Math.sqrt(-0.5 * Math.log(0.5 * tgtConf)); // reject null hypothesis at tgtConf if D_{KS} > thresh final double thresh = confScale * Math.sqrt((n1 + n2) / (n1 * n2)); double D = 0.0; int i = getNextIndex(pSamplesArr, -1); int j = getNextIndex(qSamplesArr, -1); // We're done if either array reaches the end while ((i < pSamplesArrLen) && (j < qSamplesArrLen)) { final double pSample = pSamplesArr[i]; final double qSample = qSamplesArr[j]; final long pWt = pCumWtsArr[i]; final long qWt = qCumWtsArr[j]; final double pNormWt = pWt / n1; final double qNormWt = qWt / n2; final double pMinusQ = Math.abs(pNormWt - qNormWt); final double curD = D; D = Math.max(curD, pMinusQ); System.out.printf("p[%d]: (%f, %f)\t", i, pSample, pNormWt); System.out.printf("q[%d]: (%f, %f)\n", j, qSample, qNormWt); System.out.printf("\tpCumWt = %d \tqCumWt = %d\n", pWt, qWt); System.out.printf("\tD = max(D, pNormWt - qNormWt) = max(%f, %f) = %f\n", curD, pMinusQ, D); //Increment i or j or both if (pSample == qSample) { System.out.println("\tIncrement both\n"); i = getNextIndex(pSamplesArr, i); j = getNextIndex(qSamplesArr, j); } else if ((pSample < qSample) && (i < pSamplesArrLen)) { System.out.println("\tIncrement p\n"); i = getNextIndex(pSamplesArr, i); } else { System.out.println("\tIncrement q\n"); j = getNextIndex(qSamplesArr, j); } } // One final comparison, with one of the two values at 1.0. // Subsequent values for the smaller CDF will be strictly larger, so the difference for any // later tests cannot be greater. System.out.printf("Final D = max(%f, %f)\n", D, Math.abs((pCumWtsArr[i] / n1) - (qCumWtsArr[j] / n2))); D = Math.max(D, Math.abs((pCumWtsArr[i] / n1) - (qCumWtsArr[j] / n2))); /* System.out.println("N: " + p.auxN_); for (int i = 0; i < p.auxSamplesArr_.length; ++i) { System.out.printf("%5d:\t%d\t%f\t%f\n", i, p.auxCumWtsArr_[i], p.auxSamplesArr_[i], p.auxCumWtsArr_[i] / (double) p.auxN_); } */ final double eps1 = Util.EpsilonFromK.getAdjustedEpsilon(sketch1.getK()); final double eps2 = Util.EpsilonFromK.getAdjustedEpsilon(sketch2.getK()); final double adjustedD = D - eps1 - eps2; System.out.printf("D: %f\te1: %f\te2: %f\ttotal: %f \tthresh: %f \tresult: %s\n", D, eps1, eps2, adjustedD, thresh, adjustedD > thresh); return adjustedD > thresh; } private static final int getNextIndex(final double[] samplesArr, final int stIdx) { int idx = stIdx + 1; final int samplesArrLen = samplesArr.length; if (idx >= samplesArrLen) { return samplesArrLen; } // if we have a sequence of equal values, use the last one of the sequence final double val = samplesArr[idx]; int nxtIdx = idx + 1; while ((nxtIdx < samplesArrLen) && (samplesArr[nxtIdx] == val)) { idx = nxtIdx; ++nxtIdx; } return idx; } /** * Checks the validity of the given value k * @param k must be greater than 1 and less than 65536. */ static void checkK(final int k) { if ((k < DoublesSketch.MIN_K) || (k >= (1 << 16)) || !isPowerOf2(k)) { throw new SketchesArgumentException("K must be > 1 and < 65536 and Power of 2: " + k); } } /** * Checks the validity of the given family ID * @param familyID the given family ID */ static void checkFamilyID(final int familyID) { final Family family = Family.idToFamily(familyID); if (!family.equals(Family.QUANTILES)) { throw new SketchesArgumentException( "Possible corruption: Invalid Family: " + family.toString()); } } /** * Checks the consistency of the flag bits and the state of preambleLong and the memory * capacity and returns the empty state. * @param preambleLongs the size of preamble in longs * @param flags the flags field * @param memCapBytes the memory capacity * @return the value of the empty state */ static boolean checkPreLongsFlagsCap(final int preambleLongs, final int flags, final long memCapBytes) { final boolean empty = (flags & EMPTY_FLAG_MASK) > 0; //Preamble flags empty state final int minPre = Family.QUANTILES.getMinPreLongs(); final int maxPre = Family.QUANTILES.getMaxPreLongs(); final boolean valid = ((preambleLongs == minPre) && empty) || ((preambleLongs == maxPre) && !empty); if (!valid) { throw new SketchesArgumentException( "Possible corruption: PreambleLongs inconsistent with empty state: " + preambleLongs); } checkHeapFlags(flags); if (memCapBytes < (preambleLongs << 3)) { throw new SketchesArgumentException( "Possible corruption: Insufficient capacity for preamble: " + memCapBytes); } return empty; } /** * Checks just the flags field of the preamble. Allowed flags are Read Only, Empty, Compact, and * ordered. * @param flags the flags field */ static void checkHeapFlags(final int flags) { //only used by checkPreLongsFlagsCap and test final int allowedFlags = READ_ONLY_FLAG_MASK | EMPTY_FLAG_MASK | COMPACT_FLAG_MASK | ORDERED_FLAG_MASK; final int flagsMask = ~allowedFlags; if ((flags & flagsMask) > 0) { throw new SketchesArgumentException( "Possible corruption: Invalid flags field: " + Integer.toBinaryString(flags)); } } /** * Checks just the flags field of an input Memory object. Returns true for a compact * sketch, false for an update sketch. Does not perform additional checks, including sketch * family. * @param srcMem the source Memory containign a sketch * @return true if flags indicate a comapct sketch, otherwise false */ static boolean checkIsCompactMemory(final Memory srcMem) { // only reading so downcast is ok final int flags = extractFlags(srcMem); final int compactFlags = READ_ONLY_FLAG_MASK | COMPACT_FLAG_MASK; return (flags & compactFlags) > 0; } /** * Checks the sequential validity of the given array of fractions. * They must be unique, monotonically increasing and not NaN, not &lt; 0 and not &gt; 1.0. * @param fractions array */ static final void validateFractions(final double[] fractions) { if (fractions == null) { throw new SketchesArgumentException("Fractions cannot be null."); } final int len = fractions.length; if (len == 0) { return; } final double flo = fractions[0]; final double fhi = fractions[fractions.length - 1]; if ((flo < 0.0) || (fhi > 1.0)) { throw new SketchesArgumentException( "A fraction cannot be less than zero or greater than 1.0"); } Util.validateValues(fractions); } /** * Checks the sequential validity of the given array of double values. * They must be unique, monotonically increasing and not NaN. * @param values the given array of double values */ static final void validateValues(final double[] values) { if (values == null) { throw new SketchesArgumentException("Values cannot be null."); } final int lenM1 = values.length - 1; for (int j = 0; j < lenM1; j++) { if (values[j] < values[j + 1]) { continue; } throw new SketchesArgumentException( "Values must be unique, monotonically increasing and not NaN."); } } /** * Returns the number of retained valid items in the sketch given k and n. * @param k the given configured k of the sketch * @param n the current number of items seen by the sketch * @return the number of retained items in the sketch given k and n. */ static int computeRetainedItems(final int k, final long n) { final int bbCnt = computeBaseBufferItems(k, n); final long bitPattern = computeBitPattern(k, n); final int validLevels = computeValidLevels(bitPattern); return bbCnt + (validLevels * k); } /** * Returns the total item capacity of an updatable, non-compact combined buffer * given <i>k</i> and <i>n</i>. If total levels = 0, this returns the ceiling power of 2 * size for the base buffer or the MIN_BASE_BUF_SIZE, whichever is larger. * * @param k sketch parameter. This determines the accuracy of the sketch and the * size of the updatable data structure, which is a function of <i>k</i> and <i>n</i>. * * @param n The number of items in the input stream * @return the current item capacity of the combined buffer */ static int computeCombinedBufferItemCapacity(final int k, final long n) { final int totLevels = computeNumLevelsNeeded(k, n); if (totLevels == 0) { final int bbItems = computeBaseBufferItems(k, n); return Math.max(2 * DoublesSketch.MIN_K, ceilingPowerOf2(bbItems)); } return (2 + totLevels) * k; } /** * Computes the number of valid levels above the base buffer * @param bitPattern the bit pattern * @return the number of valid levels above the base buffer */ static int computeValidLevels(final long bitPattern) { return Long.bitCount(bitPattern); } /** * Computes the total number of logarithmic levels above the base buffer given the bitPattern. * @param bitPattern the given bit pattern * @return the total number of logarithmic levels above the base buffer */ static int computeTotalLevels(final long bitPattern) { return hiBitPos(bitPattern) + 1; } /** * Computes the total number of logarithmic levels above the base buffer given k and n. * This is equivalent to max(floor(lg(n/k), 0). * Returns zero if n is less than 2 * k. * @param k the configured size of the sketch * @param n the total values presented to the sketch. * @return the total number of levels needed. */ static int computeNumLevelsNeeded(final int k, final long n) { return 1 + hiBitPos(n / (2L * k)); } /** * Computes the number of base buffer items given k, n * @param k the configured size of the sketch * @param n the total values presented to the sketch * @return the number of base buffer items */ static int computeBaseBufferItems(final int k, final long n) { return (int) (n % (2L * k)); } /** * Computes the levels bit pattern given k, n. * This is computed as <i>n / (2*k)</i>. * @param k the configured size of the sketch * @param n the total values presented to the sketch. * @return the levels bit pattern */ static long computeBitPattern(final int k, final long n) { return n / (2L * k); } /** * Returns the log_base2 of x * @param x the given x * @return the log_base2 of x */ static double lg(final double x) { return ( Math.log(x) / Math.log(2.0) ); } /** * Zero-based position of the highest one-bit of the given long. * Returns minus one if num is zero. * @param num the given long * @return Zero-based position of the highest one-bit of the given long */ static int hiBitPos(final long num) { return 63 - Long.numberOfLeadingZeros(num); } /** * Returns the zero-based bit position of the lowest zero bit of <i>bits</i> starting at * <i>startingBit</i>. If input is all ones, this returns 64. * @param bits the input bits as a long * @param startingBit the zero-based starting bit position. Only the low 6 bits are used. * @return the zero-based bit position of the lowest zero bit starting at <i>startingBit</i>. */ static int lowestZeroBitStartingAt(final long bits, final int startingBit) { int pos = startingBit & 0X3F; long myBits = bits >>> pos; while ((myBits & 1L) != 0) { myBits = myBits >>> 1; pos++; } return pos; } static class EpsilonFromK { /** * Used while crunching down the empirical results. If this value is changed the adjustKForEps * value will be incorrect and must also be recomputed. Don't touch this! */ private static final double deltaForEps = 0.01; /** * A heuristic fudge factor that causes the inverted formula to better match the empirical. * The value of 4/3 is directly associated with the deltaForEps value of 0.01. * Don't touch this! */ private static final double adjustKForEps = 4.0 / 3.0; // fudge factor /** * Ridiculously fine tolerance given the fudge factor; 1e-3 would probably suffice */ private static final double bracketedBinarySearchForEpsTol = 1e-15; /** * From extensive empirical testing we recommend most users use this method for deriving * epsilon. This uses a fudge factor of 4/3 times the theoretical calculation of epsilon. * @param k the given k that must be greater than one. * @return the resulting epsilon */ static double getAdjustedEpsilon(final int k) { //used by HeapQS, so far return getTheoreticalEpsilon(k, adjustKForEps); } /** * Finds the epsilon given K and a fudge factor. * See Cormode's Mergeable Summaries paper, Journal version, Theorem 3.6. * This has a good fit between values of k between 16 and 1024. * Beyond that has not been empirically tested. * @param k The given value of k * @param ff The given fudge factor. No fudge factor = 1.0. * @return the resulting epsilon */ //used only by getAdjustedEpsilon() private static double getTheoreticalEpsilon(final int k, final double ff) { if (k < 2) { throw new SketchesArgumentException("K must be greater than one."); } // don't need to check in the other direction because an int is very small final double kf = k * ff; assert kf >= 2.15; // ensures that the bracketing succeeds assert kf < 1e12; // ditto, but could actually be bigger final double lo = 1e-16; final double hi = 1.0 - 1e-16; assert epsForKPredicate(lo, kf); assert !epsForKPredicate(hi, kf); return bracketedBinarySearchForEps(kf, lo, hi); } private static double kOfEpsFormula(final double eps) { return (1.0 / eps) * (Math.sqrt(Math.log(1.0 / (eps * deltaForEps)))); } private static boolean epsForKPredicate(final double eps, final double kf) { return kOfEpsFormula(eps) >= kf; } private static double bracketedBinarySearchForEps(final double kf, final double lo, final double hi) { assert lo < hi; assert epsForKPredicate(lo, kf); assert !epsForKPredicate(hi, kf); if (((hi - lo) / lo) < bracketedBinarySearchForEpsTol) { return lo; } final double mid = (lo + hi) / 2.0; assert mid > lo; assert mid < hi; if (epsForKPredicate(mid, kf)) { return bracketedBinarySearchForEps(kf, mid, hi); } else { return bracketedBinarySearchForEps(kf, lo, mid); } } } //End of EpsilonFromK }
package foodtruck.server; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.base.Strings; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.codehaus.jettison.json.JSONException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import foodtruck.dao.ScheduleDAO; import foodtruck.model.DailySchedule; import foodtruck.model.Location; import foodtruck.server.api.JsonWriter; import foodtruck.truckstops.FoodTruckStopService; import foodtruck.util.Clock; /** * Servlet that serves up the main food truck page. * @author aviolette * @since Jul 12, 2011 */ @Singleton public class FoodTruckServlet extends HttpServlet { private final Location mapCenter; private final DateTimeFormatter timeFormatter; private final Clock clock; private final DateTimeFormatter dateFormatter; private static final Logger log = Logger.getLogger(FoodTruckServlet.class.getName()); private final FoodTruckStopService stopService; private ScheduleDAO scheduleCacher; private JsonWriter writer; @Inject public FoodTruckServlet(DateTimeZone zone, @Named("center") Location centerLocation, Clock clock, FoodTruckStopService service, JsonWriter writer, ScheduleDAO scheduleCacher) { this.clock = clock; this.mapCenter = centerLocation; this.timeFormatter = DateTimeFormat.forPattern("YYYYMMdd-HHmm").withZone(zone); this.dateFormatter = DateTimeFormat.forPattern("EEE MMM dd, YYYY"); this.stopService = service; this.writer = writer; this.scheduleCacher = scheduleCacher; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = req.getRequestURI(); if (req.getServerName().contains("chifoodtruckz.com")) { resp.setStatus(301); resp.setHeader("Location", "http: return; } if (!Strings.isNullOrEmpty(path)) { req.setAttribute("showScheduleFor", path.substring(1)); } final String timeRequest = req.getParameter("time"); DateTime dateTime = null; if (!Strings.isNullOrEmpty(timeRequest)) { try { dateTime = timeFormatter.parseDateTime(timeRequest); } catch (IllegalArgumentException ignored) { } } if (dateTime == null) { dateTime = clock.now(); } req.setAttribute("center", getCenter(req.getCookies(), mapCenter)); String googleAnalytics = System.getProperty("foodtruck.google.analytics", null); if (googleAnalytics != null) { req.setAttribute("google_analytics_ua", googleAnalytics); } String payload = scheduleCacher.findSchedule(clock.currentDay()); if (payload == null) { DailySchedule schedule = stopService.findStopsForDay(clock.currentDay()); try { payload = writer.writeSchedule(schedule).toString(); } catch (JSONException e) { // TODO: fix this throw new RuntimeException(e); } } final String mode = req.getParameter("mode"); req.setAttribute("mobile", "mobile".equals(mode)); req.setAttribute("requestDate", dateFormatter.print(dateTime)); req.setAttribute("requestTime", timeFormatter.print(dateTime)); req.setAttribute("requestTimeInMillis", dateTime.getMillis()); req.setAttribute("payload", payload); req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp); } private Location getCenter(Cookie[] cookies, Location defaultValue) { double lat = 0, lng = 0; for (int i = 0; i < cookies.length; i++) { if ("latitude".equals(cookies[i].getName())) { lat = Double.valueOf(cookies[i].getValue()); } else if ("longitude".equals(cookies[i].getName())) { lng = Double.valueOf(cookies[i].getValue()); } } if (lat != 0 && lng != 0) { return Location.builder().lat(lat).lng(lng).build(); } return defaultValue; } }
package hu.bme.mit.spaceship; import java.util.Random; /** * Class storing and managing the torpedos of a ship */ public class TorpedoStore { private int torpedos = 0; private Random generator = new Random(); public TorpedoStore(int numberOfTorpedos){ this.torpedos = numberOfTorpedos; System.out.println("vuhuuu bracnh B"); } public boolean fire(int numberOfTorpedos){ if(numberOfTorpedos < 1 || numberOfTorpedos > this.torpedos){ throw new IllegalArgumentException("numberOfTorpedos"); } boolean success = false; //simulate random overheating of the launcher bay which prevents firing double r = generator.nextDouble(); if (r > 0.1) { // successful firing this.torpedos -= numberOfTorpedos; success = true; } else { // failure success = false; } return success; } public boolean isEmpty(){ return this.torpedos <= 0; } public int getNumberOfTorpedos() { return this.torpedos; } }
package i5.las2peer.tools; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import i5.las2peer.api.Connector; import i5.las2peer.api.ConnectorException; import i5.las2peer.api.exceptions.ArtifactNotFoundException; import i5.las2peer.api.exceptions.StorageException; import i5.las2peer.classLoaders.L2pClassManager; import i5.las2peer.classLoaders.libraries.FileSystemRepository; import i5.las2peer.classLoaders.libraries.Repository; import i5.las2peer.communication.ListMethodsContent; import i5.las2peer.communication.Message; import i5.las2peer.execution.L2pServiceException; import i5.las2peer.execution.NoSuchServiceException; import i5.las2peer.logging.L2pLogger; import i5.las2peer.p2p.AgentAlreadyRegisteredException; import i5.las2peer.p2p.AgentNotKnownException; import i5.las2peer.p2p.NodeException; import i5.las2peer.p2p.NodeInformation; import i5.las2peer.p2p.PastryNodeImpl; import i5.las2peer.p2p.ServiceNameVersion; import i5.las2peer.p2p.TimeoutException; import i5.las2peer.persistency.EncodingFailedException; import i5.las2peer.persistency.MalformedXMLException; import i5.las2peer.persistency.SharedStorage.STORAGE_MODE; import i5.las2peer.security.Agent; import i5.las2peer.security.AgentException; import i5.las2peer.security.GroupAgent; import i5.las2peer.security.L2pSecurityException; import i5.las2peer.security.L2pSecurityManager; import i5.las2peer.security.PassphraseAgent; import i5.las2peer.security.ServiceAgent; import i5.las2peer.security.UserAgent; import rice.p2p.commonapi.NodeHandle; /** * las2peer node launcher * * It is the main tool for service developers / node maintainers to start their services, upload agents to the network * and to test their service methods directly in the p2p network. The launcher both supports the start of a new network * as well as starting a node that connects to an already existing network via a bootstrap. * * All methods to be executed can be stated via additional command line parameters to the {@link #main} method. */ public class L2pNodeLauncher { // this is the main class and therefore the logger needs to be static private static final L2pLogger logger = L2pLogger.getInstance(L2pNodeLauncher.class.getName()); private static final String DEFAULT_SERVICE_DIRECTORY = "./service/"; private static final String DEFAULT_STARTUP_DIRECTORY = "etc/startup/"; private static final String DEFAULT_SERVICE_AGENT_DIRECTORY = "etc/startup/"; private CommandPrompt commandPrompt; private static List<Connector> connectors = new ArrayList<>(); private boolean bFinished = false; public boolean isFinished() { return bFinished; } private PastryNodeImpl node; public PastryNodeImpl getNode() { return node; } private UserAgent currentUser; /** * Get the envelope with the given id * * @param id * @return the XML-representation of an envelope as a String * @throws StorageException * @throws ArtifactNotFoundException * @throws NumberFormatException * @throws SerializationException */ public String getEnvelope(String id) throws NumberFormatException, ArtifactNotFoundException, StorageException, SerializationException { return node.fetchEnvelope(id).toXmlString(); } /** * Searches for the given agent in the las2peer network. * * @param id * @return node handles * @throws AgentNotKnownException */ public Object[] findAgent(String id) throws AgentNotKnownException { long agentId = Long.parseLong(id); return node.findRegisteredAgent(agentId); } /** * Looks for the given service in the las2peer network. * * Needs an active user * * @see #registerUserAgent * * @param serviceNameVersion Exact name and version, same syantax as in {@link #startService(String)} * @return node handles * @throws AgentNotKnownException */ public Object[] findService(String serviceNameVersion) throws AgentNotKnownException { if (currentUser == null) { throw new IllegalStateException("Please register a valid user with registerUserAgent before invoking!"); } Agent agent = node.getServiceAgent(ServiceNameVersion.fromString(serviceNameVersion), currentUser); return node.findRegisteredAgent(agent); } /** * Closes the current node. */ public void shutdown() { node.shutDown(); this.bFinished = true; } /** * load passphrases from a simple text file where each line consists of the filename of the agent's xml file and a * passphrase separated by a ; * * @param filename * @return hashtable containing agent file &gt;&gt; passphrase */ private Hashtable<String, String> loadPassphrases(String filename) { Hashtable<String, String> result = new Hashtable<>(); File file = new File(filename); if (file.isFile()) { String[] content; try { content = FileContentReader.read(file).split("\n"); for (String line : content) { line = line.trim(); if (line.isEmpty()) { continue; } String[] split = line.split(";", 2); if (split.length != 2) { printWarning("Ignoring invalid passphrase line (" + line + ") in '" + filename + "'"); continue; } result.put(split[0], split[1]); } } catch (IOException e) { printErrorWithStacktrace("Error reading contents of " + filename, e); logger.printStackTrace(e); bFinished = true; } } return result; } /** * Uploads the contents of the given directory to the global storage of the las2peer network. * * Each contained .xml-file is used as an artifact or - in case the name of the file starts with <i>agent-</i> - as * an agent to upload. * * If agents are to be uploaded, make sure, that the startup directory contains a <i>passphrases.txt</i> file giving * the passphrases for the agents. * * @param directory */ public void uploadStartupDirectory(String directory) { File dir = new File(directory); if (!dir.isDirectory()) { throw new IllegalArgumentException(directory + " is not a directory!"); } Hashtable<String, String> htPassphrases = loadPassphrases(directory + "/passphrases.txt"); Map<Long, String> agentIdToXml = new HashMap<>(); List<GroupAgent> groupAgents = new LinkedList<>(); for (File xmlFile : dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xml"); } })) { try { // maybe an agent? Agent agent = Agent.createFromXml(xmlFile); agentIdToXml.put(agent.getId(), xmlFile.getName()); if (agent instanceof PassphraseAgent) { String passphrase = htPassphrases.get(xmlFile.getName()); if (passphrase != null) { ((PassphraseAgent) agent).unlockPrivateKey(passphrase); } else { printWarning("\t- got no passphrase for agent from " + xmlFile.getName()); } node.storeAgent(agent); printMessage("\t- stored agent from " + xmlFile); } else if (agent instanceof GroupAgent) { GroupAgent ga = (GroupAgent) agent; groupAgents.add(ga); } else { throw new IllegalArgumentException("Unknown agent type: " + agent.getClass()); } } catch (MalformedXMLException e) { printErrorWithStacktrace("unable to deserialize contents of " + xmlFile.toString() + "!", e); } catch (L2pSecurityException e) { printErrorWithStacktrace("error storing agent from " + xmlFile.toString(), e); } catch (AgentAlreadyRegisteredException e) { printErrorWithStacktrace("agent from " + xmlFile.toString() + " already known at this node!", e); } catch (AgentException e) { printErrorWithStacktrace("unable to generate agent " + xmlFile.toString() + "!", e); } } // wait till all user agents are added from startup directory to unlock group agents for (GroupAgent currentGroupAgent : groupAgents) { for (Long memberId : currentGroupAgent.getMemberList()) { Agent memberAgent = null; try { memberAgent = node.getAgent(memberId); } catch (AgentNotKnownException e) { printErrorWithStacktrace("Can't get agent for group member " + memberId, e); continue; } if ((memberAgent instanceof PassphraseAgent) == false) { printError("Unknown agent type to unlock, type: " + memberAgent.getClass().getName()); continue; } PassphraseAgent memberPassAgent = (PassphraseAgent) memberAgent; String xmlName = agentIdToXml.get(memberPassAgent.getId()); if (xmlName == null) { printError("No known xml file for agent " + memberPassAgent.getId()); continue; } String passphrase = htPassphrases.get(xmlName); if (passphrase == null) { printError("No known password for agent " + memberPassAgent.getId()); continue; } try { memberPassAgent.unlockPrivateKey(passphrase); currentGroupAgent.unlockPrivateKey(memberPassAgent); node.storeAgent(currentGroupAgent); printMessage("\t- stored group agent from " + xmlName); break; } catch (Exception e) { printErrorWithStacktrace("Can't unlock group agent " + currentGroupAgent.getId() + " with member " + memberPassAgent.getId(), e); continue; } } if (currentGroupAgent.isLocked()) { throw new IllegalArgumentException("group agent still locked!"); } } } /** * Upload the contents of the <i>startup</i> sub directory to the global storage of the las2peer network. * * Each contained .xml-file is used as an artifact or - in case the name of the file starts with <i>agent-</i> - as * an agent to upload. * * If agents are to be uploaded, make sure, that the startup directory contains a <i>passphrases.txt</i> file giving * the passphrases for the agents. */ public void uploadStartupDirectory() { uploadStartupDirectory(DEFAULT_STARTUP_DIRECTORY); } /** * Uploads the service jar file and its dependencies into the shared storage to be used for network class loading. * * @param serviceJarFile The service jar file that should be uploaded. * @param developerAgentXMLFile The XML file of the developers agent. * @param developerPassword The password for the developer agent. */ public void uploadServicePackage(String serviceJarFile, String developerAgentXMLFile, String developerPassword) throws ServicePackageException { PackageUploader.uploadServicePackage(node, serviceJarFile, developerAgentXMLFile, developerPassword); } /** * Starts the HTTP connector. */ public void startHttpConnector() { startConnector("i5.las2peer.httpConnector.HttpConnector"); } /** * Start the Web-Connector. */ public void startWebConnector() { startConnector("i5.las2peer.webConnector.WebConnector"); } /** * Starts a connector given by its classname. * * @param connectorClass */ public void startConnector(String connectorClass) { try { printMessage("Starting connector with class name: " + connectorClass + "!"); Connector connector = loadConnector(connectorClass); connector.start(node); connectors.add(connector); } catch (Exception e) { printErrorWithStacktrace(" --> Problems starting the connector", e); } } /** * Stops the http Connector. */ public void stopHttpConnector() { stopConnector("i5.las2peer.httpConnector.HttpConnector"); } /** * Stops the Web-Connector. */ public void stopWebConnector() { stopConnector("i5.las2peer.webConnector.WebConnector"); } /** * Stops a connector given by its classname. * * @param connectorClass */ public void stopConnector(String connectorClass) { Iterator<Connector> iterator = connectors.iterator(); while (iterator.hasNext()) { try { Connector connector = iterator.next(); if (connector.getClass().getName().equals(connectorClass)) { connector.stop(); iterator.remove(); return; } } catch (ConnectorException e) { logger.printStackTrace(e); } } printWarning("No connector with the given classname was started!"); } private Connector loadConnector(String classname) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class<?> connectorClass = L2pNodeLauncher.class.getClassLoader().loadClass(classname); Connector connector = (Connector) connectorClass.newInstance(); return connector; } /** * Try to register the user of the given id at the node and for later usage in this launcher, i.e. for service * method calls via {@link #invoke}. * * @param id id or login of the agent to load * @param passphrase passphrase to unlock the private key of the agent * @return the registered agent */ public boolean registerUserAgent(String id, String passphrase) { try { if (id.matches("-?[0-9].*")) { currentUser = (UserAgent) node.getAgent(Long.valueOf(id)); } else { currentUser = (UserAgent) node.getAgent(node.getUserManager().getAgentIdByLogin(id)); } currentUser.unlockPrivateKey(passphrase); node.registerReceiver(currentUser); return true; } catch (Exception e) { logger.printStackTrace(e); currentUser = null; return false; } } /** * Register the given agent at the las2peer node and for later usage with {@link #invoke}. * * Make sure, that the private key of the agent is unlocked before registering * * @param agent * @throws L2pSecurityException * @throws AgentAlreadyRegisteredException * @throws AgentException */ public void registerUserAgent(UserAgent agent) throws L2pSecurityException, AgentAlreadyRegisteredException, AgentException { registerUserAgent(agent, null); } /** * Register the given agent at the las2peer node and for later usage with {@link #invoke}. * * If the private key of the agent is not unlocked and a pass phrase has been given, an attempt to unlock the key is * started before registering. * * @param agent * @param passphrase * @throws L2pSecurityException * @throws AgentAlreadyRegisteredException * @throws AgentException */ public void registerUserAgent(UserAgent agent, String passphrase) throws L2pSecurityException, AgentException { if (passphrase != null && agent.isLocked()) { agent.unlockPrivateKey(passphrase); } if (agent.isLocked()) { throw new IllegalStateException("You have to unlock the agent first or give a correct passphrase!"); } try { node.registerReceiver(agent); } catch (AgentAlreadyRegisteredException e) { } currentUser = agent; } /** * Unregister the current user from the las2peer node and from this launcher. * * @see #registerUserAgent */ public void unregisterCurrentAgent() { if (currentUser == null) { return; } try { node.unregisterReceiver(currentUser); } catch (AgentNotKnownException | NodeException e) { } currentUser = null; } /** * Invokes a service method as the current agent, choosing an approptiate service version. * * The arguments must be passed via ONE String separated by "-". * * @see #registerUserAgent * @param serviceIdentifier * @param serviceMethod * @param parameters pass an empty string if you want to call a method without parameters * @return * @throws L2pServiceException any exception during service method invocation */ public Serializable invoke(String serviceIdentifier, String serviceMethod, String parameters) throws L2pServiceException { if (parameters.isEmpty()) { return invoke(serviceIdentifier, serviceMethod, new Serializable[0]); } String[] split = parameters.trim().split("-"); return invoke(serviceIdentifier, serviceMethod, (Serializable[]) split); } /** * Invokes a service method as the current agent, choosing an approptiate service version. * * @see #registerUserAgent * @param serviceIdentifier * @param serviceMethod * @param parameters * @return * @throws L2pServiceException any exception during service method invocation */ private Serializable invoke(String serviceIdentifier, String serviceMethod, Serializable... parameters) throws L2pServiceException { if (currentUser == null) { throw new IllegalStateException("Please register a valid user with registerUserAgent before invoking!"); } try { return node.invoke(currentUser, serviceIdentifier, serviceMethod, parameters); } catch (Exception e) { throw new L2pServiceException("Exception during service method invocation!", e); } } /** * Returns a list of available methods for the given service class name. * * @param serviceNameVersion Exact service name and version, same syntax as in {@link #startService(String)} * @return list of methods encapsulated in a ListMethodsContent * @throws L2pSecurityException * @throws AgentNotKnownException * @throws InterruptedException * @throws SerializationException * @throws EncodingFailedException * @throws TimeoutException */ public ListMethodsContent getServiceMethods(String serviceNameVersion) throws L2pSecurityException, AgentNotKnownException, InterruptedException, EncodingFailedException, SerializationException, TimeoutException { if (currentUser == null) { throw new IllegalStateException("please log in a valid user with registerUserAgent before!"); } Agent receiver = node.getServiceAgent(ServiceNameVersion.fromString(serviceNameVersion), currentUser); Message request = new Message(currentUser, receiver, new ListMethodsContent()); request.setSendingNodeId((NodeHandle) node.getNodeId()); Message response = node.sendMessageAndWaitForAnswer(request); response.open(currentUser, node); return (ListMethodsContent) response.getContent(); } /** * Starts a service with a known agent or generate a new agent for the service (using a random passphrase) * * Will create an xml file for the generated agent and store the passphrase lcoally * * @param serviceNameVersion Specify the service name and version to run: package.serviceClass@Version. Exact match * required. * @throws Exception on error */ public void startService(String serviceNameVersion) throws Exception { String passPhrase = SimpleTools.createRandomString(20); startService(serviceNameVersion, passPhrase); } /** * start a service with a known agent or generate a new agent for the service * * will create an xml file for the generated agent and store the passphrase lcoally * * @param serviceNameVersion the exact name and version of the service to be started * @param defaultPass this pass will be used to generate the agent if no agent exists * @throws Exception on error */ public void startService(String serviceNameVersion, String defaultPass) throws Exception { ServiceNameVersion service = ServiceNameVersion.fromString(serviceNameVersion); if (service.getVersion() == null && service.getVersion().toString().equals("*")) { printError("You must specify an exact version of the service you want to start."); return; } File file = new File(DEFAULT_SERVICE_AGENT_DIRECTORY + serviceNameVersion + ".xml"); if (!file.exists()) { // create agent ServiceAgent a = ServiceAgent.createServiceAgent(service, defaultPass); file.getParentFile().mkdirs(); file.createNewFile(); // save agent Files.write(file.toPath(), a.toXmlString().getBytes()); // save passphrase Path passphrasesPath = Paths.get(DEFAULT_SERVICE_AGENT_DIRECTORY + "passphrases.txt"); String passphraseLine = serviceNameVersion + ".xml;" + defaultPass; try { Files.write(passphrasesPath, ("\n" + passphraseLine).getBytes(), StandardOpenOption.APPEND); } catch (NoSuchFileException e) { Files.write(passphrasesPath, passphraseLine.getBytes(), StandardOpenOption.CREATE); } } // get passphrase from file Hashtable<String, String> htPassphrases = loadPassphrases(DEFAULT_SERVICE_AGENT_DIRECTORY + "passphrases.txt"); if (htPassphrases.containsKey(serviceNameVersion.toString() + ".xml")) { defaultPass = htPassphrases.get(serviceNameVersion.toString() + ".xml"); } // start startServiceXml(file.toPath().toString(), defaultPass); } /** * start a service defined by an XML file of the corresponding agent * * @param file path to the file containing the service * @param passphrase passphrase to unlock the service agent * @return the service agent * @throws Exception on error */ public ServiceAgent startServiceXml(String file, String passphrase) throws Exception { try { ServiceAgent xmlAgent = ServiceAgent.createFromXml(FileContentReader.read(file)); ServiceAgent serviceAgent; try { // check if the agent is already known to the network serviceAgent = (ServiceAgent) node.getAgent(xmlAgent.getId()); serviceAgent.unlockPrivateKey(passphrase); } catch (AgentNotKnownException e) { xmlAgent.unlockPrivateKey(passphrase); node.storeAgent(xmlAgent); logger.info("ServiceAgent was not known in network. Published it"); serviceAgent = xmlAgent; } startService(serviceAgent); return serviceAgent; } catch (Exception e) { logger.log(Level.SEVERE, "Starting service failed", e); throw e; } } /** * start the service defined by the given (Service-)Agent * * @param serviceAgent * @throws AgentAlreadyRegisteredException * @throws L2pSecurityException * @throws AgentException */ public void startService(Agent serviceAgent) throws AgentAlreadyRegisteredException, L2pSecurityException, AgentException { if (!(serviceAgent instanceof ServiceAgent)) { throw new IllegalArgumentException("given Agent is not a service agent!"); } if (serviceAgent.isLocked()) { throw new IllegalStateException("You have to unlock the agent before starting the corresponding service!"); } node.registerReceiver(serviceAgent); } /** * stop the given service * * needs name and version * * @param serviceNameVersion * @throws AgentNotKnownException * @throws NoSuchServiceException * @throws NodeException */ public void stopService(String serviceNameVersion) throws AgentNotKnownException, NoSuchServiceException, NodeException { ServiceAgent agent = node.getLocalServiceAgent(ServiceNameVersion.fromString(serviceNameVersion)); node.unregisterReceiver(agent); } /** * load an agent from an XML file and return it for later usage * * @param filename name of the file to load * @return the loaded agent * @throws AgentException */ public Agent loadAgentFromXml(String filename) throws AgentException { try { String contents = FileContentReader.read(filename); Agent result = Agent.createFromXml(contents); return result; } catch (Exception e) { throw new AgentException("problems loading an agent from the given file", e); } } /** * try to unlock the private key of the given agent with the given pass phrase * * @param agent * @param passphrase * @throws L2pSecurityException */ public void unlockAgent(PassphraseAgent agent, String passphrase) throws L2pSecurityException { agent.unlockPrivateKey(passphrase); } /** * start interactive console mode based on a {@link i5.las2peer.tools.CommandPrompt} */ public void interactive() { System.out.println("Entering interactive mode for node " + this.getNode().getPastryNode().getId().toStringFull() + "\n" + " + "Enter 'help' for further information of the console.\n" + "Use all public methods of the L2pNodeLauncher class for interaction with the P2P network.\n\n"); commandPrompt.startPrompt(); System.out.println("Exiting interactive mode for node " + this); } /** * get the information stored about the local Node * * @return a node information * @throws CryptoException */ public NodeInformation getLocalNodeInfo() throws CryptoException { return node.getNodeInformation(); } /** * get information about other nodes (probably neighbors in the ring etc) * * @return string with node information */ public String getNetInfo() { return SimpleTools.join(node.getOtherKnownNodes(), "\n\t"); } /** * Creates a new node launcher instance. * * @param port local port number to open * @param bootstrap comma separated list of bootstrap nodes to connect to or "-" for a new network * @param storageMode A {@link STORAGE_MODE} used by the local node instance for persistence. * @param monitoringObserver determines, if the monitoring-observer will be started at this node * @param cl the class loader to be used with this node * @param nodeIdSeed the seed to generate node IDs from */ private L2pNodeLauncher(Integer port, String bootstrap, STORAGE_MODE storageMode, boolean monitoringObserver, L2pClassManager cl, Long nodeIdSeed) { if (storageMode == null) { if (System.getenv().containsKey("MEM_STORAGE")) { storageMode = STORAGE_MODE.MEMORY; } else { storageMode = STORAGE_MODE.FILESYSTEM; } } node = new PastryNodeImpl(cl, monitoringObserver, port, bootstrap, storageMode, nodeIdSeed); commandPrompt = new CommandPrompt(this); } /** * actually start the node * * @throws NodeException */ private void start() throws NodeException { node.launch(); printMessage("node started!"); } /** * Prints a message to the console. * * @param message */ private static void printMessage(String message) { logger.info(message); } /** * Prints a (Yellow) warning message to the console. * * @param message */ private static void printWarning(String message) { message = ColoredOutput.colorize(message, ColoredOutput.ForegroundColor.Yellow); logger.warning(message); } /** * Prints a (Red) error message to the console. * * @param message */ private static void printError(String message) { message = ColoredOutput.colorize(message, ColoredOutput.ForegroundColor.Red); logger.severe(message); } /** * Prints a (Red) error message to the console including a stack trace. * * @param message */ private static void printErrorWithStacktrace(String message, Throwable throwable) { message = ColoredOutput.colorize(message, ColoredOutput.ForegroundColor.Red); logger.log(Level.SEVERE, message, throwable); } /** * Launches a single node. * * @param args * @return the L2pNodeLauncher instance * @throws NodeException */ public static L2pNodeLauncher launchSingle(Iterable<String> args) throws NodeException { boolean debugMode = false; Integer port = null; String bootstrap = null; STORAGE_MODE storageMode = null; boolean observer = false; String sLogDir = null; ArrayList<String> serviceDirectories = null; Long nodeIdSeed = null; List<String> commands = new ArrayList<>(); // parse args Iterator<String> itArg = args.iterator(); while (itArg.hasNext() == true) { String arg = itArg.next(); itArg.remove(); String larg = arg.toLowerCase(); if (larg.equals("-debug") || larg.equals("--debug")) { debugMode = true; } else if (larg.equals("-p") == true || larg.equals("--port") == true) { if (itArg.hasNext() == false) { printWarning("ignored '" + arg + "', because port number expected after it"); } else { String sPort = itArg.next(); try { int p = Integer.valueOf(sPort); // in case of an exception this structure doesn't override an already set port number itArg.remove(); port = p; } catch (NumberFormatException ex) { printWarning("ignored '" + arg + "', because " + sPort + " is not an integer"); } } } else if (larg.equals("-b") == true || larg.equals("--bootstrap") == true) { if (itArg.hasNext() == false) { printWarning("ignored '" + arg + "', because comma separated bootstrap list expected after it"); } else { String[] bsList = itArg.next().split(","); for (String bs : bsList) { if (bs.isEmpty() == false) { if (bootstrap == null || bootstrap.isEmpty() == true) { bootstrap = bs; } else { bootstrap += "," + bs; } } } itArg.remove(); } } else if (larg.equals("-o") == true || larg.equals("--observer") == true) { observer = true; } else if (larg.equals("-l") == true || larg.equals("--log-directory") == true) { if (itArg.hasNext() == false) { printWarning("ignored '" + arg + "', because log directory expected after it"); } else { sLogDir = itArg.next(); itArg.remove(); } } else if (larg.equals("-n") == true || larg.equals("--node-id-seed") == true) { if (itArg.hasNext() == false) { printWarning("ignored '" + arg + "', because node id seed expected after it"); } else { String sNodeId = itArg.next(); try { long idSeed = Long.valueOf(sNodeId); // in case of an exception this structure doesn't override an already set node id seed itArg.remove(); nodeIdSeed = idSeed; } catch (NumberFormatException ex) { printWarning("ignored '" + arg + "', because " + sNodeId + " is not an integer"); } } } else if (larg.equals("-s") == true || larg.equals("--service-directory") == true) { if (itArg.hasNext() == false) { printWarning("ignored '" + arg + "', because service directory expected after it"); } else { if (serviceDirectories == null) { serviceDirectories = new ArrayList<>(); } serviceDirectories.add(itArg.next()); itArg.remove(); } } else if (larg.equals("-m") == true || larg.equals("--storage-mode") == true) { if (itArg.hasNext() == false) { printWarning("ignored '" + arg + "', because storage mode expected after it"); } else { String val = itArg.next(); if (val.equals("memory")) { storageMode = STORAGE_MODE.MEMORY; } else if (val.equals("filesystem")) { storageMode = STORAGE_MODE.FILESYSTEM; } else { printWarning("ignored '" + arg + "', because storage mode expected after it"); } itArg.remove(); } } else { commands.add(arg); } } // check parameters and launch node if (debugMode) { System.err.println("WARNING! Launching node in DEBUG mode! THIS NODE IS NON PERSISTENT!"); return launchDebug(port, bootstrap, sLogDir, serviceDirectories, commands); } else { if (port == null) { printError("no port number specified"); return null; } else if (port < 1) { printError("invalid port number specified"); return null; } return launchSingle(port, bootstrap, storageMode, observer, sLogDir, serviceDirectories, nodeIdSeed, commands); } } public static L2pNodeLauncher launchSingle(int port, String bootstrap, STORAGE_MODE storageMode, boolean observer, String sLogDir, Iterable<String> serviceDirectories, Long nodeIdSeed, Iterable<String> commands) throws NodeException { // check parameters if (sLogDir != null) { try { L2pLogger.setGlobalLogDirectory(sLogDir); } catch (Exception ex) { printWarning("couldn't use '" + sLogDir + "' as log directory." + ex); } } Repository[] repositories = new Repository[0]; // default only network class loading if (serviceDirectories != null) { repositories = new Repository[] { new FileSystemRepository(serviceDirectories, true) }; } if (commands == null) { commands = new ArrayList<>(); } // instantiate launcher L2pClassManager cl = new L2pClassManager(repositories, L2pNodeLauncher.class.getClassLoader()); L2pNodeLauncher launcher = new L2pNodeLauncher(port, bootstrap, storageMode, observer, cl, nodeIdSeed); // handle commands try { launcher.start(); for (String command : commands) { System.out.println("Handling: '" + command + "'"); launcher.commandPrompt.handleLine(command); } if (launcher.isFinished()) { printMessage("All commands have been handled and shutdown has been called -> end!"); } else { printMessage("All commands have been handled -- keeping node open!"); } } catch (NodeException e) { launcher.bFinished = true; logger.printStackTrace(e); throw e; } return launcher; } private static L2pNodeLauncher launchDebug(Integer port, String boostrap, String sLogDir, Iterable<String> serviceDirectories, Iterable<String> commands) throws NodeException { // check parameters if (sLogDir != null) { try { L2pLogger.setGlobalLogDirectory(sLogDir); } catch (Exception ex) { printWarning("couldn't use '" + sLogDir + "' as log directory." + ex); } } if (serviceDirectories == null) { ArrayList<String> directories = new ArrayList<>(); directories.add(DEFAULT_SERVICE_DIRECTORY); serviceDirectories = directories; } if (commands == null) { commands = new ArrayList<>(); } // instantiate launcher L2pClassManager cl = new L2pClassManager(new FileSystemRepository(serviceDirectories, true), L2pNodeLauncher.class.getClassLoader()); L2pNodeLauncher launcher = new L2pNodeLauncher(port, boostrap, STORAGE_MODE.MEMORY, false, cl, null); // handle commands try { launcher.start(); for (String command : commands) { System.out.println("Handling: '" + command + "'"); launcher.commandPrompt.handleLine(command); } if (launcher.isFinished()) { printMessage("All commands have been handled and shutdown has been called -> end!"); } else { printMessage("All commands have been handled -- keeping node open!"); } } catch (NodeException e) { launcher.bFinished = true; logger.printStackTrace(e); throw e; } return launcher; } /** * Prints a help message for command line usage. * * @param message a custom message that will be shown before the help message content */ public static void printHelp(String message) { if (message != null && !message.isEmpty()) { System.out.println(message + "\n\n"); } System.out.println("las2peer Node Launcher"); System.out.println(" System.out.println("Usage:\n"); System.out.println("Help Message:"); System.out.println("\t['--help'|'-h']"); System.out.println("las2peer version:"); System.out.println("\t['--version'|'-v']"); System.out.println("\nStart Node:"); System.out .println("\t{optional: --colored-shell|-c} -p [port] {optional1} {optional2} {method1} {method2} ..."); System.out.println("\nOptional arguments"); System.out.println("\t--colored-shell|-c enables colored output (better readable command line)\n"); System.out.println("\t--log-directory|-l [directory] lets you choose the directory for log files (default: " + L2pLogger.DEFAULT_LOG_DIRECTORY + ")\n"); System.out.println( "\t--service-directory|-s [directory] adds the directory you added your services to, to the class loader. This argument can occur multiple times.\n"); System.out.println("\t--port|-p [port] specifies the port number of the node\n"); System.out.println("\tno bootstrap argument states, that a complete new las2peer network is to start"); System.out.println("\tor"); System.out.println( "\t--bootstrap|-b [host-list] requires a comma seperated list of [address:ip] pairs of bootstrap nodes to connect to. This argument can occur multiple times.\n"); System.out.println("\t--observer|-o starts a monitoring observer at this node\n"); System.out.println( "\t--node-id-seed|-n [long] generates the node id by using this seed to provide persistence\n"); System.out .println("\t--storage-mode|-m filesystem|memory sets Pastry's storage mode, defaults to filesystem\n"); System.out.println("The following methods can be used in arbitrary order and number:"); for (Method m : L2pNodeLauncher.class.getMethods()) { if (Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers())) { System.out.print("\t- " + m.getName()); for (int i = 0; i < m.getParameterTypes().length; i++) { System.out.print(" " + m.getParameterTypes()[i].getName() + " "); } System.out.print("\n"); } } } /** * Prints a help message for command line usage. */ public static void printHelp() { printHelp(null); } /** * Prints the las2peer version. */ public static void printVersion() { Package p = L2pNodeLauncher.class.getPackage(); String version = p.getImplementationVersion(); System.out.println("las2peer version \"" + version + "\""); } /** * Main method for command line processing. * * The method will start a node and try to invoke all command line parameters as parameterless methods of this * class. * * Hint: with "log-directory=.." you can set the logfile directory you want to use. * * Hint: with "service-directory=.." you can set the directory your service jars are located at. * * @param argv * @throws InterruptedException * @throws MalformedXMLException * @throws IOException * @throws L2pSecurityException * @throws EncodingFailedException * @throws SerializationException * @throws NodeException */ public static void main(String[] argv) throws InterruptedException, MalformedXMLException, IOException, L2pSecurityException, EncodingFailedException, SerializationException, NodeException { System.setSecurityManager(new L2pSecurityManager()); // self test encryption environment try { CryptoTools.encryptSymmetric("las2peer rulez!".getBytes(), CryptoTools.generateSymmetricKey()); } catch (CryptoException e) { throw new L2pSecurityException( "Fatal Error! Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files are not installed!", e); } // parse command line parameter into list List<String> instArgs = new ArrayList<>(); // a command can have brackets with spaces inside, which is split by arg parsing falsely List<String> argvJoined = new ArrayList<>(); String joined = ""; for (String arg : argv) { int opening = arg.length() - arg.replace("(", "").length(); // nice way to count opening brackets int closing = arg.length() - arg.replace(")", "").length(); if (opening == closing && joined.isEmpty()) { // just an argument argvJoined.add(arg); } else { // previous arg was unbalanced, attach this arg joined += arg; int openingJoined = joined.length() - joined.replace("(", "").length(); int closingJoined = joined.length() - joined.replace(")", "").length(); if (openingJoined == closingJoined) { // now its balanced argvJoined.add(joined); joined = ""; } else if (openingJoined < closingJoined) { throw new IllegalArgumentException("command \"" + joined + "\" has too many closing brackets!"); } // needs more args to balance } } if (!joined.isEmpty()) { throw new IllegalArgumentException("command \"" + joined + "\" has too many opening brackets!"); } for (String arg : argvJoined) { String larg = arg.toLowerCase(); if (larg.equals("-h") == true || larg.equals("--help") == true) { // Help Message printHelp(); System.exit(1); } else if (larg.equals("-v") || larg.equals("--version")) { printVersion(); System.exit(1); } else if (larg.equals("-w") || larg.equals("--windows-shell")) { printWarning( "Ignoring obsolete argument '" + arg + "', because colored output is disabled by default."); } else if (larg.equals("-c") == true || larg.equals("--colored-shell") == true) { // turn on colored output ColoredOutput.allOn(); } else { // node instance parameter instArgs.add(arg); } } // Launches the node L2pNodeLauncher launcher = launchSingle(instArgs); if (launcher == null) { System.exit(2); } if (launcher.isFinished()) { System.out.println("node has handled all commands and shut down!"); try { Iterator<Connector> iterator = connectors.iterator(); while (iterator.hasNext()) { iterator.next().stop(); } } catch (ConnectorException e) { logger.printStackTrace(e); } } else { System.out.println("node has handled all commands -- keeping node open\n"); System.out.println("press Strg-C to exit\n"); try { while (true) { Thread.sleep(5000); } } catch (InterruptedException e) { try { Iterator<Connector> iterator = connectors.iterator(); while (iterator.hasNext()) { iterator.next().stop(); } } catch (ConnectorException ce) { logger.printStackTrace(ce); } } } } }
package io.cfp.controller; import io.cfp.domain.exception.NotVerifiedException; import io.cfp.dto.RestrictedMeter; import io.cfp.entity.Role; import io.cfp.entity.User; import io.cfp.service.TalkUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.annotation.Secured; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController("statscontroller_v0") @RequestMapping(value = { "/v0/stats", "/api/stats" }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public class StatsController { @Autowired private TalkUserService talkService; @RequestMapping("/meter") @Secured(Role.AUTHENTICATED) public RestrictedMeter meter(@AuthenticationPrincipal User user) throws NotVerifiedException { RestrictedMeter res = new RestrictedMeter(); res.setTalks(talkService.count(user.getId())); return res; } }
package io.schinzel.basicutils; import java.time.Instant; import java.time.temporal.ChronoField; import java.util.Arrays; import java.util.Random; /** * The purpose of this class is to generate random strings. This class offers * random static methods and * * @author schinzel */ public class RandomUtil { private final Random mRandom; /** * Holds the chars that can be a part of the random string. */ private static final char[] SYMBOLS; /** * Set up the chars that can be used in the random string. */ static { StringBuilder tmp = new StringBuilder(); for (char ch = '0'; ch <= '9'; ++ch) { tmp.append(ch); } for (char ch = 'a'; ch <= 'z'; ++ch) { tmp.append(ch); } SYMBOLS = tmp.toString().toCharArray(); } /** * * @return A newly created instance with random seed. */ public static RandomUtil create() { return new RandomUtil(RandomUtil.generateSeed()); } /** * * @param seed The seed for random values * @return An newly created instance with the argument seed. */ public static RandomUtil create(long seed) { return new RandomUtil(seed); } /** * The returned seed is compiled from the nano time. * * @return A seed. */ static long generateSeed() { long seed = 1; //Get nanos long nanos = System.nanoTime(); long divider = 1000000; if (nanos > divider * 1000) { nanos -= (nanos / divider) * divider; } seed += nanos; //Get the millis of current second long milliOfSecond = Instant.now().getLong(ChronoField.MILLI_OF_SECOND); seed *= milliOfSecond; return seed; } /** * * @param min The min value of the returned number * @param max The max value of the returned number * @return A random number */ public int getInt(int min, int max) { if (min > max) { throw new RuntimeException("Max need to be larger than min"); } Thrower.throwErrorIfOutsideRange(min, "min", -100, Integer.MAX_VALUE); Thrower.throwErrorIfOutsideRange(max, "max", 1, Integer.MAX_VALUE); return mRandom.nextInt(max - min + 1) + min; } /** * Randomize a double * * @param min The min of returned value * @param max The max of returned value * @return */ public double getDouble(double min, double max) { return min + (max - min) * mRandom.nextDouble(); } /** * * @param length The length of the string to return. * @return A string with random chars. */ public String getString(int length) { Thrower.throwErrorIfOutsideRange(length, "length", 0, 500); char[] buf = new char[length]; for (int idx = 0; idx < buf.length; ++idx) { buf[idx] = SYMBOLS[mRandom.nextInt(SYMBOLS.length)]; } return new String(buf); } /** * Adds leading zeros to returned number so that returned string always is * same or larger than the argument padding. * * For example, min=1 and max=9 and padding 2 yields a string "04" for * example. * * If padding is smaller than the length of the returned value, the value is * returned as is. For example, the random generated is 123 and the padding * argument is 1, then "123" will be returned. * * * @param min * @param max * @param padding The returned string will at least have this length. Min 1 * and max 100. * @return A padded int as a string. */ public String getPaddedInt(int min, int max, int padding) { Thrower.throwErrorIfOutsideRange(padding, "padding", 1, 100); String paddingFormat = "%0" + padding + "d"; return String.format(paddingFormat, this.getInt(min, max)); } /** * Populates an integer array with random value. * * @param arraySize The number of elements in the returned array. * @param arraySum The sum of the values in the returned array. * @return A random integer array. */ public int[] getIntArray(int arraySize, int arraySum) { Thrower.throwErrorIfOutsideRange(arraySize, "arraySize", 1, Integer.MAX_VALUE); int sum = arraySum; if (sum <= arraySize) { throw new RuntimeException("Array size needs to be larger than sum"); } int vals[] = new int[arraySize]; sum -= arraySize; for (int i = 0; i < arraySize - 1; ++i) { vals[i] = mRandom.nextInt(sum); } vals[arraySize - 1] = sum; Arrays.sort(vals); for (int i = arraySize - 1; i > 0; --i) { vals[i] -= vals[i - 1]; } for (int i = 0; i < arraySize; ++i) { ++vals[i]; } return vals; } /** * * @param min The min value of the returned number * @param max The max value of the returned number * @return A random number */ public static int getRandomNumber(int min, int max) { return RandomUtil.create().getInt(min, max); } /** * * @param length The length of the string to return. * @return A string with random chars. */ public static String getRandomString(int length) { return RandomUtil.create().getString(length); } }
package io.sigpipe.sing.dataset; import java.util.NavigableSet; import java.util.TreeSet; import io.sigpipe.sing.dataset.feature.Feature; public class Quantizer { private NavigableSet<Feature> ticks = new TreeSet<>(); public Quantizer(Object start, Object end, Object step) { this( Feature.fromPrimitiveType(start), Feature.fromPrimitiveType(end), Feature.fromPrimitiveType(step)); } public Quantizer(Feature start, Feature end, Feature step) { if (start.sameType(end) == false || start.sameType(step) == false) { throw new IllegalArgumentException( "All feature types must be the same"); } Feature tick = new Feature(start); while (tick.less(end)) { insertTick(tick); tick = tick.add(step); } } public void insertTick(Feature tick) { ticks.add(tick); } public void removeTick(Feature tick) { ticks.remove(tick); } public Feature quantize(Feature feature) { Feature result = ticks.floor(feature); if (result == null) { return ticks.first(); } return result; } public Feature nextTick(Feature feature) { Feature result = ticks.higher(feature); //TODO this will return null when feature > highest tick, but should //actually return 'end' return result; /** * Retrieves the tick mark value preceding the given Feature. In other * words, this method will return the bucket before the given Feature's * bucket. If there is no previous tick mark (the specified Feature's bucket * is at the beginning of the range) then this method returns null. * * @param feature Feature to use to locate the previous tick mark bucket in * the range. * @return Next tick mark, or null if the end of the range has been reached. */ public Feature prevTick(Feature feature) { return ticks.lower(feature); } @Override public String toString() { String output = ""; for (Feature f : ticks) { output += f.getString() + System.lineSeparator(); } return output; } }
package javax.time.calendar; /** * Provides common implementations of {@code DateResolver}. * <p> * This is a thread-safe utility class. * All resolvers returned are immutable and thread-safe. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ public final class DateResolvers { /** * Private constructor since this is a utility class. */ private DateResolvers() { } /** * Returns the strict resolver which does not manipulate the state * in any way, resulting in an exception for all invalid values. * <p> * The invalid input 2011-02-30 will throw an exception.<br /> * The invalid input 2012-02-30 will throw an exception (leap year).<br /> * The invalid input 2011-04-31 will throw an exception. * * @return the strict resolver, not null */ public static DateResolver strict() { return Impl.STRICT; } /** * Returns the previous valid day resolver, which adjusts the date to be * valid by moving to the last valid day of the month. * <p> * The invalid input 2011-02-30 will return 2011-02-28.<br /> * The invalid input 2012-02-30 will return 2012-02-29 (leap year).<br /> * The invalid input 2011-04-31 will return 2011-04-30. * * @return the previous valid day resolver, not null */ public static DateResolver previousValid() { return Impl.PREVIOUS_VALID; } /** * Returns the next valid day resolver, which adjusts the date to be * valid by moving to the first of the next month. * <p> * The invalid input 2011-02-30 will return 2011-03-01.<br /> * The invalid input 2012-02-30 will return 2012-03-01 (leap year).<br /> * The invalid input 2011-04-31 will return 2011-05-01. * * @return the next valid day resolver, not null */ public static DateResolver nextValid() { return Impl.NEXT_VALID; } /** * Returns the part lenient resolver, which adjusts the date to be * valid by moving it to the next month by the number of days that * are invalid up to the 31st of the month. * <p> * The invalid input 2011-02-29 will return 2011-03-01.<br /> * The invalid input 2011-02-30 will return 2011-03-02.<br /> * The invalid input 2011-02-31 will return 2011-03-03.<br /> * The invalid input 2012-02-30 will return 2012-03-01 (leap year).<br /> * The invalid input 2012-02-31 will return 2012-03-02 (leap year).<br /> * The invalid input 2011-04-31 will return 2011-05-01. * * @return the part lenient resolver, not null */ public static DateResolver partLenient() { return Impl.PART_LENIENT; } /** * Enum implementing the resolvers. */ private static enum Impl implements DateResolver { /** Strict resolver. */ STRICT { /** {@inheritDoc} */ public LocalDate resolveDate(int year, MonthOfYear monthOfYear, int dayOfMonth) { return LocalDate.of(year, monthOfYear, dayOfMonth); } }, /** Previous valid resolver. */ PREVIOUS_VALID { /** {@inheritDoc} */ public LocalDate resolveDate(int year, MonthOfYear monthOfYear, int dayOfMonth) { int lastDay = monthOfYear.getLastDayOfMonth(ISOChronology.isLeapYear(year)); if (dayOfMonth > lastDay) { return LocalDate.of(year, monthOfYear, lastDay); } return LocalDate.of(year, monthOfYear, dayOfMonth); } }, /** Next valid resolver. */ NEXT_VALID { /** {@inheritDoc} */ public LocalDate resolveDate(int year, MonthOfYear monthOfYear, int dayOfMonth) { int len = monthOfYear.lengthInDays(ISOChronology.isLeapYear(year)); if (dayOfMonth > len) { return LocalDate.of(year, monthOfYear.next(), 1); } return LocalDate.of(year, monthOfYear, dayOfMonth); } }, /** Part lenient resolver. */ PART_LENIENT { /** {@inheritDoc} */ public LocalDate resolveDate(int year, MonthOfYear monthOfYear, int dayOfMonth) { int len = monthOfYear.lengthInDays(ISOChronology.isLeapYear(year)); if (dayOfMonth > len) { // this line works because December is never invalid assuming the input is from 1-31 return LocalDate.of(year, monthOfYear.next(), dayOfMonth - len); } return LocalDate.of(year, monthOfYear, dayOfMonth); } }, } }
package javax.time.calendar; import javax.time.CalendricalException; import javax.time.Instant; import javax.time.calendar.zone.ZoneOffsetTransition; import javax.time.calendar.zone.ZoneRules; /** * Provides common implementations of {@code ZoneResolver}. * <p> * A {@link ZoneResolver} provides a strategy for handling the gaps and overlaps * on the time-line that occur due to changes in the offset from UTC, usually * caused by Daylight Savings Time. * <p> * ZoneResolvers is a utility class. * All resolvers returned are immutable and thread-safe. * * @author Stephen Colebourne */ public final class ZoneResolvers { /** * Private constructor. */ private ZoneResolvers() { } /** * Returns the strict zone resolver which rejects all gaps and overlaps * as invalid, resulting in an exception. * * @return the strict resolver, not null */ public static ZoneResolver strict() { return Strict.INSTANCE; } /** * Class implementing strict resolver. */ private static class Strict extends ZoneResolver { /** The singleton instance. */ private static final Strict INSTANCE = new Strict(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { throw new CalendricalException("Local time " + newDateTime + " does not exist in time-zone " + zone + " due to a gap in the local time-line"); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { throw new CalendricalException("Local time " + newDateTime + " has two matching offsets, " + discontinuity.getOffsetBefore() + " and " + discontinuity.getOffsetAfter() + ", in time-zone " + zone); } } /** * Returns the pre-transition zone resolver, which returns the instant * one nanosecond before the transition for gaps, and the earlier offset * for overlaps. * * @return the pre-transition resolver, not null */ public static ZoneResolver preTransition() { return PreTransition.INSTANCE; } /** * Class implementing preTransition resolver. */ private static class PreTransition extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PreTransition(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { Instant instantBefore = discontinuity.getInstant().minusNanos(1); return OffsetDateTime.ofInstant(instantBefore, discontinuity.getOffsetBefore()); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetBefore()); } } /** * Returns the post-transition zone resolver, which returns the instant * after the transition for gaps, and the later offset for overlaps. * * @return the post-transition resolver, not null */ public static ZoneResolver postTransition() { return PostTransition.INSTANCE; } /** * Class implementing postTransition resolver. */ private static class PostTransition extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PostTransition(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } /** * Returns the post-gap-pre-overlap zone resolver, which returns the instant * after the transition for gaps, and the earlier offset for overlaps. * * @return the post-transition resolver, not null */ public static ZoneResolver postGapPreOverlap() { return PostGapPreOverlap.INSTANCE; } /** * Class implementing postGapPreOverlap resolver. */ private static class PostGapPreOverlap extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PostGapPreOverlap(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetBefore()); } } /** * Returns the retain offset resolver, which returns the instant after the * transition for gaps, and the same offset for overlaps. * <p> * This resolver is the same as the {{@link #postTransition()} resolver with * one additional rule. When processing an overlap, this resolver attempts * to use the same offset as the offset specified in the old date-time. * If that offset is invalid then the later offset is chosen. * <p> * This resolver is most commonly useful when adding or subtracting time * from a {@code ZonedDateTime}. * * @return the retain offset resolver, not null */ public static ZoneResolver retainOffset() { return RetainOffset.INSTANCE; } /** * Class implementing retain offset resolver. */ private static class RetainOffset extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new RetainOffset(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return discontinuity.getDateTimeAfter(); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { if (oldDateTime != null && discontinuity.isValidOffset(oldDateTime.getOffset())) { return OffsetDateTime.of(newDateTime, oldDateTime.getOffset()); } return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } /** * Returns the push forward resolver, which changes the time of the result * in a gap by adding the length of the gap. * <p> * If the discontinuity is a gap, then the resolver will add the length of * the gap in seconds to the local time. * For example, given a gap from 01:00 to 02:00 and a time of 01:20, this * will add one hour to result in 02:20. * <p> * If the discontinuity is an overlap, then the resolver will choose the * later of the two offsets. * * @return the push forward resolver, not null */ public static ZoneResolver pushForward() { return PushForward.INSTANCE; } /** * Class implementing push forward resolver. */ private static class PushForward extends ZoneResolver { /** The singleton instance. */ private static final ZoneResolver INSTANCE = new PushForward(); /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { LocalDateTime result = newDateTime.plus(discontinuity.getTransitionSize()); return OffsetDateTime.of(result, discontinuity.getOffsetAfter()); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return OffsetDateTime.of(newDateTime, discontinuity.getOffsetAfter()); } } /** * Creates a combined resolver, using two different strategies for gap and overlap. * <p> * If either argument is {@code null} then the {@link #strict()} resolver is used. * * @param gapResolver the resolver to use for a gap, null means strict * @param overlapResolver the resolver to use for an overlap, null means strict * @return the combination resolver, not null */ public static ZoneResolver combination(ZoneResolver gapResolver, ZoneResolver overlapResolver) { gapResolver = (gapResolver == null ? strict() : gapResolver); overlapResolver = (overlapResolver == null ? strict() : overlapResolver); if (gapResolver == overlapResolver) { return gapResolver; } return new Combination(gapResolver, overlapResolver); } /** * Class implementing combination resolver. */ private static class Combination extends ZoneResolver { /** The gap resolver. */ private final ZoneResolver gapResolver; /** The overlap resolver. */ private final ZoneResolver overlapResolver; /** * Constructor. * @param gapResolver the resolver to use for a gap, not null * @param overlapResolver the resolver to use for an overlap, not null */ public Combination(ZoneResolver gapResolver, ZoneResolver overlapResolver) { this.gapResolver = gapResolver; this.overlapResolver = overlapResolver; } /** {@inheritDoc} */ @Override protected OffsetDateTime handleGap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return gapResolver.handleGap(zone, rules, discontinuity, newDateTime, oldDateTime); } /** {@inheritDoc} */ @Override protected OffsetDateTime handleOverlap( ZoneId zone, ZoneRules rules, ZoneOffsetTransition discontinuity, LocalDateTime newDateTime, OffsetDateTime oldDateTime) { return overlapResolver.handleOverlap(zone, rules, discontinuity, newDateTime, oldDateTime); } } }
package jdbj; import jdbj.lambda.Binding; import jdbj.lambda.ResultSetMapper; import javax.annotation.concurrent.Immutable; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * Worth noting: BatchedInsertReturnKeysQuery is Mutable * * Also worth noting: returning keys during batch execution is generally not supported. * Usually (Oracle, H2) only the keys from the last batch will be returned. */ @Deprecated //no plans to remove, just wanted you to read the above documentation... public class BatchedInsertReturnKeysQuery<R> { private final List<ValueBindings> batches = new ArrayList<>(); private final NamedParameterStatement statement; private final ResultSetMapper<R> keysMapper; BatchedInsertReturnKeysQuery(NamedParameterStatement statement, ResultSetMapper<R> keysMapper) { this.statement = statement; this.keysMapper = keysMapper; } public Batch startBatch(){ return new Batch(); } public List<R> execute(Connection connection) throws SQLException { if(batches.isEmpty()){ throw new IllegalStateException("no batches to insert"); } final String sql = statement.jdbcSql(batches.get(0)); final List<R> keys = new ArrayList<>(); try (PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { for (ValueBindings batch : batches) { statement.bind(ps, batch); ps.addBatch(); } ps.executeBatch(); try(ResultSet generatedKeys = ps.getGeneratedKeys()){ while(generatedKeys.next()){ keys.add(keysMapper.map(generatedKeys)); } } } return keys; } @Immutable public class Batch implements ValueBindingsBuilder<Batch> { private ValueBindings batch; Batch(){ this(PositionalBindings.empty()); } Batch(ValueBindings batch) { this.batch = batch; } @Override public Batch bind(String name, Binding binding) { if(batch == null){ throw new IllegalStateException("batch already ended, use BatchedInsertQuery#startBatch to create a new batch"); } return new Batch(batch.addValueBinding(name, binding)); } public BatchedInsertReturnKeysQuery<R> endBatch(){ statement.checkAllBindingsPresent(batch); batches.add(batch); batch = null; return BatchedInsertReturnKeysQuery.this; } } }
// PrairieInjector.java package loci.apps.prairie; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import loci.common.RandomAccessInputStream; import loci.common.services.ServiceFactory; import loci.formats.ImageReader; import loci.formats.ome.OMEXMLMetadata; import loci.formats.services.OMEXMLService; import loci.formats.tiff.TiffSaver; import ome.xml.model.primitives.NonNegativeInteger; public class PrairieInjector { public static void main(String[] args) throws Exception { ImageReader reader = new ImageReader(); // enable injection of original metadata as structured annotations reader.setOriginalMetadataPopulated(true); ServiceFactory serviceFactory = new ServiceFactory(); OMEXMLService omexmlService = serviceFactory.getInstance(OMEXMLService.class); // create a metadata store, where info is placed OMEXMLMetadata meta = omexmlService.createOMEXMLMetadata(); // associate that store with the reader reader.setMetadataStore(meta); // parse the Prairie dataset, populating the metadata store // does not read actual image planes String pathToPrairieXMLFile = args[0]; reader.setId(pathToPrairieXMLFile); String[] files = reader.getUsedFiles(); // free resources and close any open files // does not wipe out the metadata store reader.close(); // define regex for matching Prairie TIFF filenames Pattern p = Pattern.compile(".*_Cycle([\\d]+).*_Ch([\\d]+)_([\\d]+).*"); // set the TiffData elements to describe the planar ordering int tiffDataIndex = 0; Map<String, String> uuids = new HashMap<String, String>(); for (String file : files) { if (!isTiff(file)) continue; // extract CZT values from the current filename Matcher m = p.matcher(file); if (!m.matches() || m.groupCount() != 3) { System.err.println("Warning: " + file + " does not conform to " + "Prairie naming convention; skipping."); continue; } int t = Integer.parseInt(m.group(1)) - 1; int c = Integer.parseInt(m.group(2)) - 1; int z = Integer.parseInt(m.group(3)) - 1; meta.setTiffDataFirstC(new NonNegativeInteger(c), 0, tiffDataIndex); meta.setTiffDataFirstZ(new NonNegativeInteger(z), 0, tiffDataIndex); meta.setTiffDataFirstT(new NonNegativeInteger(t), 0, tiffDataIndex); File f = new File(file); String fileName = f.getName(); meta.setUUIDFileName(fileName, 0, tiffDataIndex); String uuid = "urn:uuid:" + UUID.randomUUID().toString(); meta.setUUIDValue(uuid, 0, tiffDataIndex); uuids.put(file, uuid); tiffDataIndex++; } for (String file : files) { if (!isTiff(file)) continue; // set this TIFF file's UUID to the correct one meta.setUUID(uuids.get(file)); // remove BinData element omexmlService.removeBinData(meta); // write out the XML to the TIFF String xml = omexmlService.getOMEXML(meta); RandomAccessInputStream in = new RandomAccessInputStream(file); TiffSaver tiffSaver = new TiffSaver(file); tiffSaver.overwriteComment(in, xml); in.close(); } } private static boolean isTiff(String file) { return file.toLowerCase().endsWith(".tif") || file.toLowerCase().endsWith(".tiff"); } }
package metroinsight.citadel; import java.io.File; import io.vertx.core.AbstractVerticle; import io.vertx.core.DeploymentOptions; import metroinsight.citadel.authorization.AuthorizationVerticle; import metroinsight.citadel.metadata.impl.MetadataVerticle; import metroinsight.citadel.policy.PolicyVerticle; import metroinsight.citadel.rest.RestApiVerticle; import metroinsight.citadel.virtualsensor.impl.VirtualSensorVerticle; public class MainVerticle extends AbstractVerticle { @Override public void start() throws Exception { // Deploy verticles. vertx.deployVerticle(MetadataVerticle.class.getName()); vertx.deployVerticle(VirtualSensorVerticle.class.getName()); vertx.deployVerticle(PolicyVerticle.class.getName()); vertx.deployVerticle(AuthorizationVerticle.class.getName()); DeploymentOptions opts = new DeploymentOptions() .setWorker(true); //System.setProperty("hadoop.home.dir", "/"); //System.setProperty("log4j.configuration", new File("resources", "log4j.properties").toURI().toURL().toString()); opts.setConfig(config()); vertx.deployVerticle(RestApiVerticle.class.getName(), opts, ar -> { if (ar.failed()) { ar.cause().printStackTrace(); } }); } }
package name.abuchen.mvn; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.MessageFormat; import java.util.HashMap; import java.util.Locale; import java.util.Properties; import java.util.Scanner; import org.apache.commons.codec.binary.Hex; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.tukaani.xz.LZMA2Options; import org.tukaani.xz.XZOutputStream; import com.dd.plist.NSDictionary; import com.dd.plist.PropertyListParser; @Mojo(name = "fix-info-plist", defaultPhase = LifecyclePhase.PACKAGE) public class FixInfoPlistMojo extends AbstractMojo { @Parameter(defaultValue = "${project.build.directory}", required = true) private File outputDirectory; @Parameter(defaultValue = "${qualifiedVersion}", required = true) private String projectVersion; @Parameter(required = true) private String productId; @Parameter(required = true) private String appName; @Parameter(required = true) private Properties properties; @Override public void execute() throws MojoExecutionException { Path infoPlist = Paths.get(outputDirectory.getAbsolutePath(), "products", //$NON-NLS-1$ productId, "macosx", //$NON-NLS-1$ "cocoa", //$NON-NLS-1$ "x86_64", //$NON-NLS-1$ appName, "Contents", //$NON-NLS-1$ "Info.plist"); //$NON-NLS-1$ if (!Files.exists(infoPlist)) { getLog().info("Cannot find Info.plist: " + infoPlist.toString()); //$NON-NLS-1$ return; } fixInfoPlist(infoPlist); fixZippedBinaryArchiveInRepository(infoPlist); } private void fixInfoPlist(Path infoPlist) throws MojoExecutionException { try { NSDictionary dictionary = (NSDictionary) PropertyListParser.parse(infoPlist.toFile()); new PropertyReplacer().replace(getLog(), dictionary, properties); PropertyListParser.saveAsXML(dictionary, infoPlist.toFile()); } catch (Exception e) { throw new MojoExecutionException("Error reading/writing Info.plist", e); //$NON-NLS-1$ } } private void fixZippedBinaryArchiveInRepository(Path infoPlist) throws MojoExecutionException { Path archive = Paths.get(outputDirectory.getAbsolutePath(), "repository", //$NON-NLS-1$ "binary", //$NON-NLS-1$ productId + ".executable.cocoa.macosx.x86_64_" + projectVersion); //$NON-NLS-1$ if (!Files.exists(archive)) { getLog().info("Skipping archive manipulation; file not found: " + archive.toString()); //$NON-NLS-1$ return; } try { String oldMD5Hash = getChecksum(archive, "MD5"); //$NON-NLS-1$ String oldSHA256Hash = getChecksum(archive, "SHA-256"); //$NON-NLS-1$ URI uri = URI.create("jar:" + archive.toUri()); //$NON-NLS-1$ try (FileSystem fs = FileSystems.newFileSystem(uri, new HashMap<String, String>())) { Path fileToUpdate = fs.getPath("Info.plist"); //$NON-NLS-1$ Files.copy(infoPlist, fileToUpdate, StandardCopyOption.REPLACE_EXISTING); } String newMD5Hash = getChecksum(archive, "MD5"); //$NON-NLS-1$ String newSHA256Hash = getChecksum(archive, "SHA-256"); //$NON-NLS-1$ // read artifacts.xml to update MD5 hash getLog().info(MessageFormat.format("Updating binary MD5 hash from {0} to {1}", //$NON-NLS-1$ oldMD5Hash, newMD5Hash)); getLog().info(MessageFormat.format("Updating binary SHA256 hash from {0} to {1}", //$NON-NLS-1$ oldSHA256Hash, newSHA256Hash)); Path artifactsJAR = Paths.get(outputDirectory.getAbsolutePath(), "repository", //$NON-NLS-1$ "artifacts.jar"); //$NON-NLS-1$ String artifactsXML = readArtifactsXML(artifactsJAR); String messageFormat = "<property name=''download.md5'' value=''{0}''/>"; //$NON-NLS-1$ artifactsXML = artifactsXML.replace(MessageFormat.format(messageFormat, oldMD5Hash), MessageFormat.format(messageFormat, newMD5Hash)); messageFormat = "<property name=''download.checksum.md5'' value=''{0}''/>"; //$NON-NLS-1$ artifactsXML = artifactsXML.replace(MessageFormat.format(messageFormat, oldMD5Hash), MessageFormat.format(messageFormat, newMD5Hash)); messageFormat = "<property name=''download.checksum.sha-256'' value=''{0}''/>"; //$NON-NLS-1$ artifactsXML = artifactsXML.replace(MessageFormat.format(messageFormat, oldSHA256Hash), MessageFormat.format(messageFormat, newSHA256Hash)); updateArtifactsJAR(artifactsJAR, artifactsXML); updateArtifactsXZ(artifactsXML); } catch (NoSuchAlgorithmException | IOException e) { throw new MojoExecutionException("Failed to update binary archive", e); //$NON-NLS-1$ } } private void updateArtifactsJAR(Path artifactsJAR, String artifactsXML) throws IOException { Path tempFile = Paths.get(outputDirectory.getAbsolutePath(), "artifacts_md5_updated.xml"); //$NON-NLS-1$ Files.write(tempFile, artifactsXML.getBytes(StandardCharsets.UTF_8.name())); URI uri = URI.create("jar:" + artifactsJAR.toUri()); //$NON-NLS-1$ try (FileSystem fs = FileSystems.newFileSystem(uri, new HashMap<String, String>())) { Path fileToUpdate = fs.getPath("artifacts.xml"); //$NON-NLS-1$ Files.copy(tempFile, fileToUpdate, StandardCopyOption.REPLACE_EXISTING); } } private void updateArtifactsXZ(String artifactsXML) throws IOException { Path xzFile = Paths.get(outputDirectory.getAbsolutePath(), "repository", "artifacts.xml.xz"); //$NON-NLS-1$ //$NON-NLS-2$ try (FileOutputStream outfile = new FileOutputStream(xzFile.toFile())) { LZMA2Options options = new LZMA2Options(); options.setDictSize(LZMA2Options.DICT_SIZE_DEFAULT); options.setLcLp(3, 0); options.setPb(LZMA2Options.PB_MAX); options.setMode(LZMA2Options.MODE_NORMAL); options.setNiceLen(LZMA2Options.NICE_LEN_MAX); options.setMatchFinder(LZMA2Options.MF_BT4); options.setDepthLimit(512); try (XZOutputStream outxz = new XZOutputStream(outfile, options)) { outxz.write(artifactsXML.getBytes(StandardCharsets.UTF_8.name())); } } } private String readArtifactsXML(Path artifactsJAR) throws IOException { URI uri = URI.create("jar:" + artifactsJAR.toUri()); //$NON-NLS-1$ try (FileSystem fs = FileSystems.newFileSystem(uri, new HashMap<String, String>())) { Path fileToUpdate = fs.getPath("artifacts.xml"); //$NON-NLS-1$ try (Scanner scanner = new Scanner(fileToUpdate, StandardCharsets.UTF_8.name())) { return scanner.useDelimiter("\\A").next(); //$NON-NLS-1$ } } } private String getChecksum(Path file, String algorithm) throws IOException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(Files.readAllBytes(file)); byte[] digest = md.digest(); return Hex.encodeHexString(digest).toLowerCase(Locale.US); } }
package net.zoldar.ldap.testserver; import org.apache.commons.cli.*; import com.github.trevershick.test.ldap.LdapServerResource; import com.github.trevershick.test.ldap.annotations.LdapConfiguration; import py4j.GatewayServer; import java.util.HashMap; import java.util.Map; public class Server { private static final String PORT_OPTION = "port"; private static GatewayServer gateway; private Map<Integer, LdapServerResource> servers = new HashMap<Integer, LdapServerResource>(); public static void main(String[] args) throws Exception { Options options = new Options(); Option port = new Option("p", PORT_OPTION, true, "GatewayServer port"); options.addOption(port); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("ldap-test-server", options); System.exit(1); return; } int gatewayPort = GatewayServer.DEFAULT_PORT; if (cmd.hasOption(PORT_OPTION)) { String gatewayPortStr = cmd.getOptionValue(PORT_OPTION); gatewayPort = Integer.parseInt(gatewayPortStr); } gateway = new GatewayServer(new Server(), gatewayPort); gateway.start(); System.out.println("Gateway server started on port "+gateway.getPort()+"!"); } private Server() {} public int create(LdapConfiguration config) throws Exception { int port = config.port(); if (servers.containsKey(port)) { if (servers.get(port).isStarted()) { throw new IllegalStateException("LDAP server already running on port " + port); } } LdapServerResource newServer = new LdapServerResourceCreator(config).getResource(); servers.put(port, newServer); return port; } public void destroy() { for (int serverId : servers.keySet()) { destroy(serverId); } } public void destroy(int serverId) { if (servers.containsKey(serverId)) { servers.get(serverId).stop(); } servers.remove(serverId); } public void start() throws Exception { for (int serverId : servers.keySet()) { if (!servers.get(serverId).isStarted()) { servers.get(serverId).start(); } } } public void start(int serverId) throws Exception { if (!servers.get(serverId).isStarted()) { servers.get(serverId).start(); } } public void stop() { for (int serverId : servers.keySet()) { servers.get(serverId).stop(); } } public void stop(int serverId) { if (servers.containsKey(serverId)) { servers.get(serverId).stop(); } } /* functions provided for backwards compatability */ public void start(LdapConfiguration config) throws Exception { LdapServerResource newServer = new LdapServerResourceCreator(config).getResource(); newServer.start(); // destroy any existing servers running destroy(); servers.put(newServer.port(), newServer); } public int port() { return servers.values().iterator().next().port(); } }
package no.stelar7.api.l4j8.impl; import no.stelar7.api.l4j8.basic.calling.*; import no.stelar7.api.l4j8.basic.constants.api.*; import no.stelar7.api.l4j8.basic.constants.types.*; import no.stelar7.api.l4j8.pojo.match.*; import javax.annotation.Nullable; import java.util.*; @SuppressWarnings("unchecked") public final class MatchAPI { private static final MatchAPI INSTANCE = new MatchAPI(); public static MatchAPI getInstance() { return MatchAPI.INSTANCE; } private MatchAPI() { // Hide public constructor } /** * Returns a list of the accounts games * <p> * A number of optional parameters are provided for filtering. * It is up to the caller to ensure that the combination of filter parameters provided is valid for the requested account, otherwise, no matches may be returned. * If beginIndex is specified, but not endIndex, then endIndex defaults to beginIndex+50. * If endIndex is specified, but not beginIndex, then beginIndex defaults to 0. * If both are specified, then endIndex must be greater than beginIndex. * The maximum range allowed is 50, otherwise a 400 error code is returned. * If beginTime is specified, but not endTime, then these parameters are ignored. * If endTime is specified, but not beginTime, then beginTime defaults to the start of the account's match history. * If both are specified, then endTime should be greater than beginTime. * The maximum time range allowed is one week, otherwise a 400 error code is returned. * * @param server the platform the account is on * @param accountId the account to check * @param beginTime optional filter the games started after this time * @param endTime optional filter for games started before this time * @param beginIndex optional filter for skipping the first x games * @param endIndex optional filter for skipping only showing x games * @param rankedQueue optional filter for selecting the queue * @param season optional filter for selecting the season * @param championId optional filter for selecting the champion played * @return MatchList */ public List<MatchReference> getMatchList(Platform server, long accountId, @Nullable Long beginTime, @Nullable Long endTime, @Nullable Integer beginIndex, @Nullable Integer endIndex, @Nullable Set<GameQueueType> rankedQueue, @Nullable Set<SeasonType> season, @Nullable Set<Integer> championId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.ACCOUNT_ID_PLACEHOLDER, String.valueOf(accountId)) .withEndpoint(URLEndpoint.V3_MATCHLIST) .withPlatform(server); if (beginIndex != null) { builder.withURLData(Constants.BEGININDEX_PLACEHOLDER_DATA, beginIndex.toString()); } if (endIndex != null) { if ((beginIndex != null ? beginIndex : 0) + 50 - endIndex < 0) { throw new IllegalArgumentException("begin-endindex out of range! (difference between beginIndex and endIndex is more than 50)"); } builder.withURLData(Constants.ENDINDEX_PLACEHOLDER_DATA, endIndex.toString()); } if (beginTime != null) { builder.withURLData(Constants.BEGINTIME_PLACEHOLDER_DATA, beginTime.toString()); } if (endTime != null) { if ((beginTime != null ? beginTime : 0) + 604800000 - endTime < 0) { throw new IllegalArgumentException("begin-endtime out of range! (difference between beginTime and endTime is more than one week)"); } builder.withURLData(Constants.ENDTIME_PLACEHOLDER_DATA, endTime.toString()); } if (rankedQueue != null) { rankedQueue.forEach(queue -> builder.withURLDataAsSet(Constants.QUEUE_PLACEHOLDER_DATA, String.valueOf(queue.getValue()))); } if (season != null) { season.forEach(sea -> builder.withURLDataAsSet(Constants.SEASON_PLACEHOLDER_DATA, String.valueOf(sea.getValue()))); } if (championId != null) { championId.forEach(id -> builder.withURLDataAsSet(Constants.CHAMPION_PLACEHOLDER_DATA, String.valueOf(id))); } Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_MATCHLIST, server, accountId, beginTime, endTime, beginIndex, endIndex, rankedQueue, season, championId); if (chl.isPresent()) { return (List<MatchReference>) chl.get(); } MatchList list = (MatchList) builder.build(); if (list == null) { return Collections.emptyList(); } DataCall.getCacheProvider().store(URLEndpoint.V3_MATCHLIST, list.getMatches()); return list.getMatches(); } /** * Returns the match data from a match id * * @param server the platform the match was played on * @param matchId the id to check * @return Match */ public Match getMatch(Platform server, long matchId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.MATCH_ID_PLACEHOLDER, String.valueOf(matchId)) .withEndpoint(URLEndpoint.V3_MATCH) .withPlatform(server); Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_MATCH, matchId, server); if (chl.isPresent()) { return (Match) chl.get(); } Match match = (Match) builder.build(); DataCall.getCacheProvider().store(URLEndpoint.V3_MATCH, match, matchId, server); return match; } /** * Returns the timeline relating to a match. * Not avaliable for matches older than a year * * @param server the platform to find the match on * @param matchId the matchId to find timeline for * @return MatchTimeline if avaliable */ public MatchTimeline getTimeline(Platform server, long matchId) { DataCallBuilder builder = new DataCallBuilder().withURLParameter(Constants.MATCH_ID_PLACEHOLDER, String.valueOf(matchId)) .withEndpoint(URLEndpoint.V3_TIMELINE) .withPlatform(server); Optional chl = DataCall.getCacheProvider().get(URLEndpoint.V3_TIMELINE, matchId, server); if (chl.isPresent()) { return (MatchTimeline) chl.get(); } MatchTimeline timeline = (MatchTimeline) builder.build(); DataCall.getCacheProvider().store(URLEndpoint.V3_TIMELINE, timeline, matchId, server); return timeline; } }
package org.agmip.ui.quadui; import com.rits.cloning.Cloner; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.agmip.dome.DomeUtil; import org.agmip.dome.Engine; import org.agmip.translators.csv.AlnkInput; import org.agmip.translators.csv.DomeInput; import org.agmip.util.MapUtil; import org.apache.pivot.util.concurrent.Task; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ApplyDomeTask extends Task<HashMap> { private static Logger log = LoggerFactory.getLogger(ApplyDomeTask.class); private final HashMap<String, HashMap<String, Object>> ovlDomes = new HashMap<String, HashMap<String, Object>>(); private final HashMap<String, HashMap<String, Object>> stgDomes = new HashMap<String, HashMap<String, Object>>(); private HashMap<String, Object> linkDomes = new HashMap<String, Object>(); private HashMap<String, String> ovlLinks = new HashMap<String, String>(); private HashMap<String, String> stgLinks = new HashMap<String, String>(); private final HashMap<String, String> ovlNewDomeIdMap = new HashMap<String, String>(); private final HashMap<String, String> stgNewDomeIdMap = new HashMap<String, String>(); // private HashMap<String, ArrayList<String>> wthLinks = new HashMap<String, ArrayList<String>>(); // private HashMap<String, ArrayList<String>> soilLinks = new HashMap<String, ArrayList<String>>(); private HashMap source; private String mode; private boolean autoApply; private int thrPoolSize; public ApplyDomeTask(String linkFile, String fieldFile, String strategyFile, String mode, HashMap m, boolean autoApply) { this.source = m; this.mode = mode; this.autoApply = autoApply; // Setup the domes here. loadDomeLinkFile(linkFile); log.debug("link csv: {}", ovlLinks); if (mode.equals("strategy")) { loadDomeFile(strategyFile, stgDomes); } loadDomeFile(fieldFile, ovlDomes); thrPoolSize = Runtime.getRuntime().availableProcessors(); } public ApplyDomeTask(String linkFile, String fieldFile, String strategyFile, String mode, HashMap m, boolean autoApply, int thrPoolSize) { this(linkFile, fieldFile, strategyFile, mode, m, autoApply); this.thrPoolSize = thrPoolSize; } private void loadDomeLinkFile(String fileName) { String fileNameTest = fileName.toUpperCase(); log.debug("Loading LINK file: {}", fileName); linkDomes = null; try { if (fileNameTest.endsWith(".CSV")) { log.debug("Entering single ACMO CSV file DOME handling"); AlnkInput reader = new AlnkInput(); linkDomes = (HashMap<String, Object>) reader.readFile(fileName); } else if (fileNameTest.endsWith(".ALNK")) { log.debug("Entering single ALNK file DOME handling"); AlnkInput reader = new AlnkInput(); linkDomes = (HashMap<String, Object>) reader.readFile(fileName); } if (linkDomes != null) { log.debug("link info: {}", linkDomes.toString()); try { if (!linkDomes.isEmpty()) { if (linkDomes.containsKey("link_overlay")) { ovlLinks = (HashMap<String, String>) linkDomes.get("link_overlay"); } if (linkDomes.containsKey("link_stragty")) { stgLinks = (HashMap<String, String>) linkDomes.get("link_stragty"); } } } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } private String getLinkIds(String domeType, HashMap entry) { String exname = MapUtil.getValueOr(entry, "exname", ""); String wst_id = MapUtil.getValueOr(entry, "wst_id", ""); String soil_id = MapUtil.getValueOr(entry, "soil_id", ""); String linkIdsExp = getLinkIds(domeType, "EXNAME", exname); String linkIdsWst = getLinkIds(domeType, "WST_ID", wst_id); String linkIdsSoil = getLinkIds(domeType, "SOIL_ID", soil_id); String ret = ""; if (!linkIdsExp.equals("")) { ret += linkIdsExp + "|"; } if (!linkIdsWst.equals("")) { ret += linkIdsWst + "|"; } if (!linkIdsSoil.equals("")) { ret += linkIdsSoil; } if (ret.endsWith("|")) { ret = ret.substring(0, ret.length() - 1); } return ret; } private String getLinkIds(String domeType, String idType, String id) { HashMap<String, String> links; if (domeType.equals("strategy")) { links = stgLinks; } else if (domeType.equals("overlay")) { links = ovlLinks; } else { return ""; } if (links.isEmpty() || id.equals("")) { return ""; } String linkIds = ""; ArrayList<String> altLinkIds = new ArrayList(); altLinkIds.add(idType + "_ALL"); if (id.matches("[^_]+_\\d+$")) { altLinkIds.add(idType + "_" + id.replaceAll("_\\d+$", "")); altLinkIds.add(idType + "_" + id + "__1"); } else if (id.matches(".+_\\d+__\\d+$")) { altLinkIds.add(idType + "_" + id.replaceAll("__\\d+$", "")); altLinkIds.add(idType + "_" + id.replaceAll("_\\d+__\\d+$", "")); } altLinkIds.add(idType + "_" + id); for (String linkId : altLinkIds) { if (links.containsKey(linkId)) { linkIds += links.get(linkId) + "|"; } } if (linkIds.endsWith("|")) { linkIds = linkIds.substring(0, linkIds.length() - 1); } return linkIds; } private void reviseDomeIds(HashMap entry, String domeIds, String domeType) { HashMap<String, HashMap<String, Object>> domes; HashMap<String, String> domeClimIdMap; String domeName; if (domeType.equals("strategy")) { domes = stgDomes; domeClimIdMap = ovlNewDomeIdMap; domeName = "seasonal_strategy"; } else if (domeType.equals("overlay")) { domes = ovlDomes; domeClimIdMap = stgNewDomeIdMap; domeName = "field_overlay"; } else { return; } StringBuilder newDomeIds = new StringBuilder(); for (String domeId : domeIds.split("[|]")) { String[] metas = domeId.split("-"); if (metas.length < 7) { if (domeClimIdMap.containsKey(domeId)) { domeId = domeClimIdMap.get(domeId); } else { String climId = ""; HashMap<String, Object> dome = MapUtil.getObjectOr(domes, domeId, new HashMap()); // Only auto-fix the clim_id for seasonal strategy DOME if (!domeType.equals("overlay")) { climId = MapUtil.getValueOr(entry, "clim_id", "").toUpperCase(); if (!dome.isEmpty()) { ArrayList<HashMap<String, String>> rules = DomeUtil.getRules(dome); for (HashMap<String, String> rule : rules) { String var = MapUtil.getValueOr(rule, "variable", "").toLowerCase(); if (var.equals("clim_id")) { climId = MapUtil.getValueOr(rule, "args", climId).toUpperCase(); } } } } StringBuilder newDomeId = new StringBuilder(); for (int i = 0; i < metas.length - 1; i++) { newDomeId.append(metas[i]).append("-"); } newDomeId.append(climId).append("-").append(metas[metas.length - 1]); domeClimIdMap.put(domeId, newDomeId.toString()); domeId = newDomeId.toString(); DomeUtil.updateMetaInfo(dome, domeId); } } newDomeIds.append(domeId).append("|"); } if (newDomeIds.charAt(newDomeIds.length() - 1) == '|') { newDomeIds.deleteCharAt(newDomeIds.length() - 1); } entry.put(domeName, newDomeIds.toString()); } private void loadDomeFile(String fileName, HashMap<String, HashMap<String, Object>> domes) { String fileNameTest = fileName.toUpperCase(); log.info("Loading DOME file: {}", fileName); if (fileNameTest.endsWith(".ZIP")) { log.debug("Entering Zip file handling"); ZipFile z; try { z = new ZipFile(fileName); Enumeration entries = z.entries(); while (entries.hasMoreElements()) { // Do we handle nested zips? Not yet. ZipEntry entry = (ZipEntry) entries.nextElement(); File zipFileName = new File(entry.getName()); if (zipFileName.getName().toLowerCase().endsWith(".csv") && !zipFileName.getName().startsWith(".")) { log.debug("Processing file: {}", zipFileName.getName()); DomeInput translator = new DomeInput(); translator.readCSV(z.getInputStream(entry)); HashMap<String, Object> dome = translator.getDome(); log.debug("dome info: {}", dome.toString()); String domeName = DomeUtil.generateDomeName(dome); if (!domeName.equals(" domes.put(domeName, new HashMap<String, Object>(dome)); } } } z.close(); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } else if (fileNameTest.endsWith(".CSV")) { log.debug("Entering single CSV file DOME handling"); try { DomeInput translator = new DomeInput(); HashMap<String, Object> dome = (HashMap<String, Object>) translator.readFile(fileName); String domeName = DomeUtil.generateDomeName(dome); log.debug("Dome name: {}", domeName); log.debug("Dome layout: {}", dome.toString()); domes.put(domeName, dome); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } else if (fileNameTest.endsWith(".JSON") || fileNameTest.endsWith(".DOME")) { log.debug("Entering single ACE Binary file DOME handling"); try { ObjectMapper mapper = new ObjectMapper(); String json; if (fileNameTest.endsWith(".JSON")) { json = new Scanner(new FileInputStream(fileName), "UTF-8").useDelimiter("\\A").next(); } else { json = new Scanner(new GZIPInputStream(new FileInputStream(fileName)), "UTF-8").useDelimiter("\\A").next(); } HashMap<String, HashMap<String, Object>> tmp = mapper.readValue(json, new TypeReference<HashMap<String, HashMap<String, Object>>>() { }); // domes.putAll(tmp); for (HashMap dome : tmp.values()) { String domeName = DomeUtil.generateDomeName(dome); if (!domeName.equals(" domes.put(domeName, new HashMap<String, Object>(dome)); } } log.debug("Domes layout: {}", domes.toString()); } catch (Exception ex) { log.error("Error processing DOME file: {}", ex.getMessage()); HashMap<String, Object> d = new HashMap<String, Object>(); d.put("errors", ex.getMessage()); } } } @Override public HashMap<String, Object> execute() { // First extract all the domes and put them in a HashMap by DOME_NAME // The read the DOME_NAME field of the CSV file // Split the DOME_NAME, and then apply sequentially to the HashMap. // PLEASE NOTE: This can be a massive undertaking if the source map // is really large. Need to find optimization points. HashMap<String, Object> output = new HashMap<String, Object>(); //HashMap<String, ArrayList<HashMap<String, String>>> dome; // Load the dome if (ovlDomes.isEmpty() && stgDomes.isEmpty()) { log.info("No DOME to apply."); HashMap<String, Object> d = new HashMap<String, Object>(); //d.put("domeinfo", new HashMap<String, String>()); d.put("domeoutput", source); return d; } if (autoApply) { HashMap<String, Object> d = new HashMap<String, Object>(); if (ovlDomes.size() > 1) { log.error("Auto-Apply feature only allows one field overlay file per run"); d.put("errors", "Auto-Apply feature only allows one field overlay file per run"); return d; } else if (stgDomes.size() > 1) { log.error("Auto-Apply feature only allows one seasonal strategy file per run"); d.put("errors", "Auto-Apply feature only allows one seasonal strategy file per run"); return d; } } // Flatten the data and apply the dome. Engine domeEngine; ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source); boolean noExpMode = false; if (flattenedData.isEmpty()) { log.info("No experiment data detected, will try Weather and Soil data only mode"); noExpMode = true; flattenedData.addAll(MapUtil.getRawPackageContents(source, "soils")); flattenedData.addAll(MapUtil.getRawPackageContents(source, "weathers")); // flatSoilAndWthData(flattenedData, "soil"); // flatSoilAndWthData(flattenedData, "weather"); if (flattenedData.isEmpty()) { HashMap<String, Object> d = new HashMap<String, Object>(); log.error("No data found from input file, no DOME will be applied for data set {}", source.toString()); d.put("errors", "Loaded raw data is invalid, please check input files"); return d; } } if (mode.equals("strategy")) { log.debug("Domes: {}", stgDomes.toString()); log.debug("Entering Strategy mode!"); if (!noExpMode) { updateWthReferences(updateExpReferences(true)); flattenedData = MapUtil.flatPack(source); } // int cnt = 0; // for (HashMap<String, Object> entry : MapUtil.getRawPackageContents(source, "experiments")) { // log.debug("Exp at {}: {}, {}", // cnt, // entry.get("wst_id"), // entry.get("clim_id"), // ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("wst_id"), // ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("clim_id") // cnt++; String stgDomeName = ""; if (autoApply) { for (String domeName : stgDomes.keySet()) { stgDomeName = domeName; } log.info("Auto apply seasonal strategy: {}", stgDomeName); } Engine generatorEngine; ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>(); for (HashMap<String, Object> entry : flattenedData) { // Remove observed data from input data if apply strategy DOME entry.remove("observed"); if (autoApply) { entry.put("seasonal_strategy", stgDomeName); } String domeName = getLinkIds("strategy", entry); if (domeName.equals("")) { domeName = MapUtil.getValueOr(entry, "seasonal_strategy", ""); } else { entry.put("seasonal_strategy", domeName); log.debug("Apply seasonal strategy domes from link csv: {}", domeName); } entry.remove("seasonal_strategy"); reviseDomeIds(entry, domeName, "strategy"); String tmp[] = domeName.split("[|]"); String strategyName; if (tmp.length > 1) { log.warn("Multiple seasonal strategy dome is not supported yet, only the first dome will be applied"); for (int i = 1; i < tmp.length; i++) { setFailedDomeId(entry, "seasonal_dome_failed", tmp[i]); } } strategyName = tmp[0].toUpperCase(); log.info("Apply DOME {} for {}", strategyName, MapUtil.getValueOr(entry, "exname", MapUtil.getValueOr(entry, "soil_id", MapUtil.getValueOr(entry, "wst_id", "<Unknow>")))); log.debug("Looking for ss: {}", strategyName); if (!strategyName.equals("")) { if (stgDomes.containsKey(strategyName)) { log.debug("Found strategyName"); entry.put("dome_applied", "Y"); entry.put("seasonal_dome_applied", "Y"); generatorEngine = new Engine(stgDomes.get(strategyName), true); if (!noExpMode) { // Check if there is no weather or soil data matched with experiment if (((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).isEmpty()) { log.warn("No scenario weather data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } if (((HashMap) MapUtil.getObjectOr(entry, "soil", new HashMap())).isEmpty()) { log.warn("No soil data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } } ArrayList<HashMap<String, Object>> newEntries = generatorEngine.applyStg(flatSoilAndWthData(entry, noExpMode)); log.debug("New Entries to add: {}", newEntries.size()); strategyResults.addAll(newEntries); } else { log.error("Cannot find strategy: {}", strategyName); setFailedDomeId(entry, "seasonal_dome_failed", strategyName); } } } log.debug("=== FINISHED GENERATION ==="); log.debug("Generated count: {}", strategyResults.size()); ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments"); exp.clear(); exp.addAll(strategyResults); flattenedData = MapUtil.flatPack(source); if (noExpMode) { flattenedData.addAll(MapUtil.getRawPackageContents(source, "soils")); flattenedData.addAll(MapUtil.getRawPackageContents(source, "weathers")); } } if (!noExpMode) { if (mode.equals("strategy")) { updateExpReferences(false); } else { updateWthReferences(updateExpReferences(false)); } flattenedData = MapUtil.flatPack(source); } String ovlDomeName = ""; if (autoApply) { for (String domeName : ovlDomes.keySet()) { ovlDomeName = domeName; } log.info("Auto apply field overlay: {}", ovlDomeName); } int cnt = 0; ArrayList<ApplyDomeRunner> engineRunners = new ArrayList(); ExecutorService executor; if (thrPoolSize > 1) { log.info("Create the thread pool with the size of {} for appling filed overlay DOME", thrPoolSize); executor = Executors.newFixedThreadPool(thrPoolSize); } else if (thrPoolSize == 1) { log.info("Create the single thread pool for appling filed overlay DOME"); executor = Executors.newSingleThreadExecutor(); } else { log.info("Create the cached thread pool with flexible size for appling filed overlay DOME"); executor = Executors.newCachedThreadPool(); } HashMap<String, HashMap<String, ArrayList<HashMap<String, String>>>> soilDomeMap = new HashMap(); HashMap<String, HashMap<String, ArrayList<HashMap<String, String>>>> wthDomeMap = new HashMap(); HashSet<String> soilIds = getSWIdsSet("soils", new String[]{"soil_id"}); HashSet<String> wthIds = getSWIdsSet("weathers", new String[]{"wst_id", "clim_id"}); ArrayList<HashMap> soilDataArr = new ArrayList(); ArrayList<HashMap> wthDataArr = new ArrayList(); ArrayList<ArrayList<Engine>> soilEngines = new ArrayList(); ArrayList<ArrayList<Engine>> wthEngines = new ArrayList(); for (HashMap<String, Object> entry : flattenedData) { log.debug("Exp at {}: {}, {}, {}", cnt, entry.get("wst_id"), ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("wst_id"), ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("clim_id")); cnt++; if (autoApply) { entry.put("field_overlay", ovlDomeName); } String domeName = getLinkIds("overlay", entry); if (domeName.equals("")) { domeName = MapUtil.getValueOr(entry, "field_overlay", ""); } else { entry.put("field_overlay", domeName); log.debug("Apply field overlay domes from link csv: {}", domeName); } reviseDomeIds(entry, domeName, "overlay"); String soilId = MapUtil.getValueOr(entry, "soil_id", ""); String wstId = MapUtil.getValueOr(entry, "wst_id", ""); String climId = MapUtil.getValueOr(entry, "clim_id", ""); ArrayList<Engine> sEngines = new ArrayList(); ArrayList<Engine> wEngines = new ArrayList(); String sDomeIds = ""; String wDomeIds = ""; ArrayList<HashMap<String, String>> sRulesTotal = new ArrayList(); ArrayList<HashMap<String, String>> wRulesTotal = new ArrayList(); if (!domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = tmp.length; ArrayList<Engine> engines = new ArrayList(); for (int i = 0; i < tmpLength; i++) { String tmpDomeId = tmp[i].toUpperCase(); log.debug("Apply DOME {} for {}", tmpDomeId, MapUtil.getValueOr(entry, "exname", MapUtil.getValueOr(entry, "soil_id", MapUtil.getValueOr(entry, "wst_id", "<Unknow>")))); log.debug("Looking for dome_name: {}", tmpDomeId); if (ovlDomes.containsKey(tmpDomeId)) { domeEngine = new Engine(ovlDomes.get(tmpDomeId)); entry.put("dome_applied", "Y"); entry.put("field_dome_applied", "Y"); ArrayList<HashMap<String, String>> sRules = domeEngine.extractSoilRules(); if (!sRules.isEmpty()) { if (sDomeIds.equals("")) { sDomeIds = tmpDomeId; } else { sDomeIds += "|" + tmpDomeId; } sEngines.add(new Engine(sRules, tmpDomeId)); sRulesTotal.addAll(sRules); } ArrayList<HashMap<String, String>> wRules = domeEngine.extractWthRules(); if (!wRules.isEmpty()) { if (wDomeIds.equals("")) { wDomeIds = tmpDomeId; } else { wDomeIds += "|" + tmpDomeId; } wEngines.add(new Engine(wRules, tmpDomeId)); wRulesTotal.addAll(wRules); } engines.add(domeEngine); } else { log.error("Cannot find overlay: {}", tmpDomeId); setFailedDomeId(entry, "field_dome_failed", tmpDomeId); } } HashMap<String, ArrayList<HashMap<String, String>>> lastAppliedSoilDomes = soilDomeMap.get(soilId); if (lastAppliedSoilDomes == null) { soilDataArr.add(entry); soilEngines.add(sEngines); lastAppliedSoilDomes = new HashMap(); lastAppliedSoilDomes.put(sDomeIds, sRulesTotal); soilDomeMap.put(soilId, lastAppliedSoilDomes); } else if (!lastAppliedSoilDomes.containsKey(sDomeIds)) { boolean isSameRules = false; for (ArrayList<HashMap<String, String>> rules : lastAppliedSoilDomes.values()) { if (rules.equals(sRulesTotal)) { isSameRules = true; break; } } if (!isSameRules) { replicateSoil(entry, soilIds); soilDataArr.add(entry); soilEngines.add(sEngines); lastAppliedSoilDomes.put(sDomeIds, sRulesTotal); } } HashMap<String, ArrayList<HashMap<String, String>>> lastAppliedWthDomes = wthDomeMap.get(wstId+climId); if (lastAppliedWthDomes == null) { wthDataArr.add(entry); wthEngines.add(wEngines); lastAppliedWthDomes = new HashMap(); lastAppliedWthDomes.put(wDomeIds, wRulesTotal); wthDomeMap.put(wstId+climId, lastAppliedWthDomes); } else if (!lastAppliedWthDomes.containsKey(wDomeIds)) { boolean isSameRules = false; for (ArrayList<HashMap<String, String>> rules : lastAppliedWthDomes.values()) { if (rules.equals(wRulesTotal)) { isSameRules = true; break; } } if (!isSameRules) { replicateWth(entry, wthIds); wthDataArr.add(entry); wthEngines.add(wEngines); lastAppliedWthDomes.put(wDomeIds, wRulesTotal); } } engineRunners.add(new ApplyDomeRunner(engines, entry, noExpMode, mode)); } } for (int i = 0; i < soilDataArr.size(); i++) { for (Engine e : soilEngines.get(i)) { e.apply(flatSoilAndWthData(soilDataArr.get(i), noExpMode)); } } for (int i = 0; i < wthDataArr.size(); i++) { for (Engine e : wthEngines.get(i)) { e.apply(flatSoilAndWthData(wthDataArr.get(i), noExpMode)); } } for (ApplyDomeRunner engineRunner : engineRunners) { executor.submit(engineRunner); // engine.apply(flatSoilAndWthData(entry, noExpMode)); // ArrayList<String> strategyList = engine.getGenerators(); // if (!strategyList.isEmpty()) { // log.warn("The following DOME commands in the field overlay file are ignored : {}", strategyList.toString()); // if (!noExpMode && !mode.equals("strategy")) { // // Check if there is no weather or soil data matched with experiment // if (((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).isEmpty()) { // log.warn("No baseline weather data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); // if (((HashMap) MapUtil.getObjectOr(entry, "soil", new HashMap())).isEmpty()) { // log.warn("No soil data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A")); } executor.shutdown(); while (!executor.isTerminated()) { } // executor = null; if (noExpMode) { output.put("domeoutput", source); } else { output.put("domeoutput", MapUtil.bundle(flattenedData)); } if (ovlDomes != null && !ovlDomes.isEmpty()) { output.put("ovlDomes", ovlDomes); } if (stgDomes != null && !stgDomes.isEmpty()) { output.put("stgDomes", stgDomes); } return output; } // private void flatSoilAndWthData(ArrayList<HashMap<String, Object>> flattenedData, String key) { // ArrayList<HashMap<String, Object>> arr = MapUtil.getRawPackageContents(source, key + "s"); // for (HashMap<String, Object> data : arr) { // HashMap<String, Object> tmp = new HashMap<String, Object>(); // tmp.put(key, data); // flattenedData.add(tmp); private HashMap<String, Object> flatSoilAndWthData(HashMap<String, Object> data, boolean noExpFlg) { if (!noExpFlg) { return data; } HashMap<String, Object> ret; if (data.containsKey("dailyWeather")) { ret = new HashMap<String, Object>(); ret.put("weather", data); } else if (data.containsKey("soilLayer")) { ret = new HashMap<String, Object>(); ret.put("soil", data); } else { ret = data; } return ret; } private void setFailedDomeId(HashMap data, String failKey, String failId) { String failIds; if ((failIds = (String) data.get(failKey)) != null) { data.put(failKey, failId); } else { data.put(failKey, failIds + "|" + failId); } } private boolean updateExpReferences(boolean isStgDome) { ArrayList<HashMap<String, Object>> expArr = MapUtil.getRawPackageContents(source, "experiments"); boolean isClimIDchanged = false; HashMap<String, HashMap<String, Object>> domes; String linkid; String domeKey; int maxDomeNum; if (isStgDome) { domes = stgDomes; linkid = "strategy"; domeKey = "seasonal_strategy"; maxDomeNum = 1; } else { domes = ovlDomes; linkid = "field"; domeKey = "field_overlay"; maxDomeNum = Integer.MAX_VALUE; } // Pre-scan the seasnal DOME to update reference variables String autoDomeName = ""; if (autoApply) { for (String domeName : domes.keySet()) { autoDomeName = domeName; } } for (HashMap<String, Object> exp : expArr) { String domeName = getLinkIds(linkid, exp); if (domeName.equals("")) { if (autoApply) { domeName = autoDomeName; } else { domeName = MapUtil.getValueOr(exp, domeKey, ""); } } if (!domeName.equals("")) { String tmp[] = domeName.split("[|]"); int tmpLength = Math.min(tmp.length, maxDomeNum); for (int i = 0; i < tmpLength; i++) { String tmpDomeId = tmp[i].toUpperCase(); log.debug("Looking for dome_name: {}", tmpDomeId); if (domes.containsKey(tmpDomeId)) { log.debug("Found DOME {}", tmpDomeId); Engine domeEngine = new Engine(domes.get(tmpDomeId)); isClimIDchanged = domeEngine.updateWSRef(exp, isStgDome, mode.equals("strategy")); // Check if the wst_id is switch to 8-bit long version String wst_id = MapUtil.getValueOr(exp, "wst_id", ""); if (isStgDome && wst_id.length() < 8) { exp.put("wst_id", wst_id + "0XXX"); exp.put("clim_id", "0XXX"); isClimIDchanged = true; } log.debug("New exp linkage: {}", exp); } } } } return isClimIDchanged; } private void updateWthReferences(boolean isClimIDchanged) { ArrayList<HashMap<String, Object>> wthArr = MapUtil.getRawPackageContents(source, "weathers"); boolean isStrategy = mode.equals("strategy"); HashMap<String, HashMap> unfixedWths = new HashMap(); HashSet<String> fixedWths = new HashSet(); for (HashMap<String, Object> wth : wthArr) { String wst_id = MapUtil.getValueOr(wth, "wst_id", ""); String clim_id = MapUtil.getValueOr(wth, "clim_id", ""); if (clim_id.equals("")) { if (wst_id.length() == 8) { clim_id = wst_id.substring(4, 8); } else { clim_id = "0XXX"; } } // If user assign CLIM_ID in the DOME, or find non-baseline data in the overlay mode, then switch WST_ID to 8-bit version if (isStrategy || isClimIDchanged || !clim_id.startsWith("0")) { if (wst_id.length() < 8) { wth.put("wst_id", wst_id + clim_id); } } else { // Temporally switch all the WST_ID to 8-bit in the data set if (wst_id.length() < 8) { wth.put("wst_id", wst_id + clim_id); } else { wst_id = wst_id.substring(0, 4); } // Check if there is multiple baseline record for one site if (unfixedWths.containsKey(wst_id)) { log.warn("There is multiple baseline weather data for site [{}], please choose a particular baseline via field overlay DOME", wst_id); unfixedWths.remove(wst_id); fixedWths.add(wst_id); } else { if (!fixedWths.contains(wst_id)) { unfixedWths.put(wst_id, wth); } } } } // If no CLIM_ID provided in the overlay mode, then switch the baseline WST_ID to 4-bit. if (!isStrategy && !unfixedWths.isEmpty()) { for (String wst_id : unfixedWths.keySet()) { unfixedWths.get(wst_id).put("wst_id", wst_id); } } } private void replicateSoil(HashMap entry, HashSet soilIds) { String newSoilId = MapUtil.getValueOr(entry, "soil_id", ""); HashMap data = MapUtil.getObjectOr(entry, "soil", new HashMap()); if (data.isEmpty()) { return; } Cloner cloner = new Cloner(); HashMap newData = cloner.deepClone(data); ArrayList<HashMap<String, Object>> soils = MapUtil.getRawPackageContents(source, "soils"); int count = 1; while (soilIds.contains(newSoilId + "_" + count)) { count++; } newSoilId += "_" + count; newData.put("soil_id", newSoilId); entry.put("soil_id", newSoilId); entry.put("soil", newData); soilIds.add(newSoilId); soils.add(newData); } private void replicateWth(HashMap entry, HashSet wthIds) { String newWthId = MapUtil.getValueOr(entry, "wst_id", ""); String climId = MapUtil.getValueOr(entry, "clim_id", ""); HashMap data = MapUtil.getObjectOr(entry, "weather", new HashMap()); if (data.isEmpty()) { return; } Cloner cloner = new Cloner(); HashMap newData = cloner.deepClone(data); ArrayList<HashMap<String, Object>> wths = MapUtil.getRawPackageContents(source, "weathers"); String inst; if (newWthId.length() > 1) { inst = newWthId.substring(0, 2); } else { inst = newWthId + "0"; } newWthId = inst + "01" + climId; int count = 1; while (wthIds.contains(newWthId) && count < 99) { count++; newWthId = String.format("%s%02d%s", inst, count, climId); } if (count == 99 && wthIds.contains(newWthId)) { inst = inst.substring(0, 1); newWthId = inst + "100" + climId; while (wthIds.contains(newWthId)) { count++; newWthId = String.format("%s%03d%s", inst, count, climId); } } newData.put("wst_id", newWthId); entry.put("wst_id", newWthId); entry.put("weather", newData); wthIds.add(newWthId); wths.add(newData); } private HashSet<String> getSWIdsSet(String dataKey, String... idKeys) { HashSet<String> ret = new HashSet(); ArrayList<HashMap<String, Object>> arr = MapUtil.getRawPackageContents(source, dataKey); for (HashMap data : arr) { StringBuilder sb = new StringBuilder(); for (String idKey : idKeys) { sb.append(MapUtil.getValueOr(data, idKey, "")); } ret.add(sb.toString()); } return ret; } }
package org.animotron.statement.query; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import org.animotron.Executor; import org.animotron.graph.AnimoGraph; import org.animotron.graph.GraphOperation; import org.animotron.graph.index.Order; import org.animotron.io.PipedInput; import org.animotron.manipulator.Evaluator; import org.animotron.manipulator.OnQuestion; import org.animotron.manipulator.PFlow; import org.animotron.manipulator.QCAVector; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.operator.*; import org.animotron.statement.relation.SHALL; import org.jetlang.channels.Subscribable; import org.jetlang.core.DisposingExecutor; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import static org.animotron.Properties.RID; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.animotron.graph.RelationshipTypes.RESULT; /** * Query operator 'Get'. Return 'have' relations on provided context. * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> */ public class GET extends AbstractQuery implements Evaluable, Shift { public static final GET _ = new GET(); private static boolean debug = true; private GET() { super("get"); } TraversalDescription td = Traversal.description(). depthFirst().uniqueness(Uniqueness.RELATIONSHIP_PATH); private static TraversalDescription td_eval_ic = Traversal.description(). breadthFirst(). relationships(AN._, OUTGOING). relationships(SHALL._, OUTGOING); public OnQuestion onCalcQuestion() { return question; } private OnQuestion question = new OnQuestion() { @Override public void onMessage(final PFlow pf) { final Relationship op = pf.getOP(); final Node node = op.getEndNode(); final Set<Relationship> visitedREFs = new FastSet<Relationship>(); final Set<Node> thes = new FastSet<Node>(); for (QCAVector theNode : AN.getREFs(pf, op)) { thes.add(theNode.getAnswer().getEndNode()); } evalGet(pf, op, node, thes, visitedREFs); pf.await(); pf.done(); } private void evalGet( final PFlow pf, final Relationship op, final Node node, final Set<Node> thes, final Set<Relationship> visitedREFs) { Utils.debug(GET._, op, thes); //check, maybe, result was already calculated if (!Utils.results(pf)) { //no pre-calculated result, calculate it Subscribable<QCAVector> onContext = new Subscribable<QCAVector>() { @Override public void onMessage(QCAVector vector) { if (debug) System.out.println("GET ["+op+"] vector "+vector); if (vector == null) { pf.countDown(); return; } final Set<QCAVector> rSet = get(pf, op, vector, thes, visitedREFs); if (rSet != null) { for (QCAVector v : rSet) { pf.sendAnswer(v, RESULT);//, AN._); //XXX: change to AN } } } @Override public DisposingExecutor getQueue() { return Executor.getFiber(); } }; pf.answer.subscribe(onContext); if (Utils.haveContext(pf)) { super.onMessage(pf); } else { boolean first = true; Set<QCAVector> rSet = null; for (QCAVector vector : pf.getPFlowPath()) { System.out.println("CHECK PFLOW "+vector); if (first) { first = false; if (vector.getContext() == null) continue; Set<QCAVector> refs = new FastSet<QCAVector>(); for (QCAVector v : vector.getContext()) { refs.add(v); } rSet = get(pf, op, refs, thes, visitedREFs); } else { rSet = get(pf, op, vector, thes, visitedREFs); } if (rSet != null) { for (QCAVector v : rSet) { pf.sendAnswer(v, RESULT);//, AN._); //XXX: change to AN } break; } } } } }; }; public Set<QCAVector> get(PFlow pf, Relationship op, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) { Set<QCAVector> refs = new FastSet<QCAVector>(); refs.add(vector); return get(pf, op, refs, thes, visitedREFs); } public Set<QCAVector> get(final PFlow pf, Relationship op, Node ref, final Set<Node> thes, final Set<Relationship> visitedREFs) { Set<QCAVector> set = new FastSet<QCAVector>(); Relationship[] have = searchForHAVE(pf, null, ref, thes); if (have != null) { for (int i = 0; i < have.length; i++) { if (!pf.isInStack(have[i])) set.add(new QCAVector(pf.getOP(), have[i])); } } if (!set.isEmpty()) return set; Set<QCAVector> newREFs = new FastSet<QCAVector>(); getOutgoingReferences(pf, null, ref, newREFs, null); return get(pf, op, newREFs, thes, visitedREFs); } private boolean check(Set<QCAVector> set, final PFlow pf, final Relationship op, final QCAVector v, final Relationship toCheck, final Set<Node> thes, Set<Relationship> visitedREFs) { if (toCheck == null) return false; visitedREFs.add(toCheck); Relationship[] have = searchForHAVE(pf, toCheck, v, thes); if (have != null) { boolean added = false; for (int i = 0; i < have.length; i++) { if (!pf.isInStack(have[i])) { set.add(new QCAVector(op, v, have[i])); added = true; } } return added; } return false; } public Set<QCAVector> get( final PFlow pf, final Relationship op, final Set<QCAVector> REFs, final Set<Node> thes, Set<Relationship> visitedREFs) { //System.out.println("GET context = "+ref); if (visitedREFs == null) visitedREFs = new FastSet<Relationship>(); Set<QCAVector> set = new FastSet<QCAVector>(); Set<QCAVector> nextREFs = new FastSet<QCAVector>(); nextREFs.addAll(REFs); //boolean first = true; Relationship t = null; while (true) { if (debug) System.out.println("nextREFs ");//+Arrays.toString(nextREFs.toArray())); for (QCAVector v : nextREFs) { if (debug) System.out.println("checking "+v); if (!check(set, pf, op, v, v.getUnrelaxedAnswer(), thes, visitedREFs)) { check(set, pf, op, v, v.getQuestion(), thes, visitedREFs); } } if (set.size() > 0) return set; Set<QCAVector> newREFs = new FastSet<QCAVector>(); for (QCAVector vector : nextREFs) { QCAVector[] cs = vector.getContext(); if (cs != null) { for (QCAVector c : cs) { t = c.getUnrelaxedAnswer(); if (t != null && !visitedREFs.contains(t)) newREFs.add(c); else { t = c.getQuestion(); if (!visitedREFs.contains(t)) newREFs.add(c); } } } // Relationship n = vector.getClosest(); // //System.out.println(""+n); // //System.out.println("getStartNode OUTGOING"); // if (first || !REFs.contains(n)) { // IndexHits<Relationship> it = Order.queryDown(n.getStartNode()); // try { // for (Relationship r : it) { // if (r.equals(n)) continue; // //System.out.println(r); // Statement st = Statements.relationshipType(r); // if (st instanceof AN) { // for (QCAVector v : AN.getREFs(pf, r)) { // Relationship t = v.getAnswer(); // if (!visitedREFs.contains(t)) // newREFs.add(v); // } else if (st instanceof Reference) { // try { // if (!pf.isInStack(r)) { // PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf), r); // for (QCAVector rr : in) { // if (!visitedREFs.contains(rr.getAnswer())) // newREFs.add(rr); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } finally { // it.close(); // first = false; // //System.out.println("getEndNode OUTGOING"); t = vector.getUnrelaxedAnswer(); if (t != null) { if (! t.isType(AN._)) getOutgoingReferences(pf, t, t.getStartNode(), newREFs, visitedREFs); getOutgoingReferences(pf, t, t.getEndNode(), newREFs, visitedREFs); } } if (newREFs.size() == 0) return null; nextREFs = newREFs; } } private void getOutgoingReferences(PFlow pf, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) { IndexHits<Relationship> it = Order.queryDown(node); try { boolean first = rr == null || !rr.isType(REF._); for (Relationship r : it) { //System.out.println(r); if (first) { first = false; continue; } if (r.isType(REF._)) continue; Statement st = Statements.relationshipType(r); if (st instanceof AN) { //System.out.println(r); for (QCAVector v : AN.getREFs(pf, r)) { Relationship t = v.getAnswer(); //System.out.println(t); if (visitedREFs != null && !visitedREFs.contains(t)) newREFs.add(v); } } else if (st instanceof Reference) { if (!pf.isInStack(r)) { try { PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf, r), r); for (QCAVector v : in) { if (visitedREFs != null && !visitedREFs.contains(v.getAnswer())) newREFs.add(v); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } catch (Exception e) { pf.sendException(e); } finally { it.close(); } } private Relationship[] searchForHAVE( final PFlow pf, final Relationship ref, final QCAVector v, final Set<Node> thes) { if (ref.isType(REF._) && thes.contains(ref.getEndNode())) { return new Relationship[] {v.getQuestion()}; } boolean checkStart = true; if (ref.isType(AN._)) { checkStart = false; } Relationship[] have = null; //search for inside 'HAVE' //return searchForHAVE(pf, ref, ref.getEndNode(), thes); have = getByHave(pf, ref, ref.getEndNode(), thes); if (have != null) return have; //search for local 'HAVE' if (checkStart) { have = getByHave(pf, null, ref.getStartNode(), thes); if (have != null) return have; } return null; } private Relationship[] searchForHAVE(final PFlow pflow, Relationship op, final Node ref, final Set<Node> thes) { Relationship[] have = null; //search for inside 'HAVE' have = getByHave(pflow, op, ref, thes); if (have != null) return have; //search 'IC' by 'IS' topology for (Relationship tdR : Utils.td_eval_IS.traverse(ref).relationships()) { //System.out.println("GET IC -> IS "+tdR); Relationship r = getShall(tdR.getEndNode(), thes); if (r != null) { final Node sNode = ref; final Node eNode = r.getEndNode(); final long id = r.getId(); return new Relationship[] { AnimoGraph.execute(new GraphOperation<Relationship>() { @Override public Relationship execute() { Relationship res = sNode.createRelationshipTo(eNode, AN._); RID.set(res, id); return res; } }) }; } //search for have have = getByHave(pflow, tdR, tdR.getEndNode(), thes); if (have != null) return have; } return null; } //XXX: in-use by SELF public Relationship[] getBySELF(final PFlow pf, Node context, final Set<Node> thes) { //System.out.println("GET get context = "+context); //search for local 'HAVE' Relationship[] have = getByHave(pf, null, context, thes); if (have != null) return have; Node instance = Utils.getSingleREF(context); if (instance != null) { //change context to the-instance by REF context = instance; //search for have have = getByHave(pf, null, context, thes); if (have != null) return have; } Relationship prevTHE = null; //search 'IC' by 'IS' topology for (Relationship tdR : td_eval_ic.traverse(context).relationships()) { Statement st = Statements.relationshipType(tdR); if (st instanceof AN) { //System.out.println("GET IC -> IS "+tdR); if (prevTHE != null) { //search for have have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes); if (have != null) return have; } prevTHE = tdR; } else if (st instanceof SHALL) { //System.out.print("GET IC -> "+tdR); if (thes.contains(Utils.getSingleREF(tdR.getEndNode()))) { //System.out.println(" MATCH"); //store final Node sNode = context; final Relationship r = tdR; return new Relationship[] { AnimoGraph.execute(new GraphOperation<Relationship>() { @Override public Relationship execute() { Relationship res = sNode.createRelationshipTo(r.getEndNode(), AN._); //RID.set(res, r.getId()); return res; } }) }; //in-memory //Relationship res = new InMemoryRelationship(context, tdR.getEndNode(), AN._.relationshipType()); //RID.set(res, tdR.getId()); //return res; //as it //return tdR; } //System.out.println(); } } if (prevTHE != null) { //search for have have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes); if (have != null) return have; } return null; } private Relationship[] getByHave(final PFlow pflow, Relationship op, final Node context, final Set<Node> thes) { if (context == null) return null; TraversalDescription trav = td. relationships(AN._, OUTGOING). relationships(REF._, OUTGOING). relationships(SHALL._, OUTGOING). evaluator(new Searcher(){ @Override public Evaluation evaluate(Path path) { //System.out.println(path); return _evaluate_(path, thes); } }); Map<Relationship, Path> paths = new FastMap<Relationship, Path>(); for (Path path : trav.traverse(context)) { System.out.println("* "+path); if (path.length() == 1) { if (op == null) { System.out.println("WARNING: DONT KNOW OP"); continue; } paths.put(op, path); //break; } if (path.length() == 2) { //UNDERSTAND: should we check context return new Relationship[] {path.relationships().iterator().next()}; } Relationship fR = path.relationships().iterator().next(); Path p = paths.get(fR); if (p == null || p.length() > path.length()) { paths.put(fR, path); } } int i = 0; int j = 0; Relationship startBy = null; Relationship res = null; List<Relationship> resByHAVE = new FastList<Relationship>(); List<Relationship> resByIS = new FastList<Relationship>(); for (Path path : paths.values()) { for (Relationship r : path.relationships()) { if (startBy == null) startBy = r; if (!pflow.isInStack(r)) { if (r.isType(AN._)) { if (Utils.haveContext(r.getEndNode())) { res = r; //break; } } else if (r.isType(SHALL._)) { res = r; break; } } } if (res != null) { if (startBy != null && startBy.isType(REF._)) resByIS.add(res); else resByHAVE.add(res); } startBy = null; } if (resByHAVE.isEmpty()) return resByHAVE.toArray(new Relationship[resByHAVE.size()]); return resByIS.toArray(new Relationship[resByHAVE.size()]); } private Relationship getShall(final Node context, final Set<Node> thes) { // TraversalDescription trav = td. // evaluator(new Searcher(){ // @Override // public Evaluation evaluate(Path path) { // return _evaluate_(path, thes); //, IC._ // Relationship res = null; // for (Path path : trav.traverse(context)) { // //TODO: check that this is only one answer // //System.out.println(path); // for (Relationship r : path.relationships()) { // res = r; // break; for (Relationship r : context.getRelationships(OUTGOING, SHALL._)) { for (QCAVector rr : Utils.getByREF(null, r)) { if (thes.contains(rr.getAnswer().getEndNode())) return r; } } return null; } }
package org.animotron.statement.query; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import javolution.util.FastTable; import org.animotron.graph.index.Order; import org.animotron.io.Pipe; import org.animotron.manipulator.Evaluator; import org.animotron.manipulator.OnContext; import org.animotron.manipulator.OnQuestion; import org.animotron.manipulator.PFlow; import org.animotron.manipulator.QCAVector; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.operator.*; import org.animotron.statement.relation.SHALL; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.animotron.graph.RelationshipTypes.RESULT; /** * Query operator 'Get'. Return 'have' relations on provided context. * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> */ public class GET extends AbstractQuery implements Shift { public static final GET _ = new GET(); private static boolean debug = false; private GET() { super("get", "<~"); } protected GET(String... name) { super(name); } public OnQuestion onCalcQuestion() { return new Calc(); } class Calc extends OnQuestion { @Override public void act(final PFlow pf) throws IOException { //if (debug) System.out.println("GET "+Thread.currentThread()); final Relationship op = pf.getOP(); final Node node = op.getEndNode(); final FastSet<Relationship> visitedREFs = FastSet.newInstance(); final FastSet<Node> thes = FastSet.newInstance(); try { // Relationship r = null; Pipe p = AN.getREFs(pf, pf.getVector()); QCAVector theNode; while ((theNode = p.take()) != null) { // r = theNode.getClosest(); // if (r.isType(AN._)) { // try { // Pipe pp = Utils.eval(pf.getController(), theNode); // QCAVector rr; // while ((rr = pp.take()) != null) { // thes.add(rr.getClosestEndNode()); // } catch (Throwable t) { // pf.sendException(t); // return; // } else thes.add( DEF._.getDef( theNode.getClosestEndNode() ) ); } evalGet(pf, op, node, thes, visitedREFs); } finally { FastSet.recycle(thes); FastSet.recycle(visitedREFs); } } private void evalGet( final PFlow pf, final Relationship op, final Node node, final Set<Node> thes, final Set<Relationship> visitedREFs) throws IOException { if (debug) { Utils.debug(GET._, op, thes); } //check, maybe, result was already calculated if (!Utils.results(pf)) { //no pre-calculated result, calculate it OnContext onContext = new OnContext() { @Override public void onMessage(QCAVector vector) { super.onMessage(vector); if (vector == null) return; if (debug) { System.out.println("GET on context "+Thread.currentThread()); System.out.println("GET ["+op+"] vector "+vector); } get(pf, vector, thes, visitedREFs); } }; //pf.answerChannel().subscribe(onContext); if (Utils.haveContext(pf)) { Evaluator.sendQuestion(pf.getController(), onContext, pf.getVector(), node); onContext.isDone(); } else { if (debug) System.out.println("\nGET ["+op+"] empty "); FastSet<QCAVector> refs = FastSet.newInstance(); try { QCAVector vector = pf.getVector(); if (vector.getContext() != null) { for (QCAVector v : vector.getContext()) { refs.add(v); } } // vector = vector.getPrecedingSibling(); // while (vector != null) { // refs.add(vector); // vector = vector.getPrecedingSibling(); get(pf, refs, thes, visitedREFs, false); } finally { FastSet.recycle(refs); } } } }; } public boolean get(PFlow pf, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) { FastSet<QCAVector> refs = FastSet.newInstance(); try { refs.add(vector); return get(pf, refs, thes, visitedREFs, true); } finally { FastSet.recycle(refs); } } private boolean check( final PFlow pf, final QCAVector v, final Relationship toCheck, final Node middle, final Set<Node> thes, final Set<Relationship> visitedREFs, final boolean onContext) { if (toCheck == null) return false; if (visitedREFs.contains(toCheck)) return false; //if (toCheck.isType(REF._) && visitedREFs.contains(v.getQuestion())) return false; visitedREFs.add(toCheck); if (searchForHAVE(pf, toCheck, v, middle, thes, onContext)) return true; //if (!pf.isInStack(have[i])) { //set.add(new QCAVector(op, v, have[i])); return false; } public boolean get( final PFlow pf, final Set<QCAVector> REFs, final Set<Node> thes, Set<Relationship> visitedREFs, final boolean onContext) { if (visitedREFs == null) visitedREFs = new FastSet<Relationship>(); FastSet<QCAVector> nextREFs = FastSet.newInstance(); FastSet<QCAVector> newREFs = FastSet.newInstance(); FastSet<QCAVector> tmp = null; try { nextREFs.addAll(REFs); boolean found = false; Relationship t = null; while (true) { if (debug) System.out.println("["+pf.getOP()+"] nextREFs "); QCAVector v = null; for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) { v = nextREFs.valueOf(r); if (debug) System.out.println("checking "+v); if (v.getQuestion() != null && v.hasAnswer()) { Node middle = null; Statement s = Statements.relationshipType(v.getQuestion()); if (s instanceof ANY) { try { middle = v.getQuestion().getEndNode().getSingleRelationship(REF._, OUTGOING).getEndNode(); } catch (Exception e) { e.printStackTrace(); } } if (!check(pf, v, v.getUnrelaxedAnswer(), middle, thes, visitedREFs, onContext)) { if (v.getAnswers() != null) for (QCAVector vv : v.getAnswers()) { if (check(pf, v, vv.getUnrelaxedAnswer(), middle, thes, visitedREFs, onContext)) found = true; } } else { found = true; } } visitedREFs.add(v.getQuestion()); } if (found) return true; for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) { v = nextREFs.valueOf(r); List<QCAVector> cs = v.getContext(); if (cs != null) { for (QCAVector c : cs) { checkVector(c, newREFs, visitedREFs); } } // t = v.getUnrelaxedAnswer(); // if (t != null && !t.equals(v.getQuestion())) { // if (! t.isType(AN._)) // getOutgoingReferences(pf, v, t, t.getStartNode(), newREFs, visitedREFs); // getOutgoingReferences(pf, v, t, t.getEndNode(), newREFs, visitedREFs); // t = v.getQuestion(); // if (t != null && t.isType(DEF._)) { // getOutgoingReferences(pf, v, t, t.getEndNode(), newREFs, visitedREFs); } if (newREFs.size() == 0) return false; //swap tmp = nextREFs; nextREFs = newREFs; newREFs = tmp; newREFs.clear(); } } finally { FastSet.recycle(nextREFs); FastSet.recycle(newREFs); } } private void checkVector(final QCAVector c, final Set<QCAVector> newREFs, final Set<Relationship> visitedREFs) { Relationship t = c.getUnrelaxedAnswer(); if (t != null && !visitedREFs.contains(t)) newREFs.add(c); else { t = c.getQuestion(); if (!visitedREFs.contains(t)) newREFs.add(c); } } private void getOutgoingReferences(PFlow pf, QCAVector vector, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) { QCAVector cV = null; IndexHits<Relationship> it = Order._.context(node); try { for (Relationship r : it) { if (visitedREFs != null && visitedREFs.contains(r)) { continue; } cV = vector.question(r); Statement st = Statements.relationshipType(r); if (st instanceof AN) { Pipe p = AN.getREFs(pf, cV); QCAVector v; while ((v = p.take()) != null) { Relationship t = v.getClosest(); cV.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(t)) { newREFs.add(v); } } } else if (st instanceof Reference) { // if (!pf.isInStack(r)) { //System.out.println("["+pf.getOP()+"] evaluate "+prev); Pipe in = Evaluator._.execute(pf.getController(), cV); QCAVector v; while ((v = in.take()) != null) { cV.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(v.getAnswer())) newREFs.add(v); } } } } catch (Throwable t) { pf.sendException(t); } finally { it.close(); } } private boolean searchForHAVE( final PFlow pf, final Relationship ref, final QCAVector v, final Node middle, final Set<Node> thes, final boolean onContext) { //search for inside 'HAVE' //return searchForHAVE(pf, ref, ref.getEndNode(), thes); if (getByHave(pf, v, ref, DEF._.getActualEndNode(ref), middle, thes, onContext)) return true; //search for local 'HAVE' if (ref.isType(REF._)) { if (getByHave(pf, v, v.getQuestion(), ref.getStartNode(), middle, thes, onContext)) return true; } return false; } private boolean relaxReference(PFlow pf, QCAVector vector, Relationship op) { try{ if (!(op.isType(ANY._) || op.isType(GET._))) { if (debug) System.out.println("["+pf.getOP()+"] answered "+op); pf.sendAnswer(pf.getVector().answered(op, vector), RESULT); //pf.sendAnswer(op); return true; } if (debug) System.out.println("["+pf.getOP()+"] Relaxing "+op+" @ "+vector); try { Pipe in = Evaluator._.execute(pf.getController(), vector.question(op)); //if (!in.hasNext()) return false; boolean answered = false; Relationship res = null; QCAVector v; while ((v = in.take()) != null) { res = v.getAnswer(); if (!pf.isInStack(res)) { if (debug) System.out.println("["+pf.getOP()+"] Relaxing answered "+v.getAnswer()); pf.sendAnswer(vector.answered(v.getAnswer(), v), RESULT); answered = true; } } return answered; } catch (IOException e) { pf.sendException(e); } } catch (Throwable t) { pf.sendException(t); } return false; } private boolean haveMiddle(Path path, Node middle) { for (Node n : path.nodes()) { if (n.equals(middle)) return true; } return false; } private static TraversalDescription prepared = Traversal.description(). depthFirst(). uniqueness(Uniqueness.RELATIONSHIP_PATH). relationships(ANY._, OUTGOING). relationships(AN._, OUTGOING). relationships(REF._, OUTGOING). relationships(GET._, OUTGOING). relationships(SHALL._, OUTGOING); private boolean getByHave( final PFlow pf, QCAVector vector, Relationship op, final Node context, final Node middle, final Set<Node> thes, final boolean onContext) { if (context == null) return false; if (debug) System.out.println("middle "+middle); TraversalDescription trav = prepared. evaluator(new Searcher(){ @Override public Evaluation evaluate(Path path) { return _evaluate_(path, thes); } }); FastMap<Relationship, List<Path>> paths = FastMap.newInstance(); try { boolean middlePresent = false; List<Path> l; for (Path path : trav.traverse(context)) { if (debug) System.out.println("["+pf.getOP()+"] * "+path); if (path.length() == 1) { if (op == null) { System.out.println("WARNING: DONT KNOW OP"); continue; } if (pf.getOP().equals(op)) continue; l = new FastList<Path>(); l.add(path); paths.put(op, l); continue; } if (path.length() == 2) { //UNDERSTAND: should we check context Relationship r = path.relationships().iterator().next(); if (pf.getVector().getQuestion().getId() == r.getId()) continue; if (relaxReference(pf, vector, r)) return true; } Relationship fR = path.relationships().iterator().next(); List<Path> ps = paths.get(fR); if (ps == null) {// || p.length() > path.length()) { boolean thisMiddle = haveMiddle(path, middle); if (middlePresent) { if (thisMiddle) { l = new FastList<Path>(); l.add(path); paths.put(fR, l); } } else { if (thisMiddle) { middlePresent = thisMiddle; paths.clear(); } l = new FastList<Path>(); l.add(path); paths.put(fR, l); } } else { l = paths.get(fR); if (l.get(0).length() > path.length()) { middlePresent = haveMiddle(path, middle); l.clear(); l.add(path); } else if (l.get(0).length() == path.length()) { boolean thisMiddle = haveMiddle(path, middle); if (middlePresent) { if (thisMiddle) l.add(path); } else { if (thisMiddle) { middlePresent = thisMiddle; l.clear(); l.add(path); } else { l.add(path); } } } } } if (paths.isEmpty()) return false; Relationship startBy = null; int refs = 0; int ANs = 0; //if (op.isType(RESULT)) ANs++; Relationship res = null; Relationship prevRes = null; Relationship prevPrevRes = null; FastTable<Relationship> resByHAVE = FastTable.newInstance(); FastTable<Relationship> resByIS = FastTable.newInstance(); try { for (List<Path> ps : paths.values()) { for (Path path : ps) { res = null; prevRes = null; prevPrevRes = null; if (path.length() == 1 && path.lastRelationship().isType(REF._)) { res = op; } else { Iterator<Relationship> it = path.relationships().iterator(); for (Relationship r = null; it.hasNext(); ) { r = it.next(); if (startBy == null) startBy = r; if (!pf.isInStack(r)) { if (r.isType(AN._)) { res = r; ANs++; } else { if (ANs > 1) { //check is it pseudo HAVE or IS topology. on HAVE return it else last of top if (r.isType(REF._) && it.hasNext()) { r = it.next(); if (r.isType(AN._) && Utils.haveContext(r.getEndNode())) res = r; } break; } ANs = 0; if (r.isType(ANY._)) { if (it.hasNext() && it.next().isType(REF._) && !it.hasNext()) { res = r; } else { res = null; } break; } else if (r.isType(GET._)) { if (it.hasNext()) if (it.next().isType(REF._) && !it.hasNext()) res = r; break; } else if (r.isType(SHALL._)) { res = r; } else if (r.isType(REF._)) { //ignore pseudo IS if (Utils.haveContext(r.getStartNode())) { prevRes = null; if (onContext) break; else if (refs > 1) break; refs++; } else { prevPrevRes = prevRes; prevRes = res; } } } } } } if (prevPrevRes != null) res = prevPrevRes; if (res != null) { if (startBy != null && startBy.isType(REF._)) resByIS.add(res); else resByHAVE.add(res); } startBy = null; } } if (!resByHAVE.isEmpty()) { for (Relationship r : resByHAVE) { relaxReference(pf, vector, r); } } else { if (resByIS.isEmpty()) return false; for (Relationship r : resByIS) { relaxReference(pf, vector, r); } } } finally{ FastTable.recycle(resByHAVE); FastTable.recycle(resByIS); } return true; } finally { FastMap.recycle(paths); } } }
package org.b3log.symphony.util; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Latkes; import org.b3log.latke.cache.Cache; import org.b3log.latke.cache.CacheFactory; import org.b3log.latke.ioc.LatkeBeanManagerImpl; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.LangPropsServiceImpl; import org.b3log.latke.util.MD5; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import org.jsoup.select.NodeVisitor; import static org.parboiled.common.Preconditions.checkArgNotNull; import org.pegdown.DefaultVerbatimSerializer; import org.pegdown.Extensions; import org.pegdown.LinkRenderer; import org.pegdown.PegDownProcessor; import org.pegdown.Printer; import org.pegdown.VerbatimSerializer; import org.pegdown.ast.*; import org.pegdown.plugins.ToHtmlSerializerPlugin; public final class Markdowns { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Markdowns.class); /** * Language service. */ public static final LangPropsService LANG_PROPS_SERVICE = LatkeBeanManagerImpl.getInstance().getReference(LangPropsServiceImpl.class); /** * Markdown cache. */ private static final Cache MD_CACHE = CacheFactory.getCache("markdown"); static { MD_CACHE.setMaxCount(1024 * 10 * 4); } /** * Markdown to HTML timeout. */ private static final int MD_TIMEOUT = 800; /** * Whether marked is available. */ public static boolean MARKED_AVAILABLE; private static final String MARKED_ENGINE_URL = "http://localhost:8250"; static { try { final URL url = new URL(MARKED_ENGINE_URL); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); final OutputStream outputStream = conn.getOutputStream(); IOUtils.write("Symphony ", outputStream, "UTF-8"); IOUtils.closeQuietly(outputStream); final InputStream inputStream = conn.getInputStream(); final String html = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); MARKED_AVAILABLE = StringUtils.contains(html, "<p>Symphony </p>"); if (MARKED_AVAILABLE) { LOGGER.log(Level.INFO, "[marked] is available, uses it for markdown processing"); } else { LOGGER.log(Level.INFO, "[marked] is not available, uses built-in [pegdown] for markdown processing"); } } catch (final Exception e) { LOGGER.log(Level.INFO, "[marked] is not available, uses built-in [pegdown] for markdown processing: " + e.getMessage()); } } /** * Gets the safe HTML content of the specified content. * * @param content the specified content * @param baseURI the specified base URI, the relative path value of href will starts with this URL * @return safe HTML content */ public static String clean(final String content, final String baseURI) { final Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); final String tmp = Jsoup.clean(content, baseURI, Whitelist.relaxed(). addAttributes(":all", "id", "target", "class"). addTags("span", "hr", "kbd", "samp", "tt", "del", "s", "strike", "u"). addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight"). addAttributes("audio", "controls", "src"). addAttributes("video", "controls", "src", "width", "height"). addAttributes("source", "src", "media", "type"). addAttributes("object", "width", "height", "data", "type"). addAttributes("param", "name", "value"). addAttributes("embed", "src", "type", "width", "height", "wmode", "allowNetworking"), outputSettings); final Document doc = Jsoup.parse(tmp, baseURI, Parser.xmlParser()); final Elements ps = doc.getElementsByTag("p"); for (final Element p : ps) { p.removeAttr("style"); } final Elements as = doc.getElementsByTag("a"); for (final Element a : as) { a.attr("rel", "nofollow"); final String href = a.attr("href"); if (href.startsWith(Latkes.getServePath())) { continue; } a.attr("target", "_blank"); } final Elements audios = doc.getElementsByTag("audio"); for (final Element audio : audios) { audio.attr("preload", "none"); } final Elements videos = doc.getElementsByTag("video"); for (final Element video : videos) { video.attr("preload", "none"); } return doc.html(); } /** * Converts the email or url text to HTML. * * @param markdownText the specified markdown text * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns * 'markdownErrorLabel' if exception */ public static String linkToHtml(final String markdownText) { if (Strings.isEmptyOrNull(markdownText)) { return ""; } String ret = getHTML(markdownText); if (null != ret) { return ret; } final ExecutorService pool = Executors.newSingleThreadExecutor(); final long[] threadId = new long[1]; final Callable<String> call = new Callable<String>() { @Override public String call() throws Exception { threadId[0] = Thread.currentThread().getId(); String ret = LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); if (MARKED_AVAILABLE) { ret = toHtmlByMarked(markdownText); if (!StringUtils.startsWith(ret, "<p>")) { ret = "<p>" + ret + "</p>"; } } else { final PegDownProcessor pegDownProcessor = new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS); final RootNode node = pegDownProcessor.parseMarkdown(markdownText.toCharArray()); ret = new ToHtmlSerializer(new LinkRenderer(), Collections.<String, VerbatimSerializer>emptyMap(), Arrays.asList(new ToHtmlSerializerPlugin[0])).toHtml(node); if (!StringUtils.startsWith(ret, "<p>")) { ret = "<p>" + ret + "</p>"; } ret = formatMarkdown(ret); } // cache it putHTML(markdownText, ret); return ret; } }; try { final Future<String> future = pool.submit(call); return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]"); final Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (final Thread thread : threads) { if (thread.getId() == threadId[0]) { thread.stop(); break; } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e); } finally { pool.shutdownNow(); } return ""; } /** * Converts the specified markdown text to HTML. * * @param markdownText the specified markdown text * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns * 'markdownErrorLabel' if exception */ public static String toHTML(final String markdownText) { if (Strings.isEmptyOrNull(markdownText)) { return ""; } String ret = getHTML(markdownText); if (null != ret) { return ret; } final ExecutorService pool = Executors.newSingleThreadExecutor(); final long[] threadId = new long[1]; final Callable<String> call = new Callable<String>() { @Override public String call() throws Exception { threadId[0] = Thread.currentThread().getId(); String ret = LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); if (MARKED_AVAILABLE) { ret = toHtmlByMarked(markdownText); if (!StringUtils.startsWith(ret, "<p>")) { ret = "<p>" + ret + "</p>"; } } else { final PegDownProcessor pegDownProcessor = new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS); final RootNode node = pegDownProcessor.parseMarkdown(markdownText.toCharArray()); ret = new ToHtmlSerializer(new LinkRenderer(), Collections.<String, VerbatimSerializer>emptyMap(), Arrays.asList(new ToHtmlSerializerPlugin[0])).toHtml(node); if (!StringUtils.startsWith(ret, "<p>")) { ret = "<p>" + ret + "</p>"; } ret = formatMarkdown(ret); } // cache it putHTML(markdownText, ret); return ret; } }; Stopwatchs.start("Md to HTML"); try { final Future<String> future = pool.submit(call); return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]"); final Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (final Thread thread : threads) { if (thread.getId() == threadId[0]) { thread.stop(); break; } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e); } finally { pool.shutdownNow(); Stopwatchs.end(); } return LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); } private static String toHtmlByMarked(final String markdownText) throws Exception { final URL url = new URL(MARKED_ENGINE_URL); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); final OutputStream outputStream = conn.getOutputStream(); IOUtils.write(markdownText, outputStream, "UTF-8"); IOUtils.closeQuietly(outputStream); final InputStream inputStream = conn.getInputStream(); final String html = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); // Pangu space final Document doc = Jsoup.parse(html); doc.traverse(new NodeVisitor() { @Override public void head(final org.jsoup.nodes.Node node, int depth) { if (node instanceof org.jsoup.nodes.TextNode) { // final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node; // textNode.text(Pangu.spacingText(textNode.getWholeText())); // FIXME: Pangu space } } @Override public void tail(org.jsoup.nodes.Node node, int depth) { } }); doc.outputSettings().prettyPrint(false); String ret = doc.html(); ret = StringUtils.substringBetween(ret, "<body>", "</body>"); ret = StringUtils.trim(ret); return ret; } private static String formatMarkdown(final String markdownText) { String ret = markdownText; final Document doc = Jsoup.parse(markdownText, "", Parser.xmlParser()); final Elements tagA = doc.select("a"); for (int i = 0; i < tagA.size(); i++) { final String search = tagA.get(i).attr("href"); final String replace = StringUtils.replace(search, "_", "[downline]"); ret = StringUtils.replace(ret, search, replace); } final Elements tagImg = doc.select("img"); for (int i = 0; i < tagImg.size(); i++) { final String search = tagImg.get(i).attr("src"); final String replace = StringUtils.replace(search, "_", "[downline]"); ret = StringUtils.replace(ret, search, replace); } final Elements tagCode = doc.select("code"); for (int i = 0; i < tagCode.size(); i++) { final String search = tagCode.get(i).html(); final String replace = StringUtils.replace(search, "_", "[downline]"); ret = StringUtils.replace(ret, search, replace); } String[] rets = ret.split("\n"); for (String temp : rets) { final String[] toStrong = StringUtils.substringsBetween(temp, "**", "**"); final String[] toEm = StringUtils.substringsBetween(temp, "_", "_"); if (toStrong != null && toStrong.length > 0) { for (final String strong : toStrong) { final String search = "**" + strong + "**"; final String replace = "<strong>" + strong + "</strong>"; ret = StringUtils.replace(ret, search, replace); } } if (toEm != null && toEm.length > 0) { for (final String em : toEm) { final String search = "_" + em + "_"; final String replace = "<em>" + em + "<em>"; ret = StringUtils.replace(ret, search, replace); } } } ret = StringUtils.replace(ret, "[downline]", "_"); return ret; } /** * Enhanced with {@link Pangu} for text node. */ private static class ToHtmlSerializer implements Visitor { protected Printer printer = new Printer(); protected final Map<String, ReferenceNode> references = new HashMap<String, ReferenceNode>(); protected final Map<String, String> abbreviations = new HashMap<String, String>(); protected final LinkRenderer linkRenderer; protected final List<ToHtmlSerializerPlugin> plugins; protected TableNode currentTableNode; protected int currentTableColumn; protected boolean inTableHeader; protected Map<String, VerbatimSerializer> verbatimSerializers; public ToHtmlSerializer(LinkRenderer linkRenderer) { this(linkRenderer, Collections.<ToHtmlSerializerPlugin>emptyList()); } public ToHtmlSerializer(LinkRenderer linkRenderer, List<ToHtmlSerializerPlugin> plugins) { this(linkRenderer, Collections.<String, VerbatimSerializer>emptyMap(), plugins); } public ToHtmlSerializer(final LinkRenderer linkRenderer, final Map<String, VerbatimSerializer> verbatimSerializers) { this(linkRenderer, verbatimSerializers, Collections.<ToHtmlSerializerPlugin>emptyList()); } public ToHtmlSerializer(final LinkRenderer linkRenderer, final Map<String, VerbatimSerializer> verbatimSerializers, final List<ToHtmlSerializerPlugin> plugins) { this.linkRenderer = linkRenderer; this.verbatimSerializers = new HashMap<>(verbatimSerializers); if (!this.verbatimSerializers.containsKey(VerbatimSerializer.DEFAULT)) { this.verbatimSerializers.put(VerbatimSerializer.DEFAULT, DefaultVerbatimSerializer.INSTANCE); } this.plugins = plugins; } public String toHtml(RootNode astRoot) { checkArgNotNull(astRoot, "astRoot"); astRoot.accept(this); return printer.getString(); } public void visit(RootNode node) { for (ReferenceNode refNode : node.getReferences()) { visitChildren(refNode); references.put(normalize(printer.getString()), refNode); printer.clear(); } for (AbbreviationNode abbrNode : node.getAbbreviations()) { visitChildren(abbrNode); String abbr = printer.getString(); printer.clear(); abbrNode.getExpansion().accept(this); String expansion = printer.getString(); abbreviations.put(abbr, expansion); printer.clear(); } visitChildren(node); } public void visit(AbbreviationNode node) { } public void visit(AnchorLinkNode node) { printLink(linkRenderer.render(node)); } public void visit(AutoLinkNode node) { printLink(linkRenderer.render(node)); } public void visit(BlockQuoteNode node) { printIndentedTag(node, "blockquote"); } public void visit(BulletListNode node) { printIndentedTag(node, "ul"); } public void visit(CodeNode node) { printTag(node, "code"); } public void visit(DefinitionListNode node) { printIndentedTag(node, "dl"); } public void visit(DefinitionNode node) { printConditionallyIndentedTag(node, "dd"); } public void visit(DefinitionTermNode node) { printConditionallyIndentedTag(node, "dt"); } public void visit(ExpImageNode node) { String text = printChildrenToString(node); printImageTag(linkRenderer.render(node, text)); } public void visit(ExpLinkNode node) { String text = printChildrenToString(node); printLink(linkRenderer.render(node, text)); } public void visit(HeaderNode node) { printBreakBeforeTag(node, "h" + node.getLevel()); } public void visit(HtmlBlockNode node) { String text = node.getText(); if (text.length() > 0) { printer.println(); } printer.print(text); } public void visit(InlineHtmlNode node) { printer.print(node.getText()); } public void visit(ListItemNode node) { if (node instanceof TaskListNode) { // vsch: #185 handle GitHub style task list items, these are a bit messy because the <input> checkbox needs to be // included inside the optional <p></p> first grand-child of the list item, first child is always RootNode // because the list item text is recursively parsed. Node firstChild = node.getChildren().get(0).getChildren().get(0); boolean firstIsPara = firstChild instanceof ParaNode; int indent = node.getChildren().size() > 1 ? 2 : 0; boolean startWasNewLine = printer.endsWithNewLine(); printer.println().print("<li class=\"task-list-item\">").indent(indent); if (firstIsPara) { printer.println().print("<p>"); printer.print("<input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (((TaskListNode) node).isDone() ? " checked=\"checked\"" : "") + " disabled=\"disabled\"></input>"); visitChildren((SuperNode) firstChild); // render the other children, the p tag is taken care of here visitChildrenSkipFirst(node); printer.print("</p>"); } else { printer.print("<input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (((TaskListNode) node).isDone() ? " checked=\"checked\"" : "") + " disabled=\"disabled\"></input>"); visitChildren(node); } printer.indent(-indent).printchkln(indent != 0).print("</li>") .printchkln(startWasNewLine); } else { printConditionallyIndentedTag(node, "li"); } } public void visit(MailLinkNode node) { printLink(linkRenderer.render(node)); } public void visit(OrderedListNode node) { printIndentedTag(node, "ol"); } public void visit(ParaNode node) { printBreakBeforeTag(node, "p"); } public void visit(QuotedNode node) { switch (node.getType()) { case DoubleAngle: printer.print("&laquo;"); visitChildren(node); printer.print("&raquo;"); break; case Double: printer.print("&ldquo;"); visitChildren(node); printer.print("&rdquo;"); break; case Single: printer.print("&lsquo;"); visitChildren(node); printer.print("&rsquo;"); break; } } public void visit(ReferenceNode node) { // reference nodes are not printed } public void visit(RefImageNode node) { String text = printChildrenToString(node); String key = node.referenceKey != null ? printChildrenToString(node.referenceKey) : text; ReferenceNode refNode = references.get(normalize(key)); if (refNode == null) { // "fake" reference image link printer.print("![").print(text).print(']'); if (node.separatorSpace != null) { printer.print(node.separatorSpace).print('['); if (node.referenceKey != null) { printer.print(key); } printer.print(']'); } } else { printImageTag(linkRenderer.render(node, refNode.getUrl(), refNode.getTitle(), text)); } } public void visit(RefLinkNode node) { String text = printChildrenToString(node); String key = node.referenceKey != null ? printChildrenToString(node.referenceKey) : text; ReferenceNode refNode = references.get(normalize(key)); if (refNode == null) { // "fake" reference link printer.print('[').print(text).print(']'); if (node.separatorSpace != null) { printer.print(node.separatorSpace).print('['); if (node.referenceKey != null) { printer.print(key); } printer.print(']'); } } else { printLink(linkRenderer.render(node, refNode.getUrl(), refNode.getTitle(), text)); } } public void visit(SimpleNode node) { switch (node.getType()) { case Apostrophe: printer.print("&rsquo;"); break; case Ellipsis: printer.print("&hellip;"); break; case Emdash: printer.print("&mdash;"); break; case Endash: printer.print("&ndash;"); break; case HRule: printer.println().print("<hr/>"); break; case Linebreak: printer.print("<br/>"); break; case Nbsp: printer.print("&nbsp;"); break; default: throw new IllegalStateException(); } } public void visit(StrongEmphSuperNode node) { if (node.isClosed()) { if (node.isStrong()) { printTag(node, "strong"); } else { printTag(node, "em"); } } else { //sequence was not closed, treat open chars as ordinary chars printer.print(node.getChars()); visitChildren(node); } } public void visit(StrikeNode node) { printTag(node, "del"); } public void visit(TableBodyNode node) { printIndentedTag(node, "tbody"); } @Override public void visit(TableCaptionNode node) { printer.println().print("<caption>"); visitChildren(node); printer.print("</caption>"); } public void visit(TableCellNode node) { String tag = inTableHeader ? "th" : "td"; List<TableColumnNode> columns = currentTableNode.getColumns(); TableColumnNode column = columns.get(Math.min(currentTableColumn, columns.size() - 1)); printer.println().print('<').print(tag); column.accept(this); if (node.getColSpan() > 1) { printer.print(" colspan=\"").print(Integer.toString(node.getColSpan())).print('"'); } printer.print('>'); visitChildren(node); printer.print('<').print('/').print(tag).print('>'); currentTableColumn += node.getColSpan(); } public void visit(TableColumnNode node) { switch (node.getAlignment()) { case None: break; case Left: printer.print(" align=\"left\""); break; case Right: printer.print(" align=\"right\""); break; case Center: printer.print(" align=\"center\""); break; default: throw new IllegalStateException(); } } public void visit(TableHeaderNode node) { inTableHeader = true; printIndentedTag(node, "thead"); inTableHeader = false; } public void visit(TableNode node) { currentTableNode = node; printIndentedTag(node, "table"); currentTableNode = null; } public void visit(TableRowNode node) { currentTableColumn = 0; printIndentedTag(node, "tr"); } public void visit(VerbatimNode node) { VerbatimSerializer serializer = lookupSerializer(node.getType()); serializer.serialize(node, printer); } protected VerbatimSerializer lookupSerializer(final String type) { if (type != null && verbatimSerializers.containsKey(type)) { return verbatimSerializers.get(type); } else { return verbatimSerializers.get(VerbatimSerializer.DEFAULT); } } public void visit(WikiLinkNode node) { printLink(linkRenderer.render(node)); } public void visit(TextNode node) { if (abbreviations.isEmpty()) { printer.print(Pangu.spacingText(node.getText())); } else { printWithAbbreviations(node.getText()); } } public void visit(SpecialTextNode node) { printer.printEncoded(node.getText()); } public void visit(SuperNode node) { visitChildren(node); } public void visit(Node node) { for (ToHtmlSerializerPlugin plugin : plugins) { if (plugin.visit(node, this, printer)) { return; } } // override this method for processing custom Node implementations throw new RuntimeException("Don't know how to handle node " + node); } // helpers protected void visitChildren(SuperNode node) { for (Node child : node.getChildren()) { child.accept(this); } } // helpers protected void visitChildrenSkipFirst(SuperNode node) { boolean first = true; for (Node child : node.getChildren()) { if (!first) { child.accept(this); } first = false; } } protected void printTag(TextNode node, String tag) { printer.print('<').print(tag).print('>'); printer.printEncoded(node.getText()); printer.print('<').print('/').print(tag).print('>'); } protected void printTag(SuperNode node, String tag) { printer.print('<').print(tag).print('>'); visitChildren(node); printer.print('<').print('/').print(tag).print('>'); } protected void printBreakBeforeTag(SuperNode node, String tag) { boolean startWasNewLine = printer.endsWithNewLine(); printer.println(); printTag(node, tag); if (startWasNewLine) { printer.println(); } } protected void printIndentedTag(SuperNode node, String tag) { printer.println().print('<').print(tag).print('>').indent(+2); visitChildren(node); printer.indent(-2).println().print('<').print('/').print(tag).print('>'); } protected void printConditionallyIndentedTag(SuperNode node, String tag) { if (node.getChildren().size() > 1) { printer.println().print('<').print(tag).print('>').indent(+2); visitChildren(node); printer.indent(-2).println().print('<').print('/').print(tag).print('>'); } else { boolean startWasNewLine = printer.endsWithNewLine(); printer.println().print('<').print(tag).print('>'); visitChildren(node); printer.print('<').print('/').print(tag).print('>').printchkln(startWasNewLine); } } protected void printImageTag(LinkRenderer.Rendering rendering) { printer.print("<img"); printAttribute("src", rendering.href); // shouldn't include the alt attribute if its empty if (!rendering.text.equals("")) { printAttribute("alt", rendering.text); } for (LinkRenderer.Attribute attr : rendering.attributes) { printAttribute(attr.name, attr.value); } printer.print(" />"); } protected void printLink(LinkRenderer.Rendering rendering) { printer.print('<').print('a'); printAttribute("href", rendering.href); for (LinkRenderer.Attribute attr : rendering.attributes) { printAttribute(attr.name, attr.value); } printer.print('>').print(rendering.text).print("</a>"); } protected void printAttribute(String name, String value) { printer.print(' ').print(name).print('=').print('"').print(value).print('"'); } protected String printChildrenToString(SuperNode node) { Printer priorPrinter = printer; printer = new Printer(); visitChildren(node); String result = printer.getString(); printer = priorPrinter; return result; } protected String normalize(String string) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); switch (c) { case ' ': case '\n': case '\t': continue; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } protected void printWithAbbreviations(String string) { Map<Integer, Map.Entry<String, String>> expansions = null; for (Map.Entry<String, String> entry : abbreviations.entrySet()) { String abbr = entry.getKey(); int ix = 0; while (true) { int sx = string.indexOf(abbr, ix); if (sx == -1) { break; } // only allow whole word matches ix = sx + abbr.length(); if (sx > 0 && Character.isLetterOrDigit(string.charAt(sx - 1))) { continue; } if (ix < string.length() && Character.isLetterOrDigit(string.charAt(ix))) { continue; } if (expansions == null) { expansions = new TreeMap<Integer, Map.Entry<String, String>>(); } expansions.put(sx, entry); } } if (expansions != null) { int ix = 0; for (Map.Entry<Integer, Map.Entry<String, String>> entry : expansions.entrySet()) { int sx = entry.getKey(); String abbr = entry.getValue().getKey(); String expansion = entry.getValue().getValue(); printer.printEncoded(string.substring(ix, sx)); printer.print("<abbr"); if (org.parboiled.common.StringUtils.isNotEmpty(expansion)) { printer.print(" title=\""); printer.printEncoded(expansion); printer.print('"'); } printer.print('>'); printer.printEncoded(abbr); printer.print("</abbr>"); ix = sx + abbr.length(); } printer.print(string.substring(ix)); } else { printer.print(string); } } } /** * Gets HTML for the specified markdown text. * * @param markdownText the specified markdown text * @return HTML */ private static String getHTML(final String markdownText) { final String hash = MD5.hash(markdownText); return (String) MD_CACHE.get(hash); } /** * Puts the specified HTML into cache. * * @param markdownText the specified markdown text * @param html the specified HTML */ private static void putHTML(final String markdownText, final String html) { final String hash = MD5.hash(markdownText); MD_CACHE.put(hash, html); } /** * Private constructor. */ private Markdowns() { } }
package org.b3log.symphony.util; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.profiles.pegdown.Extensions; import com.vladsch.flexmark.profiles.pegdown.PegdownOptionsAdapter; import com.vladsch.flexmark.util.options.DataHolder; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Latkes; import org.b3log.latke.cache.Cache; import org.b3log.latke.cache.CacheFactory; import org.b3log.latke.ioc.LatkeBeanManager; import org.b3log.latke.ioc.LatkeBeanManagerImpl; import org.b3log.latke.ioc.Lifecycle; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.repository.jdbc.JdbcRepository; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.LangPropsServiceImpl; import org.b3log.latke.util.Callstacks; import org.b3log.latke.util.MD5; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Common; import org.b3log.symphony.service.UserQueryService; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import org.jsoup.select.NodeVisitor; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.*; public final class Markdowns { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Markdowns.class); /** * Language service. */ private static final LangPropsService LANG_PROPS_SERVICE = LatkeBeanManagerImpl.getInstance().getReference(LangPropsServiceImpl.class); /** * Bean manager. */ private static final LatkeBeanManager beanManager = Lifecycle.getBeanManager(); /** * User query service. */ private static final UserQueryService userQueryService; /** * Markdown cache. */ private static final Cache MD_CACHE = CacheFactory.getCache("markdown"); /** * Markdown to HTML timeout. */ private static final int MD_TIMEOUT = 2000; /** * Marked engine serve path. */ private static final String MARKED_ENGINE_URL = "http://localhost:8250"; /** * Built-in MD engine options. */ private static final DataHolder OPTIONS = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL_WITH_OPTIONALS); /** * Built-in MD engine parser. */ private static final com.vladsch.flexmark.parser.Parser PARSER = com.vladsch.flexmark.parser.Parser.builder(OPTIONS).build(); /** * Built-in MD engine HTML renderer. */ private static final HtmlRenderer RENDERER = HtmlRenderer.builder(OPTIONS).build(); /** * Whether marked is available. */ public static boolean MARKED_AVAILABLE; static { MD_CACHE.setMaxCount(1024 * 10 * 4); if (null != beanManager) { userQueryService = beanManager.getReference(UserQueryService.class); } else { userQueryService = null; } } static { try { final URL url = new URL(MARKED_ENGINE_URL); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); final OutputStream outputStream = conn.getOutputStream(); IOUtils.write("Symphony ", outputStream, "UTF-8"); IOUtils.closeQuietly(outputStream); final InputStream inputStream = conn.getInputStream(); final String html = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); MARKED_AVAILABLE = StringUtils.contains(html, "<p>Symphony </p>"); if (MARKED_AVAILABLE) { LOGGER.log(Level.INFO, "[marked] is available, uses it for markdown processing"); } else { LOGGER.log(Level.INFO, "[marked] is not available, uses built-in [flexmark] for markdown processing"); } } catch (final Exception e) { LOGGER.log(Level.INFO, "[marked] is not available caused by [" + e.getMessage() + "], uses built-in [flexmark] for markdown processing"); } } /** * Private constructor. */ private Markdowns() { } /** * Gets the safe HTML content of the specified content. * * @param content the specified content * @param baseURI the specified base URI, the relative path value of href will starts with this URL * @return safe HTML content */ public static String clean(final String content, final String baseURI) { final Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); final String tmp = Jsoup.clean(content, baseURI, Whitelist.relaxed(). addAttributes(":all", "id", "target", "class"). addTags("span", "hr", "kbd", "samp", "tt", "del", "s", "strike", "u"). addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight"). addAttributes("audio", "controls", "src"). addAttributes("video", "controls", "src", "width", "height"). addAttributes("source", "src", "media", "type"). addAttributes("object", "width", "height", "data", "type"). addAttributes("param", "name", "value"). addAttributes("input", "type", "disabled", "checked"). addAttributes("embed", "src", "type", "width", "height", "wmode", "allowNetworking"), outputSettings); final Document doc = Jsoup.parse(tmp, baseURI, Parser.htmlParser()); final Elements ps = doc.getElementsByTag("p"); for (final Element p : ps) { p.removeAttr("style"); } final Elements iframes = doc.getElementsByTag("iframe"); for (final Element iframe : iframes) { final String src = StringUtils.deleteWhitespace(iframe.attr("src")); if (StringUtils.startsWithIgnoreCase(src, "javascript") || StringUtils.startsWithIgnoreCase(src, "data:")) { iframe.remove(); } } final Elements objs = doc.getElementsByTag("object"); for (final Element obj : objs) { final String data = StringUtils.deleteWhitespace(obj.attr("data")); if (StringUtils.startsWithIgnoreCase(data, "data:") || StringUtils.startsWithIgnoreCase(data, "javascript")) { obj.remove(); continue; } final String type = StringUtils.deleteWhitespace(obj.attr("type")); if (StringUtils.containsIgnoreCase(type, "script")) { obj.remove(); } } final Elements embeds = doc.getElementsByTag("embed"); for (final Element embed : embeds) { final String data = StringUtils.deleteWhitespace(embed.attr("src")); if (StringUtils.startsWithIgnoreCase(data, "data:") || StringUtils.startsWithIgnoreCase(data, "javascript")) { embed.remove(); continue; } } final Elements as = doc.getElementsByTag("a"); for (final Element a : as) { a.attr("rel", "nofollow"); final String href = a.attr("href"); if (href.startsWith(Latkes.getServePath())) { continue; } a.attr("target", "_blank"); } final Elements audios = doc.getElementsByTag("audio"); for (final Element audio : audios) { audio.attr("preload", "none"); } final Elements videos = doc.getElementsByTag("video"); for (final Element video : videos) { video.attr("preload", "none"); } String ret = doc.body().html(); ret = ret.replaceAll("(</?br\\s*/?>\\s*)+", "<br>"); // patch for Jsoup issue return ret; } /** * Converts the specified markdown text to HTML. * * @param markdownText the specified markdown text * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns * 'markdownErrorLabel' if exception */ public static String toHTML(final String markdownText) { if (Strings.isEmptyOrNull(markdownText)) { return ""; } final String cachedHTML = getHTML(markdownText); if (null != cachedHTML) { return cachedHTML; } final ExecutorService pool = Executors.newSingleThreadExecutor(); final long[] threadId = new long[1]; final Callable<String> call = () -> { threadId[0] = Thread.currentThread().getId(); String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); if (MARKED_AVAILABLE) { html = toHtmlByMarked(markdownText); if (!StringUtils.startsWith(html, "<p>")) { html = "<p>" + html + "</p>"; } } else { com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText); html = RENDERER.render(document); if (!StringUtils.startsWith(html, "<p>")) { html = "<p>" + html + "</p>"; } } final Document doc = Jsoup.parse(html); final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>(); doc.traverse(new NodeVisitor() { @Override public void head(final org.jsoup.nodes.Node node, int depth) { if (node instanceof org.jsoup.nodes.TextNode) { final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node; final org.jsoup.nodes.Node parent = textNode.parent(); if (parent instanceof Element) { final Element parentElem = (Element) parent; if (!parentElem.tagName().equals("code")) { String text = textNode.getWholeText(); boolean nextIsBr = false; final org.jsoup.nodes.Node nextSibling = textNode.nextSibling(); if (nextSibling instanceof Element) { nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName()); } if (null != userQueryService) { try { final Set<String> userNames = userQueryService.getUserNames(text); for (final String userName : userNames) { text = text.replace('@' + userName + (nextIsBr ? "" : " "), "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a> "); } text = text.replace("@participants ", "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> "); } finally { JdbcRepository.dispose(); } } if (text.contains("@<a href=")) { final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem, ""); final int index = textNode.siblingIndex(); parentElem.insertChildren(index, nodes); toRemove.add(node); } else { textNode.text(Pangu.spacingText(text)); } } } } } @Override public void tail(org.jsoup.nodes.Node node, int depth) { } }); toRemove.forEach(node -> node.remove()); doc.select("pre>code").addClass("hljs"); doc.outputSettings().prettyPrint(false); String ret = doc.select("body").html(); ret = StringUtils.trim(ret); // cache it putHTML(markdownText, ret); return ret; }; Stopwatchs.start("Md to HTML"); try { final Future<String> future = pool.submit(call); return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]"); Callstacks.printCallstack(Level.ERROR, new String[]{"org.b3log"}, null); final Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (final Thread thread : threads) { if (thread.getId() == threadId[0]) { thread.stop(); break; } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e); } finally { pool.shutdownNow(); Stopwatchs.end(); } return LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); } private static String toHtmlByMarked(final String markdownText) throws Exception { final URL url = new URL(MARKED_ENGINE_URL); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); final OutputStream outputStream = conn.getOutputStream(); IOUtils.write(markdownText, outputStream, "UTF-8"); IOUtils.closeQuietly(outputStream); final InputStream inputStream = conn.getInputStream(); final String html = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); //conn.disconnect(); return html; } /** * Gets HTML for the specified markdown text. * * @param markdownText the specified markdown text * @return HTML */ private static String getHTML(final String markdownText) { final String hash = MD5.hash(markdownText); final JSONObject value = MD_CACHE.get(hash); if (null == value) { return null; } return value.optString(Common.DATA); } /** * Puts the specified HTML into cache. * * @param markdownText the specified markdown text * @param html the specified HTML */ private static void putHTML(final String markdownText, final String html) { final String hash = MD5.hash(markdownText); final JSONObject value = new JSONObject(); value.put(Common.DATA, html); MD_CACHE.put(hash, value); } }
package org.basex.gui.dialog; import static org.basex.core.Text.*; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.nio.charset.Charset; import java.util.SortedMap; import org.basex.core.Prop; import org.basex.gui.GUI; import org.basex.gui.SerializeProp; import org.basex.gui.GUIConstants.Msg; import org.basex.gui.layout.BaseXBack; import org.basex.gui.layout.BaseXButton; import org.basex.gui.layout.BaseXCheckBox; import org.basex.gui.layout.BaseXCombo; import org.basex.gui.layout.BaseXFileChooser; import org.basex.gui.layout.BaseXLabel; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.layout.BaseXTextField; import org.basex.gui.layout.TableLayout; import org.basex.io.IO; public final class DialogExport extends Dialog { /** Available encodings. */ private static String[] encodings; /** Directory path. */ private final BaseXTextField path; /** Directory/File flag. */ private final boolean file; /** Database info. */ private final BaseXLabel info; /** Output label. */ private final BaseXLabel out; /** XML Formatting. */ private final BaseXCheckBox format; /** Encoding. */ private final BaseXCombo encoding; /** Buttons. */ private final BaseXBack buttons; /** * Default constructor. * @param main reference to the main window */ public DialogExport(final GUI main) { super(main, GUIEXPORT); // create checkboxes final BaseXBack pp = new BaseXBack(); pp.setLayout(new TableLayout(3, 1, 0, 4)); BaseXBack p = new BaseXBack(); p.setLayout(new TableLayout(2, 2, 6, 0)); out = new BaseXLabel("", false, true); p.add(out); p.add(new BaseXLabel("")); file = gui.context.doc().length == 1; final IO io = gui.context.data.meta.file; final String fn = file ? io.path() : io.getDir(); path = new BaseXTextField(fn, this); path.addKeyListener(keys); p.add(path); final BaseXButton browse = new BaseXButton(BUTTONBROWSE, this); browse.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { choose(); } }); p.add(browse); pp.add(p); p = new BaseXBack(); p.setLayout(new TableLayout(2, 1)); p.add(new BaseXLabel(INFOENCODING + COL, false, true)); final Prop prop = gui.context.prop; final SerializeProp sprop = new SerializeProp(prop.get(Prop.SERIALIZER)); if(encodings == null) { final SortedMap<String, Charset> cs = Charset.availableCharsets(); encodings = cs.keySet().toArray(new String[cs.size()]); } encoding = new BaseXCombo(encodings, this); String enc = gui.context.data.meta.encoding; boolean f = false; for(final String s : encodings) f |= s.equals(enc); if(!f) { enc = enc.toUpperCase(); for(final String s : encodings) f |= s.equals(enc); } encoding.setSelectedItem(f ? enc : sprop.get(SerializeProp.ENCODING)); encoding.addKeyListener(keys); BaseXLayout.setWidth(encoding, BaseXTextField.DWIDTH); p.add(encoding); pp.add(p); format = new BaseXCheckBox(INDENT, sprop.is(SerializeProp.INDENT), 0, this); pp.add(format); set(pp, BorderLayout.CENTER); // create buttons p = new BaseXBack(); p.setLayout(new BorderLayout()); info = new BaseXLabel(" "); info.setBorder(18, 0, 0, 0); p.add(info, BorderLayout.WEST); buttons = okCancel(this); p.add(buttons, BorderLayout.EAST); set(p, BorderLayout.SOUTH); action(null); finish(null); } /** * Opens a file dialog to choose an XML document or directory. */ void choose() { final IO io = new BaseXFileChooser(DIALOGFC, path.getText(), gui).select( file ? BaseXFileChooser.Mode.FOPEN : BaseXFileChooser.Mode.DOPEN); if(io != null) path.setText(io.path()); } /** * Returns the chosen XML file or directory path. * @return file or directory */ public String path() { return path.getText().trim(); } /** * Indicates if the specified path is a file or directory. * @return result of check */ public boolean file() { return file; } @Override public void action(final Object cmp) { out.setText((file ? OUTFILE : OUTDIR) + COL); final IO io = IO.get(path()); final boolean empty = path().isEmpty(); final boolean exists = io.exists(); ok = !empty && (file && (!exists || !io.isDir()) || !file && (!exists || io.isDir())); info.setText(ok && file && exists ? OVERFILE : !ok && !empty ? INVPATH : null, ok ? Msg.WARN : Msg.ERR); enableOK(buttons, BUTTONOK, ok); } @Override public void close() { if(!ok) return; super.close(); gui.context.prop.set(Prop.SERIALIZER, "indent=" + (format.isSelected() ? SerializeProp.YES : SerializeProp.NO) + ",encoding=" + encoding.getSelectedItem() + ",omit-xml-declaration=no"); } }
package org.jcodec.containers.mps; import static org.jcodec.containers.mps.MPSUtils.readPESHeader; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.HashMap; import org.jcodec.codecs.mpeg12.MPEGUtil; import org.jcodec.codecs.mpeg12.bitstream.GOPHeader; import org.jcodec.codecs.mpeg12.bitstream.PictureHeader; import org.jcodec.common.FileChannelWrapper; import org.jcodec.common.NIOUtils; import org.jcodec.common.tools.MainUtils; import org.jcodec.common.tools.MainUtils.Cmd; import org.jcodec.containers.mps.MPSDemuxer.PESPacket; public class MPSDump { private static final String DUMP_FROM = "dump-from"; private static final String STOP_AT = "stop-at"; public static void main(String[] args) throws IOException { FileChannelWrapper ch = null; try { Cmd cmd = MainUtils.parseArguments(args); if (cmd.args.length < 1) { MainUtils.printHelp(new HashMap<String, String>() { { put(STOP_AT, "Stop reading at timestamp"); put(DUMP_FROM, "Start dumping from timestamp"); } }, "file name"); return; } ch = NIOUtils.readableFileChannel(new File(cmd.args[0])); Long dumpAfterPts = cmd.getLongFlag(DUMP_FROM); Long stopPts = cmd.getLongFlag(STOP_AT); MPEGVideoAnalyzer analyzer = null; PESPacket pkt = null; int hdrSize = 0; while (ch.position() + 4 < ch.size()) { ByteBuffer buffer = NIOUtils.fetchFrom(ch, 0x100000); while (true) { ByteBuffer payload = null; if (pkt != null && pkt.length > 0) { int pesLen = pkt.length - hdrSize + 6; if(pesLen <= buffer.remaining()) payload = NIOUtils.read(buffer, pesLen); } else { payload = getPesPayload(buffer); } if(payload == null) break; if (pkt != null) System.out.println(pkt.streamId + "(" + (pkt.streamId >= 0xe0 ? "video" : "audio") + ")" + " [" + pkt.pos + ", " + (payload.remaining() + hdrSize) + "], pts: " + pkt.pts + ", dts: " + pkt.dts); if (analyzer != null && pkt != null && pkt.streamId >= 0xe0 && pkt.streamId <= 0xef) { analyzer.analyzeMpegVideoPacket(payload); } if (buffer.remaining() < 32) break; skipToNextPES(buffer); if (buffer.remaining() < 32) break; hdrSize = buffer.position(); pkt = readPESHeader(buffer, ch.position() - buffer.remaining()); hdrSize = buffer.position() - hdrSize; if (dumpAfterPts != null && pkt.pts >= dumpAfterPts) analyzer = new MPEGVideoAnalyzer(); if (stopPts != null && pkt.pts >= stopPts) return; } ch.position(ch.position() - buffer.remaining()); } } finally { NIOUtils.closeQuietly(ch); } } private static void skipToNextPES(ByteBuffer buffer) { while (buffer.hasRemaining()) { int marker = buffer.duplicate().getInt(); if (marker >= 0x1bd && marker <= 0x1ff && marker != 0x1be) break; buffer.getInt(); MPEGUtil.gotoNextMarker(buffer); } } private static ByteBuffer getPesPayload(ByteBuffer buffer) { ByteBuffer copy = buffer.duplicate(); ByteBuffer result = buffer.duplicate(); while (copy.hasRemaining()) { int marker = copy.duplicate().getInt(); if (marker > 0x1af) { result.limit(copy.position()); buffer.position(copy.position()); return result; } copy.getInt(); MPEGUtil.gotoNextMarker(copy); } return null; } private static class MPEGVideoAnalyzer { private int nextStartCode = 0xffffffff; private ByteBuffer bselPayload = ByteBuffer.allocate(0x100000); private int bselStartCode; private int bselOffset; private int bselBufInd; private int prevBufSize; private int curBufInd; private void analyzeMpegVideoPacket(ByteBuffer buffer) { int pos = buffer.position(); int bufSize = buffer.remaining(); while (buffer.hasRemaining()) { bselPayload.put((byte) (nextStartCode >> 24)); nextStartCode = (nextStartCode << 8) | (buffer.get() & 0xff); if (nextStartCode >= 0x100 && nextStartCode <= 0x1b8) { bselPayload.flip(); bselPayload.getInt(); if(bselStartCode != 0) { if(bselBufInd != curBufInd) bselOffset -= prevBufSize; dumpBSEl(bselStartCode, bselOffset, bselPayload); } bselPayload.clear(); bselStartCode = nextStartCode; bselOffset = buffer.position() - 4 - pos; bselBufInd = curBufInd; } } ++curBufInd; prevBufSize = bufSize; } private static void dumpBSEl(int mark, int offset, ByteBuffer b) { System.out.print(String.format("marker: 0x%02x [@%d] ( ", mark, offset)); if (mark == 0x100) dumpPictureHeader(b); else if (mark <= 0x1af) System.out.print(MainUtils.color(String.format("slice @0x%02x", mark - 0x101), MainUtils.ANSIColor.BLACK, true)); else if (mark == 0x1b3) dumpSequenceHeader(); else if (mark == 0x1b5) dumpExtension(); else if (mark == 0x1b8) dumpGroupHeader(b); else System.out.print(" System.out.println(" )"); } private static void dumpExtension() { System.out.print(MainUtils.color("extension", MainUtils.ANSIColor.GREEN, true)); } private static void dumpGroupHeader(ByteBuffer b) { GOPHeader gopHeader = GOPHeader.read(b); System.out.print(MainUtils.color("group header" + " <closed:" + gopHeader.isClosedGop() + ",broken link:" + gopHeader.isBrokenLink() + (gopHeader.getTimeCode() != null ? (",timecode:" + gopHeader.getTimeCode().toString()) : "") + ">", MainUtils.ANSIColor.MAGENTA, true)); } private static void dumpSequenceHeader() { System.out.print(MainUtils.color("sequence header", MainUtils.ANSIColor.BLUE, true)); } private static void dumpPictureHeader(ByteBuffer b) { PictureHeader picHeader = PictureHeader.read(b); System.out.print(MainUtils.color("picture header" + " <type:" + (picHeader.picture_coding_type == 1 ? "I" : (picHeader.picture_coding_type == 2 ? "P" : "B")) + ">", MainUtils.ANSIColor.BROWN, true)); } } }
package org.owasp.esapi.codecs; public class MySQLCodec extends Codec { public static final int MYSQL_MODE = 0; public static final int ANSI_MODE = 1; private int mode = 0; /** * Instantiate the MySQL codec * * @param mode * Mode has to be one of {MYSQL_MODE|ANSI_MODE} to allow correct encoding */ public MySQLCodec( int mode ) { this.mode = mode; } /** * {@inheritDoc} * * Returns quote-encoded character * * @param immune */ public String encodeCharacter( char[] immune, Character c ) { char ch = c.charValue(); // check for immune characters if ( containsCharacter( ch, immune ) ) { return ""+ch; } // check for alphanumeric characters String hex = Codec.getHexForNonAlphanumeric( ch ); if ( hex == null ) { return ""+ch; } switch( mode ) { case ANSI_MODE: return encodeCharacterANSI( c ); case MYSQL_MODE: return encodeCharacterMySQL( c ); } return null; } /** * encodeCharacterANSI encodes for ANSI SQL. * * Only the apostrophe is encoded * * @param c * character to encode * @return * '' if ', otherwise return c directly */ private String encodeCharacterANSI( Character c ) { if ( c.charValue() == '\'' ) return "\'\'"; return ""+c; } /** * Encode a character suitable for MySQL * * @param c * Character to encode * @return * Encoded Character */ private String encodeCharacterMySQL( Character c ) { char ch = c.charValue(); if ( ch == 0x00 ) return "\\0"; if ( ch == 0x08 ) return "\\b"; if ( ch == 0x09 ) return "\\t"; if ( ch == 0x0a ) return "\\n"; if ( ch == 0x0d ) return "\\r"; if ( ch == 0x1a ) return "\\Z"; if ( ch == 0x22 ) return "\\\""; if ( ch == 0x25 ) return "\\%"; if ( ch == 0x27 ) return "\\'"; if ( ch == 0x5c ) return "\\\\"; if ( ch == 0x5f ) return "\\_"; return "\\" + c; } public Character decodeCharacter( PushbackString input ) { switch( mode ) { case ANSI_MODE: return decodeCharacterANSI( input ); case MYSQL_MODE: return decodeCharacterMySQL( input ); } return null; } /** * decodeCharacterANSI decodes the next character from ANSI SQL escaping * * @param input * A PushBackString containing characters you'd like decoded * @return * A single character, decoded */ private Character decodeCharacterANSI( PushbackString input ) { input.mark(); Character first = input.next(); if ( first == null ) { input.reset(); return null; } // if this is not an encoded character, return null if ( first.charValue() != '\'' ) { input.reset(); return null; } Character second = input.next(); if ( second == null ) { input.reset(); return null; } // if this is not an encoded character, return null if ( second.charValue() != '\'' ) { input.reset(); return null; } return( new Character( '\'' ) ); } /** * decodeCharacterMySQL decodes all the potential escaped characters that MySQL is prepared to escape * * @param input * A string you'd like to be decoded * @return * A single character from that string, decoded. */ private Character decodeCharacterMySQL( PushbackString input ) { input.mark(); Character first = input.next(); if ( first == null ) { input.reset(); return null; } // if this is not an encoded character, return null if ( first.charValue() != '\\' ) { input.reset(); return null; } Character second = input.next(); if ( second == null ) { input.reset(); return null; } if ( second.charValue() == '0' ) { return new Character( (char)0x00 ); } else if ( second.charValue() == 'b' ) { return new Character( (char)0x08 ); } else if ( second.charValue() == 't' ) { return new Character( (char)0x09 ); } else if ( second.charValue() == 'n' ) { return new Character( (char)0x0a ); } else if ( second.charValue() == 'r' ) { return new Character( (char)0x0d ); } else if ( second.charValue() == 'z' ) { return new Character( (char)0x1a ); } else if ( second.charValue() == '\"' ) { return new Character( (char)0x22 ); } else if ( second.charValue() == '%' ) { return new Character( (char)0x25 ); } else if ( second.charValue() == '\'' ) { return new Character( (char)0x27 ); } else if ( second.charValue() == '\\' ) { return new Character( (char)0x5c ); } else if ( second.charValue() == '_' ) { return new Character( (char)0x5f ); } else { return second; } } }