src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
Observer extends Node { void invariantDependenciesUnique( @Nonnull final String context ) { if ( Arez.shouldCheckInvariants() ) { invariant( () -> getDependencies().size() == new HashSet<>( getDependencies() ).size(), () -> "Arez-0089: " + context + ": The set of dependencies in observer named '" + getName() + "' is no...
@Test public void invariantDependenciesUnique() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = context.observable(); final Observer observer = context.observer( observable::reportObserved ); observer.invariantDependenciesUnique( "TEST1" ); observer.getDependencies().add( observ...
Observer extends Node { void invariantState() { if ( Arez.shouldCheckInvariants() ) { if ( isInactive() && !isDisposing() ) { invariant( () -> getDependencies().isEmpty(), () -> "Arez-0092: Observer named '" + getName() + "' is inactive but still has dependencies: " + getDependencies().stream().map( Node::getName ).col...
@Test public void invariantState() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = context.observable(); final Observer observer = context.observer( new CountingProcedure(), Observer.Flags.RUN_LATER ); observer.invariantState(); observer.getDependencies().add( observable ); asse...
Observer extends Node { void replaceDependencies( @Nonnull final List<ObservableValue<?>> dependencies ) { if ( Arez.shouldCheckInvariants() ) { invariantDependenciesUnique( "Pre replaceDependencies" ); } _dependencies = Objects.requireNonNull( dependencies ); if ( Arez.shouldCheckInvariants() ) { invariantDependencies...
@Test public void replaceDependencies() { final ArezContext context = Arez.context(); final ObservableValue<Object> observable = context.observable(); final Observer observer = context.observer( new CountingProcedure(), Observer.Flags.AREZ_OR_NO_DEPENDENCIES ); final List<ObservableValue<?>> originalDependencies = obse...
Observer extends Node { void clearDependencies() { getDependencies().forEach( dependency -> { dependency.removeObserver( this ); if ( !dependency.hasObservers() ) { dependency.setLeastStaleObserverState( Flags.STATE_UP_TO_DATE ); } } ); getDependencies().clear(); } Observer( @Nonnull final ComputableValue<?> computable...
@Test public void clearDependencies() { final ArezContext context = Arez.context(); final ObservableValue<?> observableValue1 = context.observable(); final ObservableValue<?> observableValue2 = context.observable(); final Observer observer = context.observer( () -> { observableValue1.reportObserved(); observableValue2....
Observer extends Node { void setState( final int state ) { setState( state, true ); } Observer( @Nonnull final ComputableValue<?> computableValue, final int flags ); Observer( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nu...
@Test public void setState() { final Observer observer = Arez.context().observer( new CountAndObserveProcedure() ); setupReadWriteTransaction(); observer.setState( Observer.Flags.STATE_INACTIVE ); assertEquals( observer.getState(), Observer.Flags.STATE_INACTIVE ); assertFalse( observer.getTask().isQueued() ); observer....
Observer extends Node { void scheduleReaction() { if ( isNotDisposed() ) { if ( Arez.shouldCheckInvariants() ) { invariant( this::isActive, () -> "Arez-0088: Observer named '" + getName() + "' is not active but an attempt has been made " + "to schedule observer." ); } if ( !getTask().isQueued() ) { getContext().schedul...
@Test public void scheduleReaction() { final Observer observer = Arez.context().observer( new CountAndObserveProcedure() ); setupReadWriteTransaction(); observer.setState( Observer.Flags.STATE_UP_TO_DATE ); assertFalse( observer.getTask().isQueued() ); observer.scheduleReaction(); final ArezContext context = Arez.conte...
Observer extends Node { @Override public void dispose() { if ( isNotDisposedOrDisposing() ) { getContext().safeAction( Arez.areNamesEnabled() ? getName() + ".dispose" : null, this::performDispose, ActionFlags.NO_VERIFY_ACTION_REQUIRED ); if ( !isComputableValue() ) { if ( willPropagateSpyEvents() ) { reportSpyEvent( ne...
@Test public void dispose() { final Observer observer = Arez.context().observer( new CountAndObserveProcedure() ); setCurrentTransaction( observer ); observer.setState( Observer.Flags.STATE_UP_TO_DATE ); Transaction.setTransaction( null ); assertEquals( observer.getState(), Observer.Flags.STATE_UP_TO_DATE ); assertTrue...
Observer extends Node { void markDependenciesLeastStaleObserverAsUpToDate() { for ( final ObservableValue<?> dependency : getDependencies() ) { dependency.setLeastStaleObserverState( Flags.STATE_UP_TO_DATE ); } } Observer( @Nonnull final ComputableValue<?> computableValue, final int flags ); Observer( @Nullable final...
@Test public void markDependenciesLeastStaleObserverAsUpToDate() { final Observer observer = Arez.context().observer( new CountAndObserveProcedure() ); final ObservableValue<?> observableValue1 = Arez.context().observable(); final ObservableValue<?> observableValue2 = Arez.context().observable(); final ObservableValue<...
Observer extends Node { void invokeReaction() { if ( isNotDisposed() ) { final long start; if ( willPropagateSpyEvents() ) { start = System.currentTimeMillis(); if ( isComputableValue() ) { reportSpyEvent( new ComputeStartEvent( getComputableValue().asInfo() ) ); } else { reportSpyEvent( new ObserveStartEvent( asInfo()...
@Test public void invokeReaction() { ignoreObserverErrors(); final ArezContext context = Arez.context(); final AtomicInteger errorCount = new AtomicInteger(); context.addObserverErrorHandler( ( observer, error, throwable ) -> errorCount.incrementAndGet() ); final CountAndObserveProcedure observed = new CountAndObserveP...
Observer extends Node { Observer( @Nonnull final ComputableValue<?> computableValue, final int flags ) { this( Arez.areZonesEnabled() ? computableValue.getContext() : null, null, Arez.areNamesEnabled() ? computableValue.getName() : null, computableValue, computableValue::compute, null, flags | ( Flags.KEEPALIVE == Flag...
@Test public void invokeReaction_reactionGeneratesError() { ignoreObserverErrors(); final AtomicInteger errorCount = new AtomicInteger(); final RuntimeException exception = new RuntimeException( "X" ); final ArezContext context = Arez.context(); context.addObserverErrorHandler( ( observer, error, throwable ) -> { error...
Observer extends Node { @SuppressWarnings( "ConstantConditions" ) @OmitSymbol( unless = "arez.enable_spies" ) @Nonnull ObserverInfo asInfo() { if ( Arez.shouldCheckInvariants() ) { invariant( Arez::areSpiesEnabled, () -> "Arez-0197: Observer.asInfo() invoked but Arez.areSpiesEnabled() returned false." ); } if ( Arez.ar...
@Test public void asInfo() { final Observer observer = Arez.context().tracker( ValueUtil::randomString ); final ObserverInfo info = observer.asInfo(); assertEquals( info.getName(), observer.getName() ); }
Observer extends Node { public void reportStale() { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( this::areExternalDependenciesAllowed, () -> "Arez-0199: Observer.reportStale() invoked on observer named '" + getName() + "' but the observer has not specified AREZ_OR_EXTERNAL_DEPENDENCIES flag." ); apiInvariant(...
@Test public void reportStale() { final ArezContext context = Arez.context(); final Observer observer = new Observer( context, null, ValueUtil.randomString(), new CountingProcedure(), new CountingProcedure(), Observer.Flags.AREZ_OR_EXTERNAL_DEPENDENCIES ); context.triggerScheduler(); assertEquals( observer.getState(), ...
ObserverInfoImpl implements ObserverInfo { @Override public boolean isScheduled() { return _observer.getTask().isQueued(); } ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ); @Nonnull @Override String getName(); @Override boolean isActive(); @Override boolean isRunning(); @Override boolean i...
@Test public void isScheduled() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final Observer observer = context.observer( new CountAndObserveProcedure() ); final ObserverInfo info = spy.asObserverInfo( observer ); assertFalse( info.isScheduled() ); observer.getTask().markAsQueued(); as...
Observer extends Node { public void schedule() { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( this::supportsManualSchedule, () -> "Arez-0202: Observer.schedule() invoked on observer named '" + getName() + "' but supportsManualSchedule() returns false." ); } if ( Arez.shouldEnforceTransactionType() && getConte...
@Test public void schedule() { final ArezContext context = Arez.context(); final CountAndObserveProcedure observed = new CountAndObserveProcedure(); final CountingProcedure onDepsChange = new CountingProcedure(); final Observer observer = new Observer( context, null, ValueUtil.randomString(), observed, onDepsChange, Ob...
Observer extends Node { boolean isActive() { return Flags.isActive( _flags ); } Observer( @Nonnull final ComputableValue<?> computableValue, final int flags ); Observer( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable...
@Test public void Flags_isActive() { assertFalse( Observer.Flags.isActive( Observer.Flags.STATE_DISPOSED ) ); assertFalse( Observer.Flags.isActive( Observer.Flags.STATE_DISPOSING ) ); assertFalse( Observer.Flags.isActive( Observer.Flags.STATE_INACTIVE ) ); assertTrue( Observer.Flags.isActive( Observer.Flags.STATE_UP_TO...
Observer extends Node { int getState() { return Flags.getState( _flags ); } Observer( @Nonnull final ComputableValue<?> computableValue, final int flags ); Observer( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final String name, @Nullable fin...
@Test public void Flags_getState() { assertEquals( Observer.Flags.getState( Observer.Flags.PRIORITY_NORMAL | Observer.Flags.STATE_DISPOSED ), Observer.Flags.STATE_DISPOSED ); assertEquals( Observer.Flags.getState( Observer.Flags.PRIORITY_NORMAL | Observer.Flags.STATE_DISPOSING ), Observer.Flags.STATE_DISPOSING ); asser...
Observer extends Node { int getLeastStaleObserverState() { return Flags.getLeastStaleObserverState( _flags ); } Observer( @Nonnull final ComputableValue<?> computableValue, final int flags ); Observer( @Nullable final ArezContext context, @Nullable final Component component, @Nullable final St...
@Test public void Flags_getLeastStaleObserverState() { assertEquals( Observer.Flags.getLeastStaleObserverState( Observer.Flags.PRIORITY_NORMAL | Observer.Flags.STATE_DISPOSED ), Observer.Flags.STATE_UP_TO_DATE ); assertEquals( Observer.Flags.getLeastStaleObserverState( Observer.Flags.PRIORITY_NORMAL | Observer.Flags.ST...
ArezLogger { static void log( @Nonnull final String message, @Nullable final Throwable throwable ) { c_logger.log( message, throwable ); } private ArezLogger(); }
@Test public void log() { final String message1 = ValueUtil.randomString(); final String message2 = ValueUtil.randomString(); ArezLogger.log( message1, null ); final Throwable throwable = new Throwable(); ArezLogger.log( message2, throwable ); final List<TestLogger.LogEntry> entries = getTestLogger().getEntries(); asse...
NoSuchEntityException extends NoResultException { @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "NoSuchEntityException[id=" + _id + ']'; } else { return super.toString(); } } NoSuchEntityException( @Nonnull final Object id ); @Nonnull Object getId(); @Override String toString(); }
@Test public void toString_NamesDisabled() { ArezTestUtil.disableNames(); final NoSuchEntityException exception = new NoSuchEntityException( 23 ); assertEquals( exception.toString(), "arez.component.NoSuchEntityException" ); }
TypeBasedLocator implements Locator { public <T> void registerLookup( @Nonnull final Class<T> type, @Nonnull final Function<Object, T> findByIdFunction ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> !_findByIdFunctions.containsKey( type ), () -> "Arez-0188: Attempting to register lookup function for t...
@Test public void registerLookup_duplicate() { final TypeBasedLocator locator = new TypeBasedLocator(); locator.registerLookup( A.class, i -> new A() ); assertInvariantFailure( () -> locator.registerLookup( A.class, i -> new A() ), "Arez-0188: Attempting to register lookup function for type class arez.component.TypeBas...
CollectionsUtil { @Nonnull public static <T> Collection<T> wrap( @Nonnull final Collection<T> collection ) { return Arez.areCollectionsPropertiesUnmodifiable() ? Collections.unmodifiableCollection( collection ) : collection; } private CollectionsUtil(); @Nonnull static Collection<T> wrap( @Nonnull final Collection<T> ...
@Test public void wrap_when_areRepositoryResultsModifiable_isTrue() { final ArrayList<MyEntity> input = new ArrayList<>(); final MyEntity entity = new MyEntity(); input.add( entity ); final List<MyEntity> output = CollectionsUtil.wrap( input ); assertNotSame( output, input ); assertUnmodifiable( output, MyEntity::new )...
ObserverInfoImpl implements ObserverInfo { @Override public boolean isRunning() { return _spy.isTransactionActive() && null != getTrackerTransaction(); } ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ); @Nonnull @Override String getName(); @Override boolean isActive(); @Override boolean isR...
@Test public void isRunning() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); final AtomicReference<ObserverInfo> ref = new AtomicReference<>(); final Observer observer = context.observer( () -> { assertTrue( ref.get().isRunning() ); callCount.incrementAndGet(); observ...
CollectionsUtil { @Nonnull public static <T> List<T> asList( @Nonnull final Stream<T> stream ) { return wrap( stream.collect( Collectors.toList() ) ); } private CollectionsUtil(); @Nonnull static Collection<T> wrap( @Nonnull final Collection<T> collection ); @Nonnull static Set<T> wrap( @Nonnull final Set<T> set ); @N...
@Test public void asList() { final ArrayList<MyEntity> input = new ArrayList<>(); final MyEntity entity = new MyEntity(); input.add( entity ); final List<MyEntity> output = CollectionsUtil.asList( input.stream() ); assertUnmodifiable( output, MyEntity::new ); assertEquals( output.size(), 1 ); assertEquals( output.get( ...
MemoizeCache implements Disposable { @SuppressWarnings( "unchecked" ) void disposeComputableValue( @Nonnull final Object... args ) { if ( Arez.shouldCheckInvariants() ) { invariant( () -> args.length == _argCount, () -> "Arez-0163: MemoizeCache.disposeComputableValue called with " + args.length + " argument(s) but expe...
@Test public void disposeComputableValue_passedBadArgCounts() { final MemoizeCache<String> cache = new MemoizeCache<>( null, null, ValueUtil.randomString(), args -> args[ 0 ] + "." + args[ 1 ], 2 ); assertInvariantFailure( () -> cache.disposeComputableValue( "a" ), "Arez-0163: MemoizeCache.disposeComputableValue called...
MemoizeCache implements Disposable { public T get( @Nonnull final Object... args ) { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( this::isNotDisposed, () -> "Arez-0161: MemoizeCache named '" + _name + "' had get() invoked when disposed." ); } return getComputableValue( args ).get(); } MemoizeCache( @Nullable ...
@Test public void get_passedBadArgCounts() { final MemoizeCache<String> cache = new MemoizeCache<>( null, null, ValueUtil.randomString(), args -> args[ 0 ] + "." + args[ 1 ], 2 ); assertInvariantFailure( () -> cache.get( "a" ), "Arez-0162: MemoizeCache.getComputableValue called with 1 arguments but expected 2 arguments...
ComponentKernel implements Disposable, ComponentObservable { @Override public boolean observe() { if ( Arez.shouldCheckApiInvariants() ) { apiInvariant( () -> null != _disposeOnDeactivate || null != _componentObservable, () -> "Arez-0221: ComponentKernel.observe() invoked on component named '" + getName() + "' but obse...
@Test public void observe() { ArezTestUtil.disableNativeComponents(); final ArezContext context = Arez.context(); final String name = ValueUtil.randomString(); final ComponentKernel kernel = new ComponentKernel( context, name, 0, null, null, null, null, false, true, false ); kernel.componentConstructed(); kernel.compon...
ComponentKernel implements Disposable, ComponentObservable { public void addOnDisposeListener( @Nonnull final Object key, @Nonnull final SafeProcedure action ) { assert null != _onDisposeListeners; if ( Arez.shouldCheckApiInvariants() ) { invariant( this::isNotDisposed, () -> "Arez-0170: Attempting to add OnDispose lis...
@Test public void addOnDisposeListener() { final ArezContext context = Arez.context(); final ComponentKernel kernel = new ComponentKernel( context, "MyType", 1, context.component( "MyType", 1 ), null, null, null, true, false, false ); final String key = ValueUtil.randomString(); final AtomicInteger callCount = new Atom...
ObserverInfoImpl implements ObserverInfo { @Override public boolean isReadOnly() { return Arez.shouldEnforceTransactionType() && !_observer.isMutation(); } ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ); @Nonnull @Override String getName(); @Override boolean isActive(); @Override boolean i...
@Test public void isReadOnly_on_READ_WRITE_observer() { final ArezContext context = Arez.context(); final ObservableValue<Object> observableValue = context.observable(); final Observer observer = context.observer( observableValue::reportObserved, Observer.Flags.READ_WRITE ); assertFalse( observer.asInfo().isReadOnly() ...
ComponentKernel implements Disposable, ComponentObservable { public void removeOnDisposeListener( @Nonnull final Object key ) { assert null != _onDisposeListeners; final SafeProcedure removed = _onDisposeListeners.remove( key ); if ( Arez.shouldCheckApiInvariants() ) { invariant( () -> null != removed, () -> "Arez-0167...
@Test public void removeOnDisposeListener() { final ArezContext context = Arez.context(); final ComponentKernel kernel = new ComponentKernel( context, "MyType", 1, context.component( "MyType", 1 ), null, null, null, true, false, false ); final String key = ValueUtil.randomString(); final AtomicInteger callCount = new A...
ComponentKernel implements Disposable, ComponentObservable { @Override public void dispose() { if ( isNotDisposed() ) { _state = COMPONENT_DISPOSING; if ( Arez.areNativeComponentsEnabled() ) { assert null != _component; _component.dispose(); } else { getContext().safeAction( Arez.areNamesEnabled() ? getName() + ".dispo...
@Test public void dispose() { final ArezContext context = Arez.context(); final AtomicReference<ComponentKernel> ref = new AtomicReference<>(); final ComponentKernel kernel = new ComponentKernel( context, "MyType", 1, context.component( "MyType", 1, "MyType@1", () -> ref.get().notifyOnDisposeListeners() ), null, null, ...
ArezContext { @Nonnull Zone getZone() { assert null != _zone; return _zone; } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull final Object id ); @OmitSymbol( unless = "arez.enable_native_components" ) @Non...
@Test public void zoneEnabledConstruction() { ArezTestUtil.enableZones(); final ArezContext context = Arez.context(); final Zone defaultZone = Arez.currentZone(); assertEquals( context.getZone(), defaultZone ); final Zone zone = Arez.createZone(); zone.safeRun( () -> { assertNotEquals( Arez.context().getZone(), default...
ArezContext { @Nullable String generateName( @Nonnull final String prefix, @Nullable final String name ) { return Arez.areNamesEnabled() ? null != name ? name : prefix + "@" + _nextNodeId++ : null; } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPre...
@Test public void generateName() { final ArezContext context = Arez.context(); assertEquals( context.generateName( "ComputableValue", "MyName" ), "MyName" ); context.setNextNodeId( 1 ); assertEquals( context.generateName( "ComputableValue", null ), "ComputableValue@1" ); assertEquals( context.getNextNodeId(), 2 ); Arez...
ArezContext { public void triggerScheduler() { if ( isSchedulerEnabled() && !isSchedulerPaused() ) { if ( !_schedulerActive ) { _schedulerActive = true; try { if ( Arez.isTaskInterceptorEnabled() && null != _taskInterceptor ) { assert null != _taskExecuteAction; do { _taskInterceptor.executeTasks( _taskExecuteAction );...
@Test public void triggerScheduler() { final ArezContext context = Arez.context(); final AtomicInteger callCount = new AtomicInteger(); context.observer( () -> { observeADependency(); callCount.incrementAndGet(); }, Observer.Flags.RUN_LATER ); assertEquals( callCount.get(), 0 ); context.triggerScheduler(); assertEquals...
ArezContext { public boolean isReadOnlyTransactionActive() { return Transaction.isTransactionActive( this ) && ( !Arez.shouldEnforceTransactionType() || !Transaction.current().isMutation() ); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( ...
@Test public void isReadOnlyTransactionActive() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); context.action( () -> { assertTrue( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransacti...
ArezContext { public boolean isTrackingTransactionActive() { return Transaction.isTransactionActive( this ) && null != Transaction.current().getTracker(); } ArezContext( @Nullable final Zone zone ); @OmitSymbol( unless = "arez.enable_native_components" ) boolean isComponentPresent( @Nonnull final String type, @Nonnull ...
@Test public void isTrackingTransactionActive() throws Throwable { final ArezContext context = Arez.context(); assertFalse( context.isTransactionActive() ); assertFalse( context.isReadOnlyTransactionActive() ); assertFalse( context.isReadWriteTransactionActive() ); assertFalse( context.isTrackingTransactionActive() ); ...
ArezContext { private void verifyActionFlags( @Nullable final String name, @MagicConstant( flagsFromClass = ActionFlags.class ) final int flags ) { if ( Arez.shouldCheckApiInvariants() ) { final int nonActionFlags = flags & ~ActionFlags.CONFIG_FLAGS_MASK; apiInvariant( () -> 0 == nonActionFlags, () -> "Arez-0212: Flags...
@SuppressWarnings( "MagicConstant" ) @Test public void verifyActionFlags() { final Procedure executable = () -> { }; assertInvariantFailure( () -> Arez.context().action( executable, Observer.Flags.DEACTIVATE_ON_UNOBSERVE ), "Arez-0212: Flags passed to action 'Action@1' include some " + "unexpected flags set: " + Observ...
ObserverInfoImpl implements ObserverInfo { @Nonnull @Override public List<ObservableValueInfo> getDependencies() { final Transaction transaction = _spy.isTransactionActive() ? getTrackerTransaction() : null; if ( null != transaction ) { final List<ObservableValue<?>> observableValues = transaction.getObservableValues()...
@Test public void getDependencies() { final ArezContext context = Arez.context(); final Spy spy = context.getSpy(); final ObservableValue<Object> observable = context.observable(); final Observer observer = context.observer( observable::reportObserved ); final List<ObservableValueInfo> dependencies = spy.asObserverInfo...
JMoveWriter implements RefactoringsWriter { @Override public void writeRefactoringsInTextForm(List<RefactoringTextRepresentation> refactorings, Path refactoringsPath) throws IOException { Files.write(refactoringsPath, getRefactoringsInJMoveFormat(refactorings)); } @Override String getName(); @Override void write(List<...
@Test public void writeToFile() throws IOException { Path fileToWrite = Files.createTempFile(null, null); fileToWrite.toFile().deleteOnExit(); RefactoringsWriters.getJMoveWriter().writeRefactoringsInTextForm(REFACTORINGS_TO_WRITE, fileToWrite); checkWrittenRefactorings(fileToWrite.toFile()); } @Test public void writeTo...
InputSessionValidator { public void validate(Iterable<String> input) { List<EventLine> errorSession = new ArrayList<>(); List<EventLine> validSession = new ArrayList<>(); for (String line : input) { if (line.trim().isEmpty()) continue; String[] fields = line.split("\t", -1); if (!isFormattedCorrectly(fields)) { errorSe...
@Test public void testCorrect2() throws IOException { List<String> entries = loadLogs(LOGS_PATH + "correctTest2.txt"); validator.validate(entries); assertEquals(1, result.validLines().size()); assertEquals(0, result.errorLines().size()); } @Test public void testCorrect3() throws IOException { List<String> entries = loa...
JBWriter implements RefactoringsWriter { @Override public void writeRefactoringsInTextForm(List<RefactoringTextRepresentation> refactorings, Path refactoringsPath) throws IOException { Files.write(refactoringsPath, Collections.singleton(JSON_CONVERTER.toJson(refactorings))); } @Override void write(List<MoveMethodRefac...
@Test public void writeToFile() throws IOException { Path fileToWrite = Files.createTempFile(null, null); fileToWrite.toFile().deleteOnExit(); RefactoringsWriters.getJBWriter().writeRefactoringsInTextForm(REFACTORINGS_TO_WRITE, fileToWrite); checkWrittenRefactorings(fileToWrite.toFile()); } @Test public void writeToOut...
JBReader implements RefactoringsReader { @Override public List<RefactoringTextRepresentation> read(Path refactoringsPath) throws IOException { try (BufferedReader reader = Files.newBufferedReader(refactoringsPath)) { Type listType = new TypeToken<List<JBRefactoringTextRepresentation>>(){}.getType(); return JSON_CONVERT...
@Test public void readFromFile() throws IOException { checkReadRefactorings(RefactoringsReaders.getJBReader().read(REFACTORINGS_PATH)); } @Test public void readFromInputStream() throws IOException { checkReadRefactorings(RefactoringsReaders.getJBReader().read(new FileInputStream(REFACTORINGS_PATH.toFile()))); }
JMoveReader implements RefactoringsReader { @Override public List<RefactoringTextRepresentation> read(Path refactoringsPath) throws IOException { return parseLines(Files.lines(refactoringsPath)); } @Override List<RefactoringTextRepresentation> read(Path refactoringsPath); @Override List<RefactoringTextRepresentation> ...
@Test public void readFromFile() throws IOException { checkReadRefactorings(RefactoringsReaders.getJMoveReader().read(REFACTORINGS_PATH)); } @Test public void readFromInputStream() throws IOException { checkReadRefactorings(RefactoringsReaders.getJMoveReader().read(new FileInputStream(REFACTORINGS_PATH.toFile()))); }
CombinedEvaluationResult extends AbstractEvaluationResult { void addResult(EvaluationResult evaluationResult) { if (!getAlgorithm().equals(evaluationResult.getAlgorithm())) { throw new IllegalArgumentException("Tried to add evaluation result with different algorithm"); } numberOfGood += evaluationResult.getNumberOfGood...
@Test public void addResult() { CombinedEvaluationResult combinedEvaluationResult = new CombinedEvaluationResult(TEST_ALGORITHM); assertEquals(0, combinedEvaluationResult.getNumberOfGood()); assertEquals(0, combinedEvaluationResult.getNumberOfFoundGood()); assertEquals(0, combinedEvaluationResult.getNumberOfBad()); ass...
ManifestUtils { @SuppressWarnings("unchecked") public static String createManifest(Package packageToDeploy, Map<String, ?> model) { Map<String, Object> newModel = new HashMap<>(); backslashEscapeMap((Map<String, Object>) model, newModel); String rawManifest = applyManifestTemplate(packageToDeploy, newModel); Yaml yaml ...
@Test public void testCreateManifest() throws IOException { Resource resource = new ClassPathResource("/repositories/sources/test/ticktock/ticktock-1.0.1"); PackageReader packageReader = new DefaultPackageReader(); Package pkg = packageReader.read(resource.getFile()); assertThat(pkg).isNotNull(); Date date = new Date(6...
RepositoryInitializationService { @EventListener @Transactional public void initialize(ApplicationReadyEvent event) { synchronizeRepositories(); synchronizePackageMetadata(); } RepositoryInitializationService(RepositoryRepository repositoryRepository, PackageMetadataRepository packageMetadataRepository, PackageMe...
@Test public void initialize() throws Exception { assertThat(repositoryRepository.count()).isEqualTo(2); assertThat(repositoryRepository.findByName("test").getUrl()).isEqualTo("classpath:/repositories/binaries/test"); assertThat(packageMetadataRepository.count()).isGreaterThan(5); }
DefaultClientHeadersFactoryImpl implements ClientHeadersFactory { @Override public MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders, MultivaluedMap<String, String> clientOutgoingHeaders) { if (LOG.isLoggable(Level.FINER)) { LOG.entering(CLASS_NAME, "update", new Object[]{incomingHead...
@Test public void testUpdateWithNoConfigReturnsEmptyMap() { MultivaluedMap<String, String> incomingHeaders = mockIncomingHeaders(); MultivaluedMap<String, String> clientOutgoingHeaders = new MultivaluedHashMap<>(); MultivaluedMap<String, String> updatedHeaders = impl.update(incomingHeaders, clientOutgoingHeaders); asse...
DocumentKeyWords { public static DocumentKeyWord[] getAll(){ return ALL_KEYWORDS; } static DocumentKeyWord[] getAll(); }
@Test public void all_key_words_can_be_initialzed() { DocumentKeyWord[] results = DocumentKeyWords.getAll(); assertNotNull(results); }
ParseToken { public boolean isFunctionKeyword() { return "function".equals(text); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingleSt...
@Test public void function_is_functionKeyword() { assertTrue(new ParseToken("function").isFunctionKeyword()); } @Test public void functions_is_NOT_functionKeyword() { assertFalse(new ParseToken("functions").isFunctionKeyword()); }
ParseToken { public boolean isFunction() { boolean isFunctionName = endsWithFunctionBrackets(); isFunctionName = isFunctionName && isLegalFunctionName(); isFunctionName = isFunctionName && !isComment(); isFunctionName = isFunctionName && text.length() > 2; isFunctionName = isFunctionName && !isString(); return isFuncti...
@Test public void function_is_NOT_functionName() { assertFalse(new ParseToken("function").isFunction()); } @Test public void xyz_is_NOT_functionName() { assertFalse(new ParseToken("xyz").isFunction()); } @Test public void xyz_followed_by_open_and_close_bracket_is_functionName() { assertTrue(new ParseToken("xyz()").isFu...
ParseToken { public String getTextAsFunctionName() { if (getSafeText().endsWith("()")) { return text.substring(0, text.length() - 2); } return text; } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); Stri...
@Test public void xyz_getTextAsFunctionName_returns_xyz() { assertEquals("xyz", new ParseToken("xyz").getTextAsFunctionName()); } @Test public void xyz_open_close_bracketgetTextAsFunctionName_returns_xyz() { assertEquals("xyz", new ParseToken("xyz()").getTextAsFunctionName()); }
TokenParser { public List<ParseToken> parse(String bashScript) throws TokenParserException { if (bashScript == null) { return new ArrayList<>(); } ParseContext context = new ParseContext(); context.chars = bashScript.toCharArray(); try { for (; context.hasValidPos(); context.moveForward()) { if (isIfHandled(context)) {...
@Test public void $1_has_start_0_end_2() throws Exception { String string = "$1"; List<ParseToken> tokens = parserToTest.parse(string); ParseToken token = assertThat(tokens).resolveToken("$1"); assertEquals(0, token.getStart()); assertEquals(2, token.getEnd()); } @Test public void bugfix_39__a_variable_containing_hash_...
DebugBashCodeToggleSupport { public String disableDebugging(String sourceCode) throws IOException { int index = sourceCode.indexOf(DEBUG_POSTFIX); if (index == -1) { return sourceCode; } int pos = index + DEBUG_POSTFIX.length(); String data = sourceCode.substring(pos); if (data.startsWith("\n")) { data=data.substring(1...
@Test public void disable_debugging_first_line_has_include_and_comment_secondline_has_alpha_after_include_only_comment_remains_in_first_line_second_has_alpha() throws Exception { assertEquals("#! /bin/mybash\nalpha", supportToTest.disableDebugging(EXPECTED_DEBUG_ENABLED_CODE + "#! /bin/mybash\nalpha")); } @Test public ...
TokenParser { void moveUntilNextCharWillBeNoStringContent(ParseContext context) { context.appendCharToText(); char c = context.getCharAtPos(); if (!isStringChar(c)) { return; } if (c=='\'') { }else if (context.isCharBeforeEscapeSign()) { return; } char stringCharToScan = c; moveToNextCharNotInStringAndAppendMovements(c...
@Test public void moveUntilNextCharWillBeNoStringContent_no_string_contend_handled_as_expected() throws Exception { ParseContext context = new ParseContext(); context.chars = "$(tput 'STRING')".toCharArray(); context.pos = 2; parserToTest.moveUntilNextCharWillBeNoStringContent(context); context.moveForward(); parserToT...
BashPIDSnippetSupport { public String buildKillOldTerminalsSnippet() { String code= "cd ~/.basheditor\n" + "KILL_TEXTFILE=\"./PID_debug-terminal_port_$1.txt\"\n" + "if [ -f \"$KILL_TEXTFILE\" ]; then\n" + " while IFS='' read -r LINE || [ -n \"${LINE}\" ]; do\n" + " kill -9 ${LINE}\n" + " done < $KILL_TEXTFILE;\n" + " \...
@Test public void buildKillPIDSnippet() throws IOException { String expectedSnippet= "cd ~/.basheditor\n" + "KILL_TEXTFILE=\"./PID_debug-terminal_port_$1.txt\"\n" + "if [ -f \"$KILL_TEXTFILE\" ]; then\n" + " while IFS='' read -r LINE || [ -n \"${LINE}\" ]; do\n" + " kill -9 ${LINE}\n" + " done < $KILL_TEXTFILE;\n" + " ...
BashCallPIDStoreSnippetBuilder { public String buildPIDFileAbsolutePath(String port) { String path = buildPIDFile(port).toPath().toAbsolutePath().toString(); return path; } BashCallPIDStoreSnippetBuilder(); String buildPIDFileAbsolutePath(String port); String buildPIDParentFolderAbsolutePath(); String buildWritePIDToPo...
@Test public void buildPIDForPortPort1234_returns_path_as_tempfolder_debugger_terminal_pid4port_1234_$username$_txt() throws IOException { assertEquals(tmpFolder+"/.basheditor/PID_debug-terminal_port_12345.txt", OSUtil.toUnixPath(builderToTest.buildPIDFileAbsolutePath("12345"))); }
SimpleWordListBuilder implements WordListBuilder { @Override public List<String> build(String source) { if (source == null || source.isEmpty()) { return Collections.emptyList(); } String[] allWords = source.split("[\\s,;:.!()\\?=]"); List<String> list = new ArrayList<>(); for (String word: allWords){ String transformed...
@Test public void a_colon_b_results_in_a_b() { assertEquals(expect("a","b").listExpected, builderToTest.build("a:b")); } @Test public void comment_results_in_empty_result() { assertEquals(expect().listExpected, builderToTest.build("#")); } @Test public void comment_alpha_is_reduced_to_alpha() { assertEquals(expect("alp...
BashCallPIDStoreSnippetBuilder { public String buildWritePIDToPortSpecificTmpFileSnippet(int port) { StringBuilder sb = new StringBuilder(); sb.append("cd \"").append(OSUtil.toUnixPath(buildPIDParentFolderAbsolutePath())).append("\";"); sb.append("./").append(BashPIDSnippetSupport.FILENAME_STORE_TERMINAL_PIDS_SCRIPT); ...
@Test public void buildWritePIDToPortSpecificTmpFileSnippet_generateds_expected_parts() throws IOException { assertEquals("cd \""+tmpFolder+"/.basheditor\";./"+BashPIDSnippetSupport.FILENAME_STORE_TERMINAL_PIDS_SCRIPT+" 12345 $$;", builderToTest.buildWritePIDToPortSpecificTmpFileSnippet(12345)); }
DefaultWindowsTerminalCommandStringProvider implements DefaultTerminalCommandStringProvider { @Override public String getStarterCommandString() { return "cmd.exe /C "+TerminalCommandVariable.BE_TERMINAL.getVariableRepresentation(); } @Override String getStarterCommandString(); @Override String getTerminalCommandString...
@Test public void startCommandAsExpected() { assertEquals("cmd.exe /C ${BE_TERMINAL}", providerToTest.getStarterCommandString()); }
LineIsBashSheBangValidator { public boolean isValid(String line) { if (line == null) { return false; } if (line.isEmpty()) { return false; } if (!line.startsWith("#!")) { return false; } if (line.indexOf("bash") != -1 ) { return true; } if (line.endsWith(" sh")) { return true; } return false; } boolean isValid(String ...
@Test public void shebang_slash_bin_slash_bash_is_valid() { assertTrue(validatorToTest.isValid("#!/bin/bash")); } @Test public void shebang_slash_user_slash_bin_slash_bash_is_valid() { assertTrue(validatorToTest.isValid("#!/usr/bin/bash")); } @Test public void shebang_usr_bin_slash_env_space_bash_is_valid() { assertTru...
DefaultWindowsTerminalCommandStringProvider implements DefaultTerminalCommandStringProvider { @Override public String getTerminalCommandString() { return "start \""+TerminalCommandVariable.BE_CMD_TITLE.getVariableRepresentation()+"\" cmd.exe /C bash --login -c '"+TerminalCommandVariable.BE_CMD_CALL.getVariableRepresent...
@Test public void startTerminalCommandAsExpected() { assertEquals("start \"${BE_CMD_TITLE}\" cmd.exe /C bash --login -c '${BE_CMD_CALL}'", providerToTest.getTerminalCommandString()); }
FileExtensionExtractor { public String extractFileExtension(File file) { Objects.requireNonNull(file); String fileName = file.getName(); int index = fileName.lastIndexOf('.'); if (index==-1) { return null; } if (fileName.length()==index-1) { return null; } return fileName.substring(index); } String extractFileExtensio...
@Test public void test() { assertEquals(".txt",extractorToTest.extractFileExtension(new File("/tmp/file1.txt"))); assertEquals(".",extractorToTest.extractFileExtension(new File("/tmp/file1."))); assertEquals(null,extractorToTest.extractFileExtension(new File("/tmp/file1"))); assertEquals(".bash",extractorToTest.extract...
ExternalToolCommandArrayBuilder { public String[] build(String externalToolCall, File editorFile) { numKeywordsReplaced = 0; String[] ret = externalToolCall.split(" "); for (int i = 0; i < ret.length; i++) if (ret[i].equalsIgnoreCase("$filename")) { ret[i] = editorFile.toPath().toString(); numKeywordsReplaced++; } retu...
@Test public void anExistingFile_commands_are_as_expected_and_parameter_replaced() { File editorFile = TestScriptLoader.getTestScriptFile("strings.sh"); String[] result = actionToTest.build("beautysh.py $filename", editorFile); assertEquals(2, result.length); assertEquals("beautysh.py",result[0]); if (OSUtil.isWindows(...
SimpleWordCodeCompletion { public Set<String> calculate(String source, int offset) { rebuildCacheIfNecessary(source); if (offset == 0) { return unmodifiableSet(allWordsCache); } String wanted = getTextbefore(source, offset); return filter(allWordsCache, wanted); } void add(String word); Set<String> calculate(String so...
@Test public void source_empty__calculate_nothing_on_index_0(){ Set<String> result = completionToTest.calculate("", 0); assertResult(result).hasNoResults(); } @Test public void a_space_albert_likes_automated_testing__offset_1_calculates_albert__automated_() { Set<String> result = completionToTest.calculate("a albert li...
SimpleWordCodeCompletion { public String getTextbefore(String source, int offset) { if (source == null || source.isEmpty()) { return ""; } if (offset <= 0) { return ""; } int sourceLength = source.length(); if (offset > sourceLength) { return ""; } StringBuilder sb = new StringBuilder(); int current = offset - 1; boole...
@Test public void getTextbefore__a_b_c__index_0_text_before_is_empty(){ assertEquals("", completionToTest.getTextbefore("a b c", 0)); } @Test public void getTextbefore__a_b_c__index_1_text_before_is_a(){ assertEquals("a", completionToTest.getTextbefore("a b c", 1)); } @Test public void getTextbefore__a_b_c__index_2_tex...
CommandStringToCommandListConverter { public List<String> convert(String commandString) { List<String> list = new ArrayList<>(); if (commandString == null) { return list; } String inspect = commandString.trim(); if (inspect.isEmpty()) { return list; } String[] commands = commandString.split(" "); for (String command: c...
@Test public void a_space_b_space_c__are_three_entries_a_b_c() { assertEquals(asList("a", "b", "c"), converterToTest.convert("a b c")); } @Test public void three_spaces_only_are_empty_list() { assertEquals(asList(), converterToTest.convert(" ")); } @Test public void three_spaces_then_a_followed_by_three_spaces_only_are...
SimpleStringUtils { public static String nextReducedVariableWord(String string, int offset) { return nextWord(string, offset, new ReducedVariableWordEndDetector()); } static boolean equals(String text1, String text2); static String shortString(String string, int max); static String nextReducedVariableWord(String strin...
@Test public void nextReducedVariable_from_string_alpha_beta_gamma_offset_0_is_alpha() { assertEquals("alpha", SimpleStringUtils.nextReducedVariableWord("alpha beta gamma", 0)); } @Test public void nextReducedVariable_from_string_alpha_beta_gamma_offset_n1_is_empty() { assertEquals("", SimpleStringUtils.nextReducedVari...
DebugBashCodeToggleSupport { public String enableDebugging(String sourceCode, String hostname, int port) throws IOException { bashPIDSnippetSupport.ensureKillOldTerminalFileExistsInSystemUserHome(); bashPIDSnippetSupport.ensureStoreTerminalPIDFileExistsInSystemUserHome(); ensureDebugFileExistsInSystemUserHome(); String...
@Test public void enable_debugging_empty_code_results_in_firstline_including_temp_debugger_file() throws Exception { String newCode = supportToTest.enableDebugging("","localhost", BashDebugConstants.DEFAULT_DEBUG_PORT); String[] asArray = newCode.split("\n"); assertEquals(1, asArray.length); assertTrue(asArray[0].start...
SimpleStringUtils { public static String shortString(String string, int max) { if (max == 0) { return EMPTY; } if (string == null) { return EMPTY; } if (string.length() <= max) { return string; } if (max == 1) { return "."; } if (max == 2) { return ".."; } if (max == 3) { return "..."; } StringBuilder sb = new StringBu...
@Test public void short_string_null_1_returns_empty_string() { assertEquals("", SimpleStringUtils.shortString(null, 1)); } @Test public void short_string_a_0_returns_empty_string() { assertEquals("", SimpleStringUtils.shortString("a", 0)); } @Test public void short_string_a_1_returns_a_string() { assertEquals("a", Simp...
SimpleStringUtils { public static boolean equals(String text1, String text2) { if (text1 == null) { if (text2 == null) { return true; } return false; } if (text2 == null) { return false; } return text2.equals(text1); } static boolean equals(String text1, String text2); static String shortString(String string, int max)...
@Test public void null_equals_null__is_true() { assertTrue(SimpleStringUtils.equals(null, null)); } @Test public void a_equals_a__is_true() { assertTrue(SimpleStringUtils.equals("a", "a")); } @Test public void a_equals_null__is_false() { assertFalse(SimpleStringUtils.equals("a", null)); } @Test public void a_equals_b__...
OSUtil { public static String toUnixPath(String path) { if (path==null) { return "null"; } int index = path.indexOf(':'); if (index!=1) { return path; } char windowsDrive = path.charAt(0); String remaining = path.substring(2); StringBuilder sb = new StringBuilder(); sb.append('/'); sb.append(windowsDrive); sb.append(WI...
@Test public void bugfix_139_convert_unixpathes_in_windows() throws Exception { assertEquals("/C/Users/albert/.basheditor/remote-debugging-v1.sh", OSUtil.toUnixPath("C:\\Users\\albert\\.basheditor\\remote-debugging-v1.sh")); assertEquals("/D/some/Other/.path/xYz.sh", OSUtil.toUnixPath("D:\\some\\Other\\.path\\xYz.sh"))...
CommandStringVariableReplaceSupport { public String replaceVariables(String commandLineWithVariables, Map<String,String> mapping) { if (mapping==null) { return commandLineWithVariables; } String result = ""+commandLineWithVariables; for (String key: mapping.keySet()) { String replace = mapping.get(key); if (replace==nu...
@Test public void real_life_example() { Map<String, String> map = new HashMap<>(); map.put("BE_CMD_CALL", "cd /tmp;./xyz4722810921592969191.txt -a 1 -b 2;_exit_status=$?;echo \"Exit code=$_exit_status\";"); map.put("BE_CMD_TITLE", "Bash Editor DEBUG Session:xyz4722810921592969191.txt"); String result = supportToTest.re...
InternalTerminalCommandStringBuilder { public String build(TerminalLaunchContext context) { if (context == null) { return ""; } StringBuilder sb = new StringBuilder(); sb.append(bashPIDFileSupport.buildWritePIDToPortSpecificTmpFileSnippet(context.getPort())); sb.append("cd "); sb.append(context.getUnixStyledWorkingDir(...
@Test public void null_results_in_empty_string() { assertEquals("", toTest.build(null)); } @Test public void context_1() { assertTrue(toTest.build(context).contains("./null;_exit_status=$?;echo \"Exit code=$_exit_status\";")); } @Test public void context_2() { context.file=null; context.terminalCommand="terminalCommand...
BashFileExtensionMatcher { public boolean isMatching(String fileExtension) { return isMatching(fileExtension,true); } boolean isMatching(String fileExtension); boolean isMatching(String fileExtension, boolean removePoint); }
@Test public void test_matching() { assertTrue(matcherToTest.isMatching(null)); assertTrue(matcherToTest.isMatching("")); assertTrue(matcherToTest.isMatching("bash")); assertTrue(matcherToTest.isMatching("sh")); assertTrue(matcherToTest.isMatching(".bash")); assertTrue(matcherToTest.isMatching(".sh")); assertTrue(match...
BashScriptModelBuilder { public BashScriptModel build(String bashScript) throws BashScriptModelException { BashScriptModel model = new BashScriptModel(); TokenParser parser = new TokenParser(); List<ParseToken> tokens; try { tokens = parser.parse(bashScript); } catch (TokenParserException e) { throw new BashScriptModel...
@Test public void bugfix_196_inside_heredoc_something_looking_like_a_function_is_not_a_function() throws Exception{ String testScript = "cat << -EOT\n" + "st.getval();\n" + "-EOT"; BashScriptModel bashScriptModel = builderToTest.build(testScript); assertThat(bashScriptModel). hasNoErrors(). hasNoFunctions(); } @Test pu...
BashScriptModel implements BashVariableRegistry { public boolean hasErrors() { return !getErrors().isEmpty(); } Collection<BashFunction> getFunctions(); Collection<BashError> getErrors(); boolean hasErrors(); List<ParseToken> getDebugTokens(); boolean hasDebugTokens(); Map<String, BashVariable> getVariables(); BashVar...
@Test public void has_errors_returns_false_when_no_error_is_added() { assertFalse(modelToTest.hasErrors()); }
ParseToken { public boolean isVariableDefinition() { String t = getSafeText(); boolean isVariable = t.endsWith("="); isVariable = isVariable && t.length()>1; isVariable = isVariable && VALID_VARIABLE_NAME_PATTERN.matcher(t).matches(); return isVariable; } ParseToken(); ParseToken(String text); ParseToken(String tex...
@Test public void token_var_starting_with_underscore_is_var() { assertTrue(new ParseToken("_XYZ=").isVariableDefinition()); } @Test public void token_var_ending_with_underscore_is_var() { assertTrue(new ParseToken("XYZ_=").isVariableDefinition()); } @Test public void token_var1_equal_is_var() { assertTrue(new ParseToke...
ParseToken { public boolean isDo() { return getSafeText().equals("do"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingleString(); bo...
@Test public void token_do_is_do() { assertTrue(new ParseToken("do").isDo()); }
ParseToken { public boolean isDone() { return getSafeText().equals("done"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingleString()...
@Test public void token_done_is_done() { assertTrue(new ParseToken("done").isDone()); }
ParseToken { public boolean isIf() { return getSafeText().equals("if"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingleString(); bo...
@Test public void token_if_is_if() { assertTrue(new ParseToken("if").isIf()); }
ParseToken { public boolean isFi() { return getSafeText().equals("fi"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingleString(); bo...
@Test public void token_fi_is_fi() { assertTrue(new ParseToken("fi").isFi()); }
ParseToken { public boolean isHereDoc() { return ! isHereString() && getSafeText().startsWith("<<"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment();...
@Test public void token_starts_with_heredoc_is_heredoc() { assertTrue(new ParseToken("<< xyz").isHereDoc()); } @Test public void token_starts_with_herestring_is_no_heredoc() { assertFalse(new ParseToken("<<< xyz").isHereDoc()); }
ParseToken { public boolean isHereString() { return getSafeText().startsWith("<<<"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingl...
@Test public void token_starts_with_heredoc_is_no_herestring() { assertFalse(new ParseToken("<< xyz").isHereString()); } @Test public void token_starts_with_herestring_is_herestring() { assertTrue(new ParseToken("<<< xyz").isHereString()); }
ParseToken { public boolean isComment() { return getSafeText().startsWith("#"); } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String createTypeDescription(); boolean isComment(); boolean isSingleStri...
@Test public void token_starts_with_hash_space_xyz_is_comment() { assertTrue(new ParseToken("# xyz").isComment()); } @Test public void token_starts_with_hash_xyz_is_comment() { assertTrue(new ParseToken("#xyz").isComment()); } @Test public void token_starts_with_a_is_no_comment() { assertFalse(new ParseToken("axyz").is...
ParseToken { public boolean isString() { boolean isString = isSingleString() || isDoubleString() || isDoubleTickedString(); return isString; } ParseToken(); ParseToken(String text); ParseToken(String text, int start, int end); String getText(); int getStart(); int getEnd(); @Override String toString(); String creat...
@Test public void single_string_xxx_is_string() { assertTrue(new ParseToken("'xxx'").isString()); } @Test public void double_ticked_string_xxx_is_string() { assertTrue(new ParseToken("`xxx`").isString()); } @Test public void double_string_xxx_is_string() { assertTrue(new ParseToken("\"xxx\"").isString()); }
JdbcTemplateLocationDataSource implements LocationDataSource { @Override public Print next() { return cacheNext(); } JdbcTemplateLocationDataSource(JdbcTemplate tmplate); @Override Print next(); @Override Print prev(); @Override boolean hasNext(); }
@Test public void testNext() { long pre = System.currentTimeMillis(); long start = pre; for (int i = 0; i < 100; i++) { while (source.hasNext()) { source.next(); } System.out.print((System.currentTimeMillis() - pre) + " "); pre = System.currentTimeMillis(); } long total = System.currentTimeMillis()-start; System.out.pr...
WallInfo { public boolean isCrossWall(Point a, Point b) { if (x2 < Math.min(a.getX(), b.getX()) || x1 > Math.max(a.getX(), b.getX())) { return false; } if (y2 < Math.min(a.getY(), b.getY()) || y1 > Math.max(a.getY(), b.getY())) { return false; } if (isInWall(b.getX(), b.getY()) && !isInWall(a.getX(), a.getY())) { retur...
@Test public void testIsCrossWall() { Point p1 = new Point(0,0); Point p2 = new Point(5,5); Assert.assertTrue(wall.isCrossWall(p1, p2)); Point p3 = new Point(3,3); Assert.assertTrue(!wall.isCrossWall(p1, p3)); Point p4 = new Point(6,2); Point p5 = new Point(3,10); Assert.assertTrue(wall.isCrossWall(p4, p5)); Point p6 =...
LoadPaths { public static void loadStaticPath(String filename, CountDownLatch latch){ List<StaticPath> tmpPaths = new ArrayList<StaticPath>(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(LoadPaths.class...
@Test public void testLoadPaths() { CountDownLatch latch = new CountDownLatch(1); LoadPaths.loadStaticPath("paths.xml", latch); System.out.println("path: "); System.out.println(LoadPaths.paths); }
CommonUtils { @SuppressWarnings("unchecked") public static List<Result> selectSort(List<Result> results, int k, String distanceMethod) { int len = results.size(); assert len >= k; TreeSet<Result> set; Comparator<Result> comp = distanceMethod.trim().equals("euclidean") ? new AscendingOrderComparator() : new DescendingOr...
@Test public void testSelectSort() { Random random = new Random(); List<Result> rs = new ArrayList<>(); for (int i = 0; i < 10; i++) { rs.add(new Result(random.nextDouble(), null)); } for (Result r : rs) { System.out.print(r.value() + " "); } System.out.println(); List<Result> ret1 = CommonUtils.selectSort(rs, 3, "eucl...
PointQueue { public Point enqueue(Point p, int level) { assert level == Constant.SLOW_QUEUE_LENGTH || level == Constant.NORMAL_QUEUE_LENGTH || level == Constant.FAST_QUEUE_LENGTH || level == Constant.MAX_QUEUE_LENGTH; if (this._queue.size() < Constant.MAX_QUEUE_LENGTH + 1) { return (Point)p.clone(); } Point result = ca...
@Test public void testEnqueue() { for (int i = 0; i < Constant.SLOW_QUEUE_LENGTH; i++) { Point t = new Point(i, i); Point r = queue.enqueue(t, Constant.FAST_QUEUE_LENGTH); System.out.println("t: " + t + " r: " + r); Assert.assertTrue(t.equals(r)); } for (int i = 0; i < 5; i++) { Point p = new Point(i + 100, i + 100); S...
KDTreeTool { public static KDTree unmodifiableKDTree(KDTree tree) { UnmodifiableKDTree kdTree = new KDTreeTool.UnmodifiableKDTree(2); kdTree.setKdTree(tree); return kdTree; } static KDTree unmodifiableKDTree(KDTree tree); }
@Test public void testAsUnmodifiableKDTree() throws KeySizeException, KeyDuplicateException, KeyMissingException { KDTree kd = new KDTree(2); kd.insert(new double[]{1,2},1); kd.insert(new double[]{2,2},2); KDTree tree = KDTreeTool.unmodifiableKDTree(kd); int val = (int) tree.nearest(new double[]{1,2}); System.out.print...
StaticPathChecker { public Point checker(PathPoint pathPoint) { int x = pathPoint.getX(), y = pathPoint.getY(); int angle = pathPoint.angle(); if (queue.size() > 0) { PathPoint lastPoint = this.queue.peekLast(); int distance = (int) Math.sqrt(Math.pow(lastPoint.getX() - x, 2) + Math.pow(lastPoint.getY() + y, 2)); if (d...
@Test public void testChecker() { Random rand = new Random(); for (int i = 0; i < 40; i++) { Point p = new Point(i*50 + rand.nextInt(10), 1300 + rand.nextInt(10)); PathPoint pp = new PathPoint(p, 0); Point ret = checker.checker(pp); if (ret != null) { System.out.println(ret); } else { System.out.println("fail"); } } fo...
PF implements Filter { public PF(int n) { this.particleNumbers = n; MIN_NEFF = 2*n/3; particles = new Particle[particleNumbers]; LOGGER.debug("particle numbers: {}", particleNumbers); } PF(int n); @Override void init(Point point); @Override void predict(Sensors sensor, double al); @Override Point update(Point fingerRet...
@Test public void testPF() { Point point = new Point(1000, 1000); pf.init(point); for (int i = 1; i < 5; i++) { Sensors ss = CommonUtils.buildSensorsData(); pf.predict(ss, 0.1); Point p = new Point(1000 , 1000 + i*Constant.NORMAL_STEP_LENGTH); double[][] r = {{0.1, 0}, {0, 0.1}}; Matrix R = new Matrix(r); Point ret = p...
WxCpDepartmentServiceImpl implements WxCpDepartmentService { @Override public Integer create(WxCpDepart depart) throws WxErrorException { String url = "https: String responseContent = this.mainService.post(url, depart.toJson()); JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return GsonHelper.get...
@Test public void testCreate() throws Exception { WxCpDepart cpDepart = new WxCpDepart(); cpDepart.setName("子部门" + System.currentTimeMillis()); cpDepart.setParentId(1); cpDepart.setOrder(1); Integer departId = this.wxCpService.getDepartmentService().create(cpDepart); System.out.println(departId); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeArticleTotal> getArticleTotal(Date beginDate, Date endDate) throws WxErrorException { String responseContent = this.wxMpService.post(GET_ARTICLE_TOTAL, buildParams(beginDate, endDate)); return WxDataCubeArticleTotal.fromJson(respon...
@Test(dataProvider = "oneDay") public void testGetArticleTotal(Date date) throws WxErrorException { List<WxDataCubeArticleTotal> results = this.wxService.getDataCubeService() .getArticleTotal(date, date); Assert.assertNotNull(results); System.out.println(results); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeArticleResult> getUserRead(Date beginDate, Date endDate) throws WxErrorException { return this.getArticleResults(GET_USER_READ, beginDate, endDate); } WxMpDataCubeServiceImpl(WxMpService wxMpService); @Override List<WxDataCubeUserS...
@Test(dataProvider = "threeDays") public void testGetUserRead(Date beginDate, Date endDate) throws WxErrorException { List<WxDataCubeArticleResult> results = this.wxService.getDataCubeService() .getUserRead(beginDate, endDate); Assert.assertNotNull(results); System.out.println(results); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeArticleResult> getUserReadHour(Date beginDate, Date endDate) throws WxErrorException { return this.getArticleResults(GET_USER_READ_HOUR, beginDate, endDate); } WxMpDataCubeServiceImpl(WxMpService wxMpService); @Override List<WxData...
@Test(dataProvider = "oneDay") public void testGetUserReadHour(Date date) throws WxErrorException { List<WxDataCubeArticleResult> results = this.wxService.getDataCubeService() .getUserReadHour(date, date); Assert.assertNotNull(results); System.out.println(results); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeArticleResult> getUserShare(Date beginDate, Date endDate) throws WxErrorException { return this.getArticleResults(GET_USER_SHARE, beginDate, endDate); } WxMpDataCubeServiceImpl(WxMpService wxMpService); @Override List<WxDataCubeUse...
@Test(dataProvider = "sevenDays") public void testGetUserShare(Date beginDate, Date endDate) throws WxErrorException { List<WxDataCubeArticleResult> results = this.wxService.getDataCubeService() .getUserShare(beginDate, endDate); Assert.assertNotNull(results); System.out.println(results); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeArticleResult> getUserShareHour(Date beginDate, Date endDate) throws WxErrorException { return this.getArticleResults(GET_USER_SHARE_HOUR, beginDate, endDate); } WxMpDataCubeServiceImpl(WxMpService wxMpService); @Override List<WxDa...
@Test(dataProvider = "oneDay") public void testGetUserShareHour(Date date) throws WxErrorException { List<WxDataCubeArticleResult> results = this.wxService.getDataCubeService() .getUserShareHour(date, date); Assert.assertNotNull(results); System.out.println(results); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeMsgResult> getUpstreamMsg(Date beginDate, Date endDate) throws WxErrorException { return this.getUpstreamMsg(GET_UPSTREAM_MSG, beginDate, endDate); } WxMpDataCubeServiceImpl(WxMpService wxMpService); @Override List<WxDataCubeUserSu...
@Test(dataProvider = "sevenDays") public void testGetUpstreamMsg(Date beginDate, Date endDate) throws WxErrorException { List<WxDataCubeMsgResult> results = this.wxService.getDataCubeService() .getUpstreamMsg(beginDate, endDate); Assert.assertNotNull(results); System.out.println(results); }
WxMpDataCubeServiceImpl implements WxMpDataCubeService { @Override public List<WxDataCubeMsgResult> getUpstreamMsgHour(Date beginDate, Date endDate) throws WxErrorException { return this.getUpstreamMsg(GET_UPSTREAM_MSG_HOUR, beginDate, endDate); } WxMpDataCubeServiceImpl(WxMpService wxMpService); @Override List<WxDataC...
@Test(dataProvider = "oneDay") public void testGetUpstreamMsgHour(Date date) throws WxErrorException { List<WxDataCubeMsgResult> results = this.wxService.getDataCubeService() .getUpstreamMsgHour(date, date); Assert.assertNotNull(results); System.out.println(results); }