src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
CurrentDatetime { public void forget() { constructionDateTime = LocalDateTime.now(); constructionNanos = System.nanoTime(); currentDateTime = null; currentDate = null; currentTime = null; currentTimestamp = null; } CurrentDatetime(); Date getCurrentDate(); Time getCurrentTime(); Timestamp getCurrentTimestamp(); void forget(); int getTimestampPrecision(); void setTimestampPrecision(int timestampPrecision); }
@Test public void testForget() throws InterruptedException { Timestamp timestamp = cut.getCurrentTimestamp(); TimeUnit.MILLISECONDS.sleep(10); Timestamp sameTimestamp = cut.getCurrentTimestamp(); assertEquals(timestamp, sameTimestamp); TimeUnit.MILLISECONDS.sleep(10); cut.forget(); Timestamp newTimestamp = cut.getCurrentTimestamp(); assertNotEquals(timestamp, newTimestamp); }
HLC { public long sendOrLocalEvent() { long currentHLC; long returnHLC; while (true) { currentHLC = atomicHLC.get(); long[] hlc = HLCToPhysicalAndLogical(currentHLC); long logical = Math.max(hlc[0], System.currentTimeMillis()); if (logical == hlc[0]) hlc[1]++; else { hlc[0] = logical; hlc[1] = 0l; } returnHLC = physicalAndLogicalToHLC(hlc[0],hlc[1]); if (atomicHLC.compareAndSet(currentHLC,returnHLC)) return returnHLC; } } long sendOrLocalEvent(); long receiveEvent(long message); static long clockTimestampToHLC(long timestamp, TimeUnit timeUnit); static long[] HLCToPhysicalAndLogical(long htTimestamp); static long physicalAndLogicalToHLC(long physical, long logical); static final int hlcNumBitsToShift; static final int hlcLogicalBitsMask; }
@Test public void alwaysIncreasingLocalEvent() { HLC hlc = new HLC(); long value = 0; for (int i = 0; i< 1000000; i++) { long comparison = hlc.sendOrLocalEvent(); Assert.assertTrue("went backwards, catastophic",value<comparison); value = comparison; } }
SimpleTxnFilter implements TxnFilter { @Override public DataFilter.ReturnCode filterCell(DataCell keyValue) throws IOException{ CellType type=keyValue.dataType(); switch (type) { case COMMIT_TIMESTAMP: ensureTransactionIsCached(keyValue); return DataFilter.ReturnCode.SKIP; case FOREIGN_KEY_COUNTER: case FIRST_WRITE_TOKEN: case DELETE_RIGHT_AFTER_FIRST_WRITE_TOKEN: return DataFilter.ReturnCode.SKIP; } readResolve(keyValue); switch(type){ case TOMBSTONE: addToTombstoneCache(keyValue); return DataFilter.ReturnCode.SKIP; case ANTI_TOMBSTONE: addToAntiTombstoneCache(keyValue); return DataFilter.ReturnCode.SKIP; case USER_DATA: return checkVisibility(keyValue); default: throw new AssertionError("Unexpected Data type: "+type); } } SimpleTxnFilter(String tableName, TxnView myTxn, ReadResolver readResolver, TxnSupplier baseSupplier, boolean ignoreNewerTransactions); @SuppressWarnings("unchecked") SimpleTxnFilter(String tableName, TxnView myTxn, ReadResolver readResolver, TxnSupplier baseSupplier); @Override boolean filterRow(); @Override void reset(); TxnSupplier getTxnSupplier(); @Override DataFilter.ReturnCode filterCell(DataCell keyValue); @Override DataCell produceAccumulatedResult(); @Override void nextRow(); @Override boolean getExcludeRow(); @Override RowAccumulator getAccumulator(); }
@Test public void testCanSeeCommittedRowSnapshotIsolation() throws Exception{ TxnSupplier baseStore=txnStore; TxnView committed=new CommittedTxn(0x100l,0x200l); baseStore.cache(committed); ReadResolver noopResolver=NoOpReadResolver.INSTANCE; TxnView myTxn=new InheritingTxnView(Txn.ROOT_TRANSACTION,0x300l,0x300l,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.State.ACTIVE); DataPut testCommitKv=operationFactory.newDataPut(myTxn,Encoding.encode("1")); testCommitKv.addCell(SIConstants.DEFAULT_FAMILY_BYTES,SIConstants.COMMIT_TIMESTAMP_COLUMN_BYTES,0x100l,Bytes.toBytes(1l)); DataCell commitCell=testCommitKv.cells().iterator().next(); Assert.assertNotNull("Did not create a commit cell!",commitCell); Assert.assertEquals("Incorrect data type!",CellType.COMMIT_TIMESTAMP,commitCell.dataType()); SimpleTxnFilter filterState=new SimpleTxnFilter(null,myTxn,noopResolver,baseStore); DataFilter.ReturnCode code=filterState.filterCell(commitCell); Assert.assertEquals("Incorrect return code for commit keyvalue!",DataFilter.ReturnCode.SKIP,code); DataPut testUserPut=operationFactory.newDataPut(myTxn,Encoding.encode("1")); testUserPut.addCell(SIConstants.DEFAULT_FAMILY_BYTES,SIConstants.PACKED_COLUMN_BYTES,0x100l,Encoding.encode("hello")); DataCell userCell=testUserPut.cells().iterator().next(); Assert.assertNotNull("Did not create a user cell!",userCell); Assert.assertEquals("Incorrect data type!",CellType.USER_DATA,userCell.dataType()); DataFilter.ReturnCode returnCode=filterState.filterCell(userCell); Assert.assertEquals("Incorrect return code for data cell!",DataFilter.ReturnCode.INCLUDE,returnCode); } @Test public void testCannotSeeRolledBackRow() throws Exception{ TxnSupplier baseStore=txnStore; Txn rolledBack=txnLifecycleManager.beginTransaction(Bytes.toBytes("hello")); rolledBack.rollback(); ReadResolver noopResolver=NoOpReadResolver.INSTANCE; TxnView myTxn=new InheritingTxnView(Txn.ROOT_TRANSACTION,0x300l,0x300l,Txn.IsolationLevel.SNAPSHOT_ISOLATION,Txn.State.ACTIVE); SimpleTxnFilter filterState=new SimpleTxnFilter(null,myTxn,noopResolver,baseStore); DataCell userCell=getUserCell(rolledBack); DataFilter.ReturnCode returnCode=filterState.filterCell(userCell); Assert.assertEquals("Incorrect return code for data cell!",DataFilter.ReturnCode.SKIP,returnCode); }
EntryDecoder implements Supplier<MultiFieldDecoder> { public BitIndex getCurrentIndex() { return bitIndex; } EntryDecoder(); EntryDecoder(byte[] bytes); EntryDecoder(byte[] bytes, int offset, int length); void set(byte[] bytes); void set(byte[] bytes, int offset, int length); boolean isSet(int position); boolean nextIsNull(int position); BitIndex getCurrentIndex(); byte[] getData(int position); MultiFieldDecoder getEntryDecoder(); boolean seekForward(MultiFieldDecoder decoder, int position); ByteBuffer nextAsBuffer(MultiFieldDecoder decoder, int position); void accumulate(int position, EntryAccumulator accumulator, byte[] buffer, int offset, int length); void close(); long length(); void nextField(MultiFieldDecoder mutationDecoder, int indexPosition, ByteSlice rowSlice); @Override MultiFieldDecoder get(); }
@Test public void getCurrentIndex_returnsIndexWithCardinalityOfNonNullFields() throws IOException { byte[] value = new byte[]{-126, -128, 0, 69}; EntryDecoder entryDecoder = new EntryDecoder(value); BitIndex bitIndex = entryDecoder.getCurrentIndex(); assertEquals("Note that the cardinality only indicates number of non-null fields", 1, bitIndex.cardinality()); }
SagaInterestMatcher { public boolean matches(NewtonEvent event, SagaInterest interests) { final Method[] methods = event.getClass().getDeclaredMethods(); boolean matches = false; for (Method method : methods) { if (method.getName().startsWith("get")) { PropertyDescriptor ed = BeanUtils.findPropertyForMethod(method); if (ed == null) { continue; } if (ed.getName().equals(interests.getKey())) { try { Object ret = method.invoke(event); if (ret == null) break; String val = ret.toString(); if (interests.getValue().equals(val)) { matches = true; break; } } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } } return matches; } boolean matches(NewtonEvent event, SagaInterest interests); }
@Test public void matchesSuccess() throws Exception { SagaInterestMatcher matcher = new SagaInterestMatcher(); final TestEvent testEvent = new TestEvent("hello world"); final SagaInterest sagaInterest = new SagaInterest( TestSaga.class.getName(), TestEvent.class.getCanonicalName(), "saga-id", "some-id", "myId", "hello world" ); final boolean result = matcher.matches(testEvent, sagaInterest); assertTrue(result); }
DynamicInvokeEventAdaptor implements Function<NewtonEvent, Boolean>, Consumer<NewtonEvent> { @Override public void accept(NewtonEvent event) { apply(event); } DynamicInvokeEventAdaptor(Object target, Class<? extends Annotation> annotation); @Override void accept(NewtonEvent event); @Override Boolean apply(NewtonEvent event); }
@Test public void matchesAgainstParamInterfaceType() throws Exception { ParentHandler handler = new ParentHandler(); new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new EventWithParent()); assertTrue(handler.event instanceof EventWithParent); } @Test public void canInvokeClassHandler() throws Exception { Handler handler = new Handler(); new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new Event1()); assertTrue(handler.event instanceof Event1); } @Test public void canInvokeClassParentHandler() throws Exception { HandlerWithParent handler = new HandlerWithParent(); new DynamicInvokeEventAdaptor(handler, EventHandler.class).accept(new NonExplicitMatchEvent()); assertTrue(handler.event instanceof NonExplicitMatchEvent); }
MuonEventSourceRepository implements EventSourceRepository<A> { @Override public A load(Object aggregateIdentifier) { try { AggregateRoot aggregate = snapshotRepository.getLatestSnapshot(aggregateIdentifier).orElseGet(() -> { try { AggregateRoot ag = aggregateType.newInstance(); replayEvents(aggregateIdentifier).forEach(ag::handleEvent); return ag; } catch (InstantiationException | IllegalAccessException e) { throw new MuonException("Error creating new instance of Aggregate", e); } }); if (aggregate.isDeleted()) throw new AggregateNotFoundException(aggregateIdentifier); return (A) aggregate; } catch (EventStoreException | AggregateNotFoundException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Unable to load aggregate: ".concat(aggregateType.getSimpleName()), e); } } MuonEventSourceRepository(Class<A> type, AggregateRootSnapshotRepository snapshotRepository, NewtonEventClient aggregateEventClient, EventStreamProcessor eventStreamProcessor, String appName); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier, Long expectedVersion); @Override A load(Object aggregateIdentifier); @Override A load(Object aggregateIdentifier, Long version); @Override A newInstance(Callable<A> factoryMethod); @Override List<NewtonEvent> save(A aggregate); @Override List<NewtonEvent> delete(A aggregate); @Override Publisher<NewtonEvent> replay(Object aggregateIdentifier); @Override Publisher<AggregateRootUpdate<A>> susbcribeAggregateUpdates(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeColdHot(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeHot(Object aggregateIdentifier); static T executeCausedBy(NewtonEvent ev, Supplier<T> run); }
@Test public void load() throws Exception { String id = "simple-id"; client.publishDomainEvents(id.toString(), TestAggregate.class, Collections.singletonList( new TestAggregateCreated(id) ), null); TestAggregate aggregate = repository.load(id); assertNotNull(aggregate); assertEquals(id, aggregate.getId()); } @DirtiesContext @Test(expected = EventStoreException.class) public void loadWhenTransportFailureThrowsException() throws Exception { transport.triggerFailure(); repository.load(UUID.randomUUID().toString()); } @Test(expected = AggregateNotFoundException.class) public void throwsExceptionOnNonExistingAggregate() { repository.load("no-such-id-as-this"); } @Test(expected = AggregateNotFoundException.class) public void withVersionThrowsExceptionOnNonExistingAggregate() { repository.load("no-such-id-as-this", 5L); } @Test public void canLoadWithVersion() { String id = "awesome-things"; client.publishDomainEvents(id.toString(), TestAggregate.class, Arrays.asList( new TestAggregateCreated(), new TestAggregateCreated() ), null); TestAggregate aggregate = repository.load(id, 2L); assertEquals(2, aggregate.getVersion()); } @Test(expected = OptimisticLockException.class) public void throwsOptimisticLockExceptionOnBadVersion() { String id = "awesome-id"; client.publishDomainEvents(id.toString(), TestAggregate.class, Arrays.asList( new TestAggregateCreated() ), null); repository.load(id, 2L); }
MuonEventSourceRepository implements EventSourceRepository<A> { @Override public CompletableFuture<A> loadAsync(Object aggregateIdentifier) { return CompletableFuture.supplyAsync(() -> load(aggregateIdentifier)); } MuonEventSourceRepository(Class<A> type, AggregateRootSnapshotRepository snapshotRepository, NewtonEventClient aggregateEventClient, EventStreamProcessor eventStreamProcessor, String appName); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier, Long expectedVersion); @Override A load(Object aggregateIdentifier); @Override A load(Object aggregateIdentifier, Long version); @Override A newInstance(Callable<A> factoryMethod); @Override List<NewtonEvent> save(A aggregate); @Override List<NewtonEvent> delete(A aggregate); @Override Publisher<NewtonEvent> replay(Object aggregateIdentifier); @Override Publisher<AggregateRootUpdate<A>> susbcribeAggregateUpdates(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeColdHot(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeHot(Object aggregateIdentifier); static T executeCausedBy(NewtonEvent ev, Supplier<T> run); }
@Test public void loadAsync() throws Exception { String id = "simple-id"; client.publishDomainEvents(id.toString(), TestAggregate.class, Collections.singletonList( new TestAggregateCreated(id) ), null); TestAggregate aggregate = repository.loadAsync(id).get(); assertNotNull(aggregate); assertEquals(id, aggregate.getId()); } @Test public void throwsExceptionOnNonExistingAggregateAsync() throws ExecutionException, InterruptedException { final AtomicBoolean bool = new AtomicBoolean(false); repository.loadAsync("no-such-id-as-this").exceptionally(throwable -> { bool.set(true); return null; }).join(); assertTrue(bool.get()); }
MuonEventSourceRepository implements EventSourceRepository<A> { @Override public List<NewtonEvent> save(A aggregate) { emitForAggregatePersistence(aggregate); emitForStreamProcessing(aggregate); List<NewtonEvent> events = new ArrayList<>(aggregate.getNewOperations()); aggregate.getNewOperations().clear(); snapshotRepository.persist(aggregate); return events; } MuonEventSourceRepository(Class<A> type, AggregateRootSnapshotRepository snapshotRepository, NewtonEventClient aggregateEventClient, EventStreamProcessor eventStreamProcessor, String appName); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier); @Override CompletableFuture<A> loadAsync(Object aggregateIdentifier, Long expectedVersion); @Override A load(Object aggregateIdentifier); @Override A load(Object aggregateIdentifier, Long version); @Override A newInstance(Callable<A> factoryMethod); @Override List<NewtonEvent> save(A aggregate); @Override List<NewtonEvent> delete(A aggregate); @Override Publisher<NewtonEvent> replay(Object aggregateIdentifier); @Override Publisher<AggregateRootUpdate<A>> susbcribeAggregateUpdates(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeColdHot(Object aggregateIdentifier); @Override Publisher<NewtonEvent> subscribeHot(Object aggregateIdentifier); static T executeCausedBy(NewtonEvent ev, Supplier<T> run); }
@Test public void save() throws Exception { String id = UUID.randomUUID().toString(); TestAggregate customer = new TestAggregate(id); repository.save(customer); List<Event> events = client.loadAggregateRoot(id.toString(), TestAggregate.class).get(); assertEquals(1, events.size()); assertEquals(TestAggregateCreated.class.getSimpleName(), events.get(0).getEventType()); }
SagaStreamManager { public void processSaga(Class<? extends Saga> saga) { SagaStreamConfig[] s = saga.getAnnotationsByType(SagaStreamConfig.class); if (s.length == 0) throw new IllegalStateException("Saga does not have @SagaStreamConfig: " + saga); recordSagaCreatedByEvent(saga); List<String> streams = new ArrayList<>(); streams.addAll(Arrays.asList(s[0].streams())); Arrays.asList(s[0].aggregateRoots()).forEach(aggregateRootClass -> streams.add(AggregateRootUtil.getAggregateRootStream(aggregateRootClass)) ); for (String stream : streams) { if (!subscribedStreams.contains(stream)) { subscribedStreams.add(stream); streamSubscriptionManager.globallyUniqueSubscriptionFromNow("saga-manager-" + stream, stream, event -> { worker.execute(() -> { processEvent(event); }); }); } } } SagaStreamManager( StreamSubscriptionManager streamSubscriptionManager, SagaRepository sagaRepository, CommandBus commandBus, SagaInterestMatcher sagaInterestMatcher, SagaFactory sagaFactory, SagaLoader sagaLoader); @EventListener void onApplicationEvent(ApplicationReadyEvent onReadyEvent); void listenToLifecycleEvents(); void processSaga(Class<? extends Saga> saga); void processEvent(NewtonEvent event); final static String SAGA_LIFECYCLE_STREAM; }
@Test(expected = IllegalStateException.class) public void badlyConfiguredSagaBreaks() throws Exception { SagaStreamManager manager = streamManager(); manager.processSaga(NoAnnotationSaga.class); } @Test public void sagaConfigOpensStreamSubscriptions() throws Exception { SagaStreamManager manager = streamManager(); manager.processSaga(SagaWithConfig.class); verify(subscriptionManager, times(1)).globallyUniqueSubscriptionFromNow(eq("saga-manager-stream"), eq("stream"), any()); verify(subscriptionManager, times(1)).globallyUniqueSubscriptionFromNow(eq("saga-manager-stream2"), eq("stream2"), any()); } @Test public void duplicateStreamConfigDoesNotOpenAgain() throws Exception { SagaStreamManager manager = streamManager(); manager.processSaga(SagaWithConfig.class); manager.processSaga(SagaWithConfig.class); verify(subscriptionManager, times(1)).globallyUniqueSubscriptionFromNow(eq("saga-manager-stream"), eq("stream"), any()); } @Test public void dataOnStreamIsSentToSagas() throws Exception { SagaWithEventHandler saga = mock(SagaWithEventHandler.class); String sagaId = "12345"; when(sagaRepository.getSagasInterestedIn(eq(SagaEvent.class))).thenReturn(Arrays.asList(new SagaInterest( TestSaga.class.getName(), SagaWithEventHandler.class.getName(), "££££123", sagaId, "hello", "world"))); Class<? extends Saga> type = SagaWithEventHandler.class; when(sagaLoader.loadSagaClass(any())).thenReturn((Class)type); when(sagaRepository.load(eq(sagaId), eq(SagaWithEventHandler.class))).thenReturn(Optional.of(saga)); SagaStreamManager manager = streamManager(); ArgumentCaptor<Consumer<NewtonEvent>> eventStreamCaptor = (ArgumentCaptor)ArgumentCaptor.forClass(Consumer.class); manager.processSaga(SagaWithConfig.class); verify(subscriptionManager, times(1)).globallyUniqueSubscriptionFromNow(eq("saga-manager-stream"), eq("stream"), eventStreamCaptor.capture()); SagaEvent ev = new SagaEvent(); eventStreamCaptor.getValue().accept(ev); Thread.sleep(500); verify(saga).handle(eq(ev)); } @Test public void associationsAreUsedToFilterStream() throws Exception { when(sagaInterestMatcher.matches(any(), any())).thenReturn(false); SagaWithCommands saga = new SagaWithCommands(); SagaStreamManager manager = streamManager(); ArgumentCaptor<Consumer<NewtonEvent>> eventStreamCaptor = (ArgumentCaptor)ArgumentCaptor.forClass(Consumer.class); manager.processSaga(SagaWithCommands.class); String sagaId = "1234"; when(sagaRepository.getSagasInterestedIn(eq(SagaEvent.class))).thenReturn(Arrays.asList(new SagaInterest( TestSaga.class.getName(), SagaWithEventHandler.class.getCanonicalName(), sagaId, "4321", "hello", "orld"))); Class<? extends Saga> type = SagaWithCommands.class; when(sagaLoader.loadSagaClass(any())).thenReturn((Class)type); when(sagaRepository.load(eq(sagaId), eq(SagaWithCommands.class))).thenReturn(Optional.of(saga)); verify(subscriptionManager).globallyUniqueSubscriptionFromNow(eq("saga-manager-mystream"), eq("mystream"), eventStreamCaptor.capture()); eventStreamCaptor.getValue().accept(new SagaEvent()); verify(commandBus, times(0)).dispatch(any(CommandIntent.class)); }
AggregateRoot { protected void raiseEvent(NewtonEvent event) { newOperations.add(event); handleEvent(event); } abstract T getId(); long getVersion(); List<NewtonEvent> getNewOperations(); void handleEvent(NewtonEvent event); void delete(); }
@Test public void raiseEvent() throws Exception { TestAggregateRoot testAggregate = new TestAggregateRoot(); testAggregate.doA("ZZZ"); assertEquals("A event raised and handled", "ZZZ", testAggregate.getAString()); assertTrue("New Operations contains AEvent", ((AEvent)testAggregate.getNewOperations().get(0)).getValue().equals("ZZZ")); }
CommandFactory implements ApplicationContextAware { public Command create(Class<? extends Command> commandType) { return create(commandType, null, null, null, null); } Command create(Class<? extends Command> commandType); Command create(Class<? extends Command> commandType, Object payload, String tenantId); Command create(Class<? extends Command> commandType, Object payload, Object id, String tenantId); Command create(Class<? extends Command> commandType, Object payload, Object id, Map<String, Object> additionalProperties, String tenantId); @Override void setApplicationContext(ApplicationContext applicationContext); }
@Test public void create() throws Exception { Command cmd = commandFactory.create(TestCommand.class); Assert.assertNotNull(cmd); cmd.execute(); } @Test public void createFromPayload() throws Exception { Command cmd = commandFactory.create(TestPayloadCommand.class, new TestRequest("AAA"), null); Assert.assertNotNull(cmd); cmd.execute(); } @Test public void createFromCommandDefinition() throws Exception { final TestRequest payload = new TestRequest("AAA"); final String id = UUID.randomUUID().toString(); final Class<TestPayloadCommand> type = TestPayloadCommand.class; Command cmd = commandFactory.create(type, payload, id, "tenantId"); Assert.assertNotNull(cmd); cmd.execute(); } @Test public void createFromCommandDefinition_withAdditionalProperties() throws Exception { Command cmd = commandFactory.create(TestPayloadCommand.class, null, null, Collections.singletonMap("prop1", "Value"), null); Assert.assertNotNull(cmd); cmd.execute(); } @Test public void createFromStringIdUsingReflection() throws Exception { final String id = "1234"; Command cmd = commandFactory .create(TestCommand.class,null, id,null); Assert.assertNotNull(cmd); assertEquals(id, ((TestCommand)cmd).getId()); } @Test public void createFromCustomIdUsingReflection() throws Exception { final CustomId id = new CustomId("1234"); Command cmd = commandFactory .create(TestCommandWithCustomId.class,null, id,null); Assert.assertNotNull(cmd); assertEquals(id, ((TestCommandWithCustomId)cmd).getId()); } @Test public void createFromAdditonalProperties_GenericList() throws Exception { ArrayList<String> list = new ArrayList<>(); list.add("abc"); Map<String,Object> additionalProperties = new HashMap<>(); additionalProperties.put("list", list); Command cmd = commandFactory .create(TestCommand.class,null,null, additionalProperties, null); Assert.assertNotNull(cmd); assertEquals(list, ((TestCommand)cmd).getList()); }
StatefulSaga implements Saga { @Override public void handle(NewtonEvent event) { boolean eventHandled = eventAdaptor.apply(event); if (!eventHandled) { throw new IllegalStateException("Undefined @EventHandler method for event: ".concat(event.getClass().getName())); } version++; } long getVersion(); @Override void startWith(NewtonEvent event); @Override void handle(NewtonEvent event); }
@Test public void canDynamicDispatchEvents() throws Exception { TestSaga saga = new TestSaga(); saga.handle(new MyEvent()); assertNotNull(saga.event); } @Test(expected = IllegalStateException.class) public void requiresAnnotation() throws Exception { TestSaga saga = new TestSaga(); saga.handle(new MyOtherEvent()); assertNotNull(saga.event); }
Signatures { public static String sign(String urlString, String algorithm, String secretKey) { if (algorithm != null && !algorithm.equals(HMAC_SHA256_ALGORITHM)) { throw new RuntimeException("Unsupported signature: " + algorithm); } if (secretKey == null) { throw new RuntimeException("Signature key not found."); } Mac mac = null; URL url = null; try { byte[] secretyKeyBytes = secretKey.getBytes(UTF8_CHARSET); SecretKeySpec secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM); mac = Mac.getInstance(HMAC_SHA256_ALGORITHM); mac.init(secretKeySpec); url = new URL(urlString); } catch (Exception e) { throw new RuntimeException(e); } String protocol = url.getProtocol(); String host = url.getHost(); String path = url.getPath(); String query = url.getQuery(); Map<String, String> params = new HashMap<String, String>(); for (String pair: query.split("&")) { String[] keyValue = pair.split("="); params.put(keyValue[0], keyValue[1]); } if(!params.containsKey("Timestamp")) params.put("Timestamp", timestamp()); SortedMap<String, String> sortedParamMap = new TreeMap<String, String>(params); String canonicalQS = canonicalize(sortedParamMap); String toSign = "GET\n" + host + "\n" + path + "\n" + canonicalQS; String hmac = hmac(mac, toSign); String sig = percentEncodeRfc3986(hmac); return protocol + ": } static String sign(String urlString, String algorithm, String secretKey); }
@Test public void testAmazonHMACSHA256() { String secretKey = "1234567890"; String requestUrl = "http: String targetUrl = "http: String signedUrl = Signatures.sign(requestUrl, "HmacSHA256", secretKey); Assert.assertEquals("Signed request", targetUrl, signedUrl); }
DateUtils { public static String getCurrentTimeString() { GregorianCalendar gc = new GregorianCalendar(); gc.setTimeZone(TimeZone.getTimeZone(DUBLIN_TIME_ZONE)); SimpleDateFormat sfd = new SimpleDateFormat(MASK, Locale.ENGLISH); return sfd.format(gc.getTime()); } static String getCurrentTimeString(); static String getCurrentTimeStringNoSeparator(); static String formatStringDate(String date); }
@Test public void shouldPrintDublinTime() { System.out.print(DateUtils.getCurrentTimeString()); }
NowPlayingPresenterImpl implements NowPlayingPresenter, NowPlayingResponseModel { @Override public void infoLoaded(List<MovieInfo> movieInfoList) { List<MovieViewInfo> movieViewInfoList = new ArrayList<>(); for (MovieInfo movieInfo : movieInfoList) { movieViewInfoList.add(new MovieViewInfoImpl(movieInfo)); } nowPlayingViewModel.addToAdapter(movieViewInfoList); nowPlayingViewModel.showInProgress(false); } @Inject NowPlayingPresenterImpl(NowPlayingViewModel nowPlayingViewModel, NowPlayingInteractor nowPlayingInteractor); @Override void loadMoreInfo(); @Override void onStart(); @Override void onStop(); @Override void start(Bundle savedInstanceState); @Override void dataRestored(); @Override void infoLoaded(List<MovieInfo> movieInfoList); @Override void errorLoadingInfoData(); }
@Test public void infoLoaded() throws Exception { NowPlayingPresenterImpl nowPlayingPresenter = new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor); List<MovieInfo> movieInfoList = new ArrayList<>(); movieInfoList.add(movieInfo); ArgumentCaptor<List<MovieViewInfo>> argumentCaptor = ArgumentCaptor.forClass(List.class); nowPlayingPresenter.infoLoaded(movieInfoList); verify(mockNowPlayingViewModel).addToAdapter(anyListOf(MovieViewInfo.class)); verify(mockNowPlayingViewModel).showInProgress(false); verify(mockNowPlayingViewModel).addToAdapter(argumentCaptor.capture()); assertThat(argumentCaptor.getValue().size()).isEqualTo(1); }
NowPlayingPresenterImpl implements NowPlayingPresenter, NowPlayingResponseModel { @Override public void errorLoadingInfoData() { nowPlayingViewModel.showError(); loadMoreInfo(); } @Inject NowPlayingPresenterImpl(NowPlayingViewModel nowPlayingViewModel, NowPlayingInteractor nowPlayingInteractor); @Override void loadMoreInfo(); @Override void onStart(); @Override void onStop(); @Override void start(Bundle savedInstanceState); @Override void dataRestored(); @Override void infoLoaded(List<MovieInfo> movieInfoList); @Override void errorLoadingInfoData(); }
@Test public void errorLoadingInfoData() throws Exception { NowPlayingPresenterImpl nowPlayingPresenter = new NowPlayingPresenterImpl(mockNowPlayingViewModel, mockNowPlayingInteractor); List<MovieInfo> movieInfoList = new ArrayList<>(); movieInfoList.add(movieInfo); nowPlayingPresenter.errorLoadingInfoData(); verify(mockNowPlayingViewModel).showError(); verify(mockNowPlayingInteractor).loadMoreInfo(); }
AccountData implements Cloneable { public AccountData() { this(null, null, null, null, null); } AccountData(); AccountData(String username, String email, String password); AccountData(String username, String email, String password, String dob, String country); void setDob(String dob); void setCountry(String country); AccountData clone(); String toCsv(); @Override String toString(); static String randomAdultDateOfBirth(); static String randomDateOfBirth(int minAge, int maxAge); static final String DEFAULT_COUNTRY; }
@Test public void testAccountData() { AccountData account = new AccountData(); assertThat(account.getDob()).isNotBlank(); }
ProxySpacedBottleneck implements Runnable, Bottleneck<ProxyInfo> { @Override public void syncUseOf(ProxyInfo proxy) { hostBottleNeck.syncUseOf(proxy.getProvider().getHost()); } ProxySpacedBottleneck(); ProxySpacedBottleneck(int retentionTime); void setRetentionTime(int retentionTime); @Override void syncUseOf(ProxyInfo proxy); @Override void asyncUseOf(ProxyInfo proxy, BottleneckCallback callback); @Override void run(); @Override void onServerError(ProxyInfo proxy); }
@Ignore @Test public void parallelUsesTest() { ProxySpacedBottleneck bottleneck = new ProxySpacedBottleneck(); Thread bottleNeckThread = new Thread(bottleneck); bottleNeckThread.start(); ProxyPolicy proxyPolicy = new NintendoTimeLimitPolicy(); ProxyInfo proxy1 = new ProxyInfo(proxyPolicy, new HttpProxy("test", 1234)); ProxyInfo proxy2 = new ProxyInfo(proxyPolicy, new HttpProxy("test2", 1234)); logger.info("Start using proxy 1"); bottleneck.syncUseOf(proxy1); logger.info("First Use of proxy 1"); bottleneck.syncUseOf(proxy2); logger.info("First Use of proxy 2"); bottleneck.syncUseOf(proxy2); logger.info("Second Use of proxy 2"); bottleneck.syncUseOf(proxy1); logger.info("Second Use of proxy 1"); bottleneck.syncUseOf(proxy1); bottleneck.syncUseOf(proxy2); logger.info("Third Use of proxy 2"); } @Ignore @Test public void singleProxyTest() { ProxySpacedBottleneck bottleneck = new ProxySpacedBottleneck(); Thread bottleNeckThread = new Thread(bottleneck); bottleNeckThread.start(); ProxyPolicy proxyPolicy = new NintendoTimeLimitPolicy(); ProxyInfo proxy1 = new ProxyInfo(proxyPolicy, new HttpProxy("test", 1234)); logger.info("Start using proxy 1"); bottleneck.syncUseOf(proxy1); logger.info("First Use of proxy 1"); bottleneck.syncUseOf(proxy1); logger.info("Second Use of proxy 1"); bottleneck.syncUseOf(proxy1); logger.info("Third Use of proxy 1"); }
HttpProxy implements HttpProxyProvider { public static HttpProxy fromURI(String uri) { if (uri == null) { return null; } Matcher matcher = Pattern.compile(URI_REGEXP).matcher(uri); if (matcher.find()) { String host = matcher.group("host"); String protocol = StringUtils.lowerCase(matcher.group("protocol")); String login = matcher.group("login"); String pass = matcher.group("pass"); int port = -1; if (matcher.group("port") != null) { port = Integer.parseInt(matcher.group("port")); } if (port < 0 && protocol == null) { protocol = "http"; port = DEFAULT_PORT; } else { if (protocol == null) { for (Entry<String, Integer> entry : DEFAULT_MAPPING.entrySet()) { if (entry.getValue() == port) { protocol = entry.getKey(); break; } } if (protocol == null) { protocol = DEFAULT_PROTOCOL; } } else if (port < 0) { if (DEFAULT_MAPPING.get(protocol) != null) { port = DEFAULT_MAPPING.get(protocol); } else { port = DEFAULT_PORT; } } } Type type = StringUtils.startsWith(protocol, "socks") ? Type.SOCKS : Type.HTTP; return new HttpProxy(host, port, login, pass, type, protocol); } else { logger.warn("Cannot load URI [{}] as a HTTP Proxy", uri); return null; } } HttpProxy(String host, int port, String login, String pass); HttpProxy(String host, int port, String login, String pass, Type type, String protocol); HttpProxy(String host, int port); static HttpProxy fromURI(String uri); @Override OkHttpClient getClient(); String toURI(); String toString(); @Override String getHost(); static final String URI_REGEXP; }
@Test public void encodedCharUriTest() { String uri = "user:p%[email protected]:3128"; HttpProxy proxy = HttpProxy.fromURI(uri); assertThat(proxy).isNotNull(); }
SequenceAccountGenerator implements AccountGenerator { public void init() { emailGenerator = new PlusTrickEmailGenerator(baseEmail); SequenceUsernameGenerator seqUsernameGenerator = new SequenceUsernameGenerator(usernamePattern, startFrom); if (startFrom + nbAccounts > seqUsernameGenerator.getMaxSequence() + 1) { throw new IllegalArgumentException("Sequence would overflow format, use more *"); } usernameGenerator = seqUsernameGenerator; passwordGenerator = new SinglePasswordGenerator(staticPassword); initDone = true; } void init(); @Override boolean hasNext(); @Override AccountData next(); }
@Test public void maxStartAt1Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(1); generator.setNbAccounts(99); generator.init(); } @Test(expected = IllegalArgumentException.class) public void overFlowStartAt1Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(1); generator.setNbAccounts(100); generator.init(); } @Test public void maxStartAt0Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(0); generator.setNbAccounts(100); generator.init(); } @Test(expected = IllegalArgumentException.class) public void overFlowStartAt0Test() { SequenceAccountGenerator generator = getSequenceAccountGenerator(); generator.setStartFrom(0); generator.setNbAccounts(101); generator.init(); }
ImageTypersProvider extends CaptchaProvider { public ImageTypersProvider(CaptchaQueue queue, String apiKey) throws ImageTypersConfigurationException { this.queue = queue; this.apiKey = apiKey; this.captchaClient = new OkHttpClient(); if (this.apiKey == null || this.apiKey.isEmpty()) { throw new ImageTypersConfigurationException("Missing ImageTypers Access Token"); } } ImageTypersProvider(CaptchaQueue queue, String apiKey); static CaptchaProvider getInstance(CaptchaQueue queue, String apiKey); @Override void run(); double getBalance(); static final String INSUFFICIENT_BALANCE; }
@Test @Ignore public void imageTypersProviderTest() throws ImageTypersConfigurationException, InterruptedException { CaptchaQueue queue = new CaptchaQueue(new LogCaptchaCollector()); String token = prop.getProperty("imageTypers.token"); ImageTypersProvider provider = new ImageTypersProvider(queue, token); logger.info("Start Provider"); new Thread(provider).start(); logger.info("Provider Started, get Balance"); double balance = provider.getBalance(); logger.info("Balance is : {}", balance); CaptchaRequest request = queue.addRequest(new CaptchaRequest("test1")); CaptchaRequest request2 = queue.addRequest(new CaptchaRequest("test2")); while (request.getResponse() == null || request2.getResponse() == null) { Thread.sleep(500); } logger.info("Response 1 given : {}", request.getResponse()); logger.info("Response 2 given : {}", request2.getResponse()); Thread.sleep(2000); }
TwoCaptchaProvider extends CaptchaProvider { public double getBalance() throws TechnicalException, TwoCaptchaConfigurationException { Request sendRequest = buildBalanceCheckequest(); try (Response sendResponse = captchaClient.newCall(sendRequest).execute()) { String body = sendResponse.body().string(); if (body == null) { throw new TechnicalException("invalid response from 2captcha"); } if (body.startsWith(ERROR_WRONG_USER_KEY)) { throw new TwoCaptchaConfigurationException("Given 2captcha key " + apiKey + " is invalid"); } if (body.startsWith(ERROR_KEY_DOES_NOT_EXIST)) { throw new TwoCaptchaConfigurationException("Given 2captcha key does not match any account"); } if (body.startsWith(ERROR_PREFIX)) { throw new TwoCaptchaConfigurationException("Returned 2captcha Error : " + body); } try { JsonObject jsonResponse = Json.createReader(new StringReader(body)).readObject(); if (isValidResponse(jsonResponse)) { try { return Double.parseDouble(jsonResponse.getString(JSON_RESPONSE)); } catch (NumberFormatException e) { throw new TechnicalException("invalid balance from 2captcha : " + jsonResponse.getString(JSON_RESPONSE)); } } else { throw new TechnicalException("invalid response from 2captcha : " + body); } } catch (JsonParsingException e) { throw new TwoCaptchaConfigurationException("Other Error : " + body); } } catch (IOException e) { throw new TechnicalException(HTTP_ERROR_MSG, e); } } TwoCaptchaProvider(CaptchaQueue queue, String apiKey); static CaptchaProvider getInstance(CaptchaQueue queue, String apiKey); @Override void run(); void manageChallengeResponse(TwoCaptchaChallenge challenge, String response); double getBalance(); boolean isValidResponse(JsonObject jsonResponse); static final String CAPCHA_NOT_READY; static final String OK_RESPONSE_PREFIX; static final String ERROR_WRONG_USER_KEY; static final String ERROR_KEY_DOES_NOT_EXIST; static final String ERROR_ZERO_BALANCE; static final String ERROR_PREFIX; }
@Ignore @Test public void solvingTest() throws CaptchaException, TechnicalException, InterruptedException { CaptchaQueue queue = new CaptchaQueue(new LogCaptchaCollector()); String apiKey = prop.getProperty("twoCaptcha.key"); TwoCaptchaProvider provider = new TwoCaptchaProvider(queue, apiKey); logger.info("Start Provider"); new Thread(provider).start(); logger.info("Provider Started, get Balance"); double balance = provider.getBalance(); logger.info("Balance is : {}", balance); CaptchaRequest request = queue.addRequest(new CaptchaRequest("test1")); CaptchaRequest request2 = queue.addRequest(new CaptchaRequest("test2")); while (request.getResponse() == null || request2.getResponse() == null) { Thread.sleep(500); } logger.info("Response 1 given : {}", request.getResponse()); logger.info("Response 2 given : {}", request2.getResponse()); Thread.sleep(2000); }
AccountData implements Cloneable { public static String randomAdultDateOfBirth() { return randomDateOfBirth(18, 80); } AccountData(); AccountData(String username, String email, String password); AccountData(String username, String email, String password, String dob, String country); void setDob(String dob); void setCountry(String country); AccountData clone(); String toCsv(); @Override String toString(); static String randomAdultDateOfBirth(); static String randomDateOfBirth(int minAge, int maxAge); static final String DEFAULT_COUNTRY; }
@Test public void testChooseRandomDateOfBirth() { logger.debug("Checking 10 random adults DOB"); for (int i = 0; i < 10; i++) { String rdob = AccountData.randomAdultDateOfBirth(); logger.debug("Random DOB : {}", rdob); assertThat(rdob).isNotBlank(); assertThat(rdob).matches("[0-9]{4}-[0-9]{2}-[0-9]{2}"); int year = Integer.parseInt((rdob.substring(0, 4))); int month = Integer.parseInt((rdob.substring(5, 7))); int day = Integer.parseInt((rdob.substring(8, 10))); assertThat(year).isGreaterThan(1900); assertThat(month).isLessThanOrEqualTo(12); assertThat(day).isLessThanOrEqualTo(31); int age = LocalDateTime.now().getYear() - year; assertThat(age).isGreaterThanOrEqualTo(18); assertThat(age).isLessThanOrEqualTo(80); } }
PtcSession { public void checkForErrors(AccountData account, Document doc) throws FatalException, AccountRateLimitExceededException, TechnicalException, AccountDuplicateException { Elements accessDenied = doc.getElementsContainingOwnText("Access Denied"); if (!accessDenied.isEmpty()) { throw new FatalException("Access Denied"); } Elements errors = doc.select(".errorlist, div.error"); boolean isUsernameUsed = false; boolean isQuotaExceeded = false; boolean isEmailError = false; if (!errors.isEmpty()) { if (dumpResult == ON_FAILURE) { dumpResult(doc, account); } if (errors.size() == 1 && errors.get(0).child(0).text().trim().equals("This field is required.")) { throw new TechnicalException("Invalid or missing Captcha. Captcha may have expired, try reducing captchaMaxTotalTime"); } else { List<String> errorMessages = new ArrayList<>(); for (int i = 0; i < errors.size(); i++) { Element error = errors.get(i); String errorTxt = error.toString().replaceAll("<[^>]*>", "").replaceAll("[\n\r]", "").trim(); if (errorTxt.contains("username already exists")) { isUsernameUsed = true; } else if (errorTxt.contains("Account Creation Rate Limit Exceeded")) { isQuotaExceeded = true; } else if (errorTxt.contains("There is a problem with your email address")) { isEmailError = true; } errorMessages.add(errorTxt); } logger.warn("{} error(s) found creating account {} : {}", errors.size(), account.getUsername(), errorMessages); if (isUsernameUsed) { throw new AccountDuplicateException(); } if (isEmailError) { throw new EmailDuplicateOrBlockedException(); } if (isQuotaExceeded) { throw new AccountRateLimitExceededException(); } throw new TechnicalException("Unknown creation error : " + errorMessages); } } logger.debug("SUCCESS : Account created"); } PtcSession(OkHttpClient client); boolean isAccountValid(AccountData account); boolean isAccountValidWebservice(AccountData account); String sendAgeCheckAndGrabCrsfToken(AccountData account); void sendAgeCheck(AccountData account, String crsfToken); void manageError(AccountData account, Response response, Document doc, String step); void createAccount(AccountData account, String crsfToken, String captcha); void checkForErrors(AccountData account, Document doc); static Headers getHeaders(); static final int NEVER; static final int ON_FAILURE; static final int ALWAYS; }
@Test(expected = AccountRateLimitExceededException.class) public void QuotaCheck() throws IOException, FatalException, TechnicalException { PtcSession session = new PtcSession(null); try (InputStream test1 = this.getClass().getResourceAsStream("/test1.html")) { AccountData account = new AccountData("username", "email", "password"); Document doc = Jsoup.parse(test1, null, ""); session.checkForErrors(account, doc); } }
AntiCaptchaProvider extends CaptchaProvider { public double getBalance() throws AntiCaptchaConfigurationException { try { Request sendRequest = buildBalanceCheckequestGet(); Response sendResponse = captchaClient.newCall(sendRequest).execute(); BalanceResponse balance = mapper.readValue(sendResponse.body().string(), BalanceResponse.class); if (balance.getErrorId() > 0) { String errMsg = String.format("Balance Error : %s - %s", balance.getErrorCode(), balance.getErrorDescription()); throw new AntiCaptchaConfigurationException(errMsg); } return balance.getBalance(); } catch (Exception e) { throw new AntiCaptchaConfigurationException("Error getting account balance", e); } } AntiCaptchaProvider(CaptchaQueue queue, String apiKey); static CaptchaProvider getInstance(CaptchaQueue queue, String apiKey); @Override void run(); double getBalance(); static final String INSUFFICIENT_BALANCE; public String RECAPTCHA_SUBMIT_ENDPOINT; public String RECAPTCHA_RETRIEVE_ENDPOINT; public String BALANCE_ENDPOINT; @Setter public String captchaSubmitUrl; @Setter public String captchaRetrieveUrl; @Setter public String captchaBalanceUrl; }
@Test public void captchaProviderTest() throws AntiCaptchaConfigurationException, InterruptedException { if (!hasConfig) { return; } CaptchaQueue queue = new CaptchaQueue(new LogCaptchaCollector()); String token = prop.getProperty("anticaptcha.token"); AntiCaptchaProvider provider = new AntiCaptchaProvider(queue, token); logger.info("Start Provider"); new Thread(provider).start(); logger.info("Provider Started, get Balance"); double balance = provider.getBalance(); logger.info("Balance is : {}", balance); CaptchaRequest request = queue.addRequest(new CaptchaRequest("test1")); CaptchaRequest request2 = queue.addRequest(new CaptchaRequest("test2")); while (request.getResponse() == null || request2.getResponse() == null) { Thread.sleep(500); } logger.info("Response 1 given : {}", request.getResponse()); logger.info("Response 2 given : {}", request2.getResponse()); Thread.sleep(2000); }
ToFileLinkActivator implements LinkActivator { @Override public boolean activateLink(Activation link) { FileLogger.logStatus(link, FileLogger.SKIPPED); return true; } @Override boolean activateLink(Activation link); @Override void start(); }
@Test public void testActivateLink() { ToFileLinkActivator activator = new ToFileLinkActivator(); activator.activateLink(new Activation("Test", "[email protected]")); }
PasswordProviderFactory { public static PasswordProvider getPasswordProvider(Properties config) { List<MatchingPair> mapping = new ArrayList<>(); String csvConfig = config.getProperty(CSV_CONFIG); if(StringUtils.isNotEmpty(csvConfig)) { CsvPasswordReader csvReader = new CsvPasswordReader(); mapping.addAll(csvReader.load(csvConfig)); } String mappingConfig = config.getProperty(MAPPING_CONFIG); if(StringUtils.isNotEmpty(mappingConfig)) { String[] configs = mappingConfig.split("\\|\\|"); for (String sConfig : configs) { if(!sConfig.contains(":")){ log.error("Invalid mapping config [{}] => skip", sConfig); } else { String[] data = sConfig.split(":"); mapping.add(new MatchingPair(new RegexEmailMatcher(data[0]), data[1])); } } } String staticConfig = config.getProperty(STATIC_CONFIG); if(StringUtils.isNotEmpty(staticConfig)) { mapping.add(new MatchingPair(new AnyEmailMatcher(), staticConfig)); } MatcherPasswordProvider provider = new MatcherPasswordProvider(); provider.setMatchingPairs(mapping); return provider; } static PasswordProvider getPasswordProvider(Properties config); }
@Test public void getStaticPasswordProvider() { Properties config = new Properties(); config.setProperty("emailChanger.password.static", "static"); PasswordProvider factory = PasswordProviderFactory.getPasswordProvider(config); assertThat(factory.getPassword("anything")).isEqualTo("static"); } @Test public void getCsvPasswordProvider() { Properties config = new Properties(); config.setProperty("emailChanger.password.csv", "accounts.example.csv"); PasswordProvider factory = PasswordProviderFactory.getPasswordProvider(config); assertThat(factory.getPassword("[email protected]")).isEqualTo("testAA123+"); assertThat(factory.getPassword("[email protected]")).isEqualTo("testAA456+"); assertThat(factory.getPassword("anything")).isNull(); } @Test public void getRegexPasswordProvider() { Properties config = new Properties(); config.setProperty("emailChanger.password.mapping", "aaaaa.*@domain.com:pass1||bbbbb[0-9]+@.*:pass2"); PasswordProvider factory = PasswordProviderFactory.getPasswordProvider(config); assertThat(factory.getPassword("[email protected]")).isEqualTo("pass1"); assertThat(factory.getPassword("[email protected]")).isEqualTo("pass1"); assertThat(factory.getPassword("[email protected]")).isEqualTo("pass2"); assertThat(factory.getPassword("anything")).isNull(); assertThat(factory.getPassword("[email protected]")).isNull(); assertThat(factory.getPassword("[email protected]")).isNull(); } @Test public void getFullPasswordProvider() { Properties config = new Properties(); config.setProperty("emailChanger.password.csv", "accounts.example.csv"); config.setProperty("emailChanger.password.mapping", "aaaaa.*@domain.com:pass1||bbbbb[0-9]+@.*:pass2"); config.setProperty("emailChanger.password.static", "static"); PasswordProvider factory = PasswordProviderFactory.getPasswordProvider(config); assertThat(factory.getPassword("[email protected]")).isEqualTo("testAA123+"); assertThat(factory.getPassword("[email protected]")).isEqualTo("testAA456+"); assertThat(factory.getPassword("[email protected]")).isEqualTo("pass1"); assertThat(factory.getPassword("[email protected]")).isEqualTo("pass1"); assertThat(factory.getPassword("[email protected]")).isEqualTo("pass2"); assertThat(factory.getPassword("anything")).isEqualTo("static"); assertThat(factory.getPassword("[email protected]")).isEqualTo("static"); assertThat(factory.getPassword("[email protected]")).isEqualTo("static"); }
AppServerConfig implements ServerConfig { @Override public MetricsListener metricsListener() { return guiceValues.metricsListener; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void constructor_calls_initServerConfigMetrics_on_metricsListener() { AppServerConfig asc = new AppServerConfig(configForTesting); assertThat(((CodahaleMetricsListener) asc.metricsListener()).getEndpointRequestsTimers()).isNotEmpty(); } @Test public void constructor_does_not_blow_up_if_metricsListener_is_null() { AppServerConfig asc = new AppServerConfig(configForTesting) { @Override protected List<Module> getAppGuiceModules(Config appConfig) { return Arrays.asList( Modules.override(new AppGuiceModule(appConfig)).with( binder -> binder .bind(new TypeLiteral<CodahaleMetricsListener>() {}) .toProvider(Providers.of(null))), new BackstopperRiposteConfigGuiceModule() ); } }; assertThat(asc.metricsListener()).isNull(); } @Test public void metricsListener_returns_non_null_object() { MetricsListener obj = appServerConfig.metricsListener(); assertThat(obj).isNotNull(); } @Test public void metricsListener_returns_null_object_if_no_metrics_reporters_are_enabled() { Config configNoReporters = TypesafeConfigUtil.loadConfigForAppIdAndEnvironment(APP_ID, "compiletimetest") .withValue("metrics.slf4j.reporting.enabled", ConfigValueFactory.fromAnyRef(false)) .withValue("metrics.graphite.reporting.enabled", ConfigValueFactory.fromAnyRef(false)) .withValue("metrics.jmx.reporting.enabled", ConfigValueFactory.fromAnyRef(false)); AppServerConfig asc = new AppServerConfig(configNoReporters); MetricsListener obj = asc.metricsListener(); assertThat(obj).isNull(); }
AppGuiceModule extends AbstractModule { @Provides @Singleton public CodahaleMetricsEngine codahaleMetricsEngine(@Nullable CodahaleMetricsCollector cmc, @Nullable List<ReporterFactory> reporters, @Named("metrics.reportJvmMetrics") boolean reportJvmMetrics) { if (cmc == null) return null; if (reporters == null) reporters = Collections.emptyList(); CodahaleMetricsEngine engine = new CodahaleMetricsEngine(cmc, reporters); if (reportJvmMetrics) engine.reportJvmMetrics(); engine.start(); return engine; } AppGuiceModule(Config appConfig); @Provides @Singleton @Named("appEndpoints") Set<Endpoint<?>> appEndpoints( HealthCheckEndpoint healthCheckEndpoint, // TODO: EXAMPLE CLEANUP - Remove these example endpoints from this method's arguments and don't return them from this method. ExampleEndpoint.Get exampleEndpointGet, ExampleEndpoint.Post exampleEndpointPost, ExampleCassandraAsyncEndpoint exampleCassandraAsyncEndpoint, ExampleDownstreamHttpAsyncEndpoint exampleDownstreamHttpAsyncEndpoint, ExampleProxyRouterEndpoint exampleProxyRouterEndpoint, ExampleBasicAuthProtectedEndpoint.Get exampleBasicAuthProtectedEndpointGet, ExampleBasicAuthProtectedEndpoint.Post exampleBasicAuthProtectedEndpointPost ); @Provides @Singleton Validator validator(); @Provides @Singleton ProjectApiErrors projectApiErrors(); @Provides @Singleton AsyncHttpClientHelper asyncHttpClientHelper(); @Provides @Singleton CodahaleMetricsListener metricsListener(@Nullable CodahaleMetricsCollector metricsCollector, @Nullable CodahaleMetricsEngine engine); @Provides @Singleton CodahaleMetricsEngine codahaleMetricsEngine(@Nullable CodahaleMetricsCollector cmc, @Nullable List<ReporterFactory> reporters, @Named("metrics.reportJvmMetrics") boolean reportJvmMetrics); @Provides @Singleton CodahaleMetricsCollector codahaleMetricsCollector(@Nullable List<ReporterFactory> reporters); @Provides @Singleton List<ReporterFactory> metricsReporters( @Named("metrics.slf4j.reporting.enabled") boolean slf4jReportingEnabled, @Named("metrics.jmx.reporting.enabled") boolean jmxReportingEnabled, @Named("metrics.graphite.url") String graphiteUrl, @Named("metrics.graphite.port") int graphitePort, @Named("metrics.graphite.reporting.enabled") boolean graphiteEnabled, @Named("appInfoFuture") CompletableFuture<AppInfo> appInfoFuture ); @Provides @Singleton @Named("basicAuthProtectedEndpoints") List<Endpoint<?>> basicAuthProtectedEndpoints(@Named("appEndpoints") Set<Endpoint<?>> endpoints); @Provides @Singleton BasicAuthSecurityValidator basicAuthSecurityValidator( @Named("basicAuthProtectedEndpoints") List<Endpoint<?>> basicAuthProtectedEndpoints, @Named("exampleBasicAuth.username") String basicAuthUsername, @Named("exampleBasicAuth.password") String basicAuthPassword ); @Provides @Singleton @Named("appInfoFuture") CompletableFuture<AppInfo> appInfoFuture(AsyncHttpClientHelper asyncHttpClientHelper); }
@Test public void codahaleMetricsEngine_gracefully_handles_null_reporters_list() { CodahaleMetricsCollector cmc = new CodahaleMetricsCollector(); CodahaleMetricsEngine engine = appGuiceModule.codahaleMetricsEngine(cmc, null, false); assertThat((Collection<ReporterFactory>)Whitebox.getInternalState(engine, "reporters")).isEmpty(); assertThat(Whitebox.getInternalState(engine, "started")).isEqualTo(true); }
HealthCheckEndpoint extends StandardEndpoint<Void, Void> { @Override public Matcher requestMatcher() { return matcher; } @Override CompletableFuture<ResponseInfo<Void>> execute( RequestInfo<Void> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx ); @Override Matcher requestMatcher(); }
@Test public void healthCheckEndpoint_should_match_all_http_methods() { assertThat(healthCheckEndpoint.requestMatcher().isMatchAllMethods()).isTrue(); }
HealthCheckEndpoint extends StandardEndpoint<Void, Void> { @Override public CompletableFuture<ResponseInfo<Void>> execute( RequestInfo<Void> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx ) { return CompletableFuture.completedFuture(ResponseInfo.<Void>newBuilder().withHttpStatusCode(200).build()); } @Override CompletableFuture<ResponseInfo<Void>> execute( RequestInfo<Void> request, Executor longRunningTaskExecutor, ChannelHandlerContext ctx ); @Override Matcher requestMatcher(); }
@Test public void healthCheckEndpoint_should_always_return_http_status_code_200() { CompletableFuture<ResponseInfo<Void>> responseFuture = healthCheckEndpoint.execute(null, null, null); ResponseInfo<Void> responseInfo = responseFuture.join(); assertThat(responseInfo.getHttpStatusCode()).isEqualTo(200); }
AppServerConfig implements ServerConfig { @Override public AccessLogger accessLogger() { return accessLogger; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void accessLogger_returns_non_null_object() { AccessLogger obj = appServerConfig.accessLogger(); assertThat(obj).isNotNull(); }
AppServerConfig implements ServerConfig { @Override public CompletableFuture<AppInfo> appInfo() { return guiceValues.appInfoFuture; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void appInfo_returns_non_null_object() { CompletableFuture<AppInfo> obj = appServerConfig.appInfo(); assertThat(obj).isNotNull(); assertThat(obj.join()).isNotNull(); }
AppServerConfig implements ServerConfig { @Override public RequestSecurityValidator requestSecurityValidator() { return guiceValues.basicAuthSecurityValidator; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void requestSecurityValidator_returns_a_BasicAuthSecurityValidator() { AppServerConfig asc = new AppServerConfig(configForTesting); assertThat(asc.requestSecurityValidator()) .isNotNull() .isInstanceOf(BasicAuthSecurityValidator.class); }
AppServerConfig implements ServerConfig { @Override public boolean isDebugActionsEnabled() { return guiceValues.debugActionsEnabled; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void isDebugActionsEnabled_comes_from_config() { assertThat(appServerConfig.isDebugActionsEnabled()) .isEqualTo(configForTesting.getBoolean("debugActionsEnabled")); }
AppServerConfig implements ServerConfig { @Override public int endpointsPort() { return guiceValues.endpointsPort; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void endpointsPort_comes_from_config() { assertThat(appServerConfig.endpointsPort()).isEqualTo(configForTesting.getInt("endpoints.port")); }
AppServerConfig implements ServerConfig { @Override public int endpointsSslPort() { return guiceValues.endpointsSslPort; } protected AppServerConfig(Config appConfig, PropertiesRegistrationGuiceModule propertiesRegistrationGuiceModule); AppServerConfig(Config appConfig); @Override AccessLogger accessLogger(); @Override CompletableFuture<AppInfo> appInfo(); @Override MetricsListener metricsListener(); @Override RequestSecurityValidator requestSecurityValidator(); @Override Collection<Endpoint<?>> appEndpoints(); @Override RiposteErrorHandler riposteErrorHandler(); @Override RiposteUnhandledErrorHandler riposteUnhandledErrorHandler(); @Override RequestValidator requestContentValidationService(); @Override boolean isDebugActionsEnabled(); @Override boolean isDebugChannelLifecycleLoggingEnabled(); @Override int endpointsPort(); @Override int endpointsSslPort(); @Override boolean isEndpointsUseSsl(); @Override int numBossThreads(); @Override int numWorkerThreads(); @Override int maxRequestSizeInBytes(); }
@Test public void endpointsSslPort_comes_from_config() { assertThat(appServerConfig.endpointsSslPort()).isEqualTo(configForTesting.getInt("endpoints.sslPort")); }
FacesResourceProcessor { public static byte[] execute(URL url, InputStream input, String encoding) throws IOException { byte[] bytes; try { StringBuilder sb = new StringBuilder(); UnicodeReader reader = new UnicodeReader(input, encoding); try { char[] cbuf = new char[32]; int r; while ((r = reader.read(cbuf, 0, 32)) != -1) { sb.append(cbuf, 0, r); } String str = sb.toString(); if (!str.contains("ui:component")) { try { String fileEncoding = reader.getEncoding(); InputSource is = new InputSource(new StringReader(str)); is.setEncoding(fileEncoding); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLDocumentFilter[] filters = { new Writer(baos, fileEncoding) { protected void printStartElement(QName element, XMLAttributes attributes) { fPrinter.print('<'); fPrinter.print(element.rawname); int attrCount = attributes != null ? attributes.getLength() : 0; for (int i = 0; i < attrCount; i++) { String aname = attributes.getQName(i); String avalue = attributes.getValue(i); fPrinter.print(' '); fPrinter.print(aname); fPrinter.print("=\""); printAttributeValue(avalue); fPrinter.print('"'); } if (HTMLElements.getElement(element.rawname).isEmpty()) { fPrinter.print(' '); fPrinter.print('/'); } fPrinter.print('>'); fPrinter.flush(); } protected void printAttributeValue(String text) { fPrinter.print(StringEscapeUtils.escapeHtml(text)); fPrinter.flush(); } protected void printEntity(String name) { fPrinter.print('&'); fPrinter.print('#'); fPrinter.print(HTMLEntities.get(name)); fPrinter.print(';'); fPrinter.flush(); } }}; DOMParser parser = new DOMParser(); parser.setFeature("http: parser.setFeature("http: parser.setProperty("http: parser.setProperty("http: parser.setProperty("http: parser.parse(is); str = "<!DOCTYPE html>" + baos.toString(fileEncoding); } catch (Exception e) { logger.error(e.getMessage(), e); } if (url.getFile().contains("META-INF/templates")) { str = "<ui:component xmlns:ui=\"http: Pattern.compile("(<\\!DOCTYPE html>)|(</?html[^>]*>)|(<title>[^<]*</title>)", Pattern.CASE_INSENSITIVE).matcher(str).replaceAll("").replaceAll( "\\$\\{template\\.body\\}", "<ui:insert />") + "</ui:component>"; } } bytes = str.getBytes(reader.getEncoding()); } finally { reader.close(); } } catch (IOException e) { throw e; } return bytes; } static byte[] execute(URL url, InputStream input, String encoding); }
@Test public void testPage() throws FileNotFoundException, IOException { URL url; byte[] bytes; String encoding = (String) ResourceUtils.getProperty("app.encoding"); url = ResourceUtils.getClasspathResource("META-INF/pages/index.html"); bytes = FacesResourceProcessor.execute(url, url.openConnection().getInputStream(), encoding); assertEquals( "<!DOCTYPE html>\n" + "<html>\n" + " \n" + " <title>${messages.page.welcome}</title>\n" + " \n" + " <script>\n" + " function getWelcomeKey() {\n" + " return \"Welcome Key\";\n" + " }\n" + " </script>\n" + " \n" + " <script type=\"text/expression\">\n" + " function getWelcomeKey() {\n" + " return 'page'.concat('.' + 'welcome');\n" + " }\n" + " </script>\n" + " \n" + " <h1><a href=\"http: " \n" + " <p>&#169; 2010-2011 Asual DZZD</p>\n" + " \n" + "</html>", new String(bytes, encoding).replaceAll(System.getProperty("line.separator"), "\n")); }
PropertyResource extends AbstractResource implements BeanFactoryPostProcessor { public Object getProperty(String key) { return eppc.getProperty(key); } PropertyResource(); Object getProperty(String key); void setIgnoreResourceNotFound(boolean ignoreResourceNotFound); void setLocation(String location); void setLocations(String[] locations); void setLocations(List<String> locations); void setWildcardLocations(String[] locations); void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory); Resource[] getResources(); }
@Test public void testOrder(){ assertEquals(10, ((Integer) ResourceUtils.getProperty("test")).intValue()); }
RESTAPICallPreHandler implements APICallPreHandler { public URL getBaseURL() throws MalformedURLException { if (url == null) { String mode = this.configurationMap.get(Constants.MODE); String urlString = this.configurationMap.get(Constants.ENDPOINT); if (urlString == null || urlString.trim().isEmpty()) { if (Constants.SANDBOX.equalsIgnoreCase(mode)) { urlString = Constants.REST_SANDBOX_ENDPOINT; } else if (Constants.LIVE.equalsIgnoreCase(mode)) { urlString = Constants.REST_LIVE_ENDPOINT; } } if (urlString == null || urlString.trim().length() <= 0) { throw new MalformedURLException( "service.EndPoint not set (OR) mode not configured to sandbox/live "); } if (!urlString.endsWith("/")) { urlString += "/"; } url = new URL(urlString); } return url; } RESTAPICallPreHandler(Map<String, String> configurationMap); RESTAPICallPreHandler(Map<String, String> configurationMap, Map<String, String> headersMap); void setAuthorizationToken(String authorizationToken); void setResourcePath(String resourcePath); void setRequestId(String requestId); void setPayLoad(String payLoad); void setSdkVersion(SDKVersion sdkVersion); Map<String, String> getHeaderMap(); String getPayLoad(); String getEndPoint(); OAuthTokenCredential getCredential(); void validate(); URL getBaseURL(); void setUrl(String urlString); Map<String, String> getConfigurationMap(); }
@Test public void getBaseURL_returnsServiceEndpointIfSet() throws MalformedURLException { Map<String, String> configurations = new HashMap<String, String>(); configurations.put(Constants.ENDPOINT, "https: RESTAPICallPreHandler restapiCallPreHandler = new RESTAPICallPreHandler(configurations); URL result = restapiCallPreHandler.getBaseURL(); assertNotNull(result); assertEquals(result.getHost(), "www.example.com"); assertEquals(result.getPath(), "/abc/"); } @Test public void getBaseURL_usesModeEndpointIfServiceEndpointNotSet() throws MalformedURLException { Map<String, String> configurations = new HashMap<String, String>(); configurations.put(Constants.MODE, "sandbox"); RESTAPICallPreHandler restapiCallPreHandler = new RESTAPICallPreHandler(configurations); URL result = restapiCallPreHandler.getBaseURL(); assertNotNull(result); assertEquals(result.getHost(), "api.sandbox.paypal.com"); assertEquals(result.getPath(), "/"); } @Test(expectedExceptions = MalformedURLException.class, expectedExceptionsMessageRegExp = "service\\.EndPoint not set \\(OR\\) mode not configured to sandbox\\/live ") public void getBaseURL_throwsExceptionIfBothModeAndServiceEndpointNotSet() throws MalformedURLException { Map<String, String> configurations = new HashMap<String, String>(); RESTAPICallPreHandler restapiCallPreHandler = new RESTAPICallPreHandler(configurations); restapiCallPreHandler.getBaseURL(); }
RESTUtil { public static String formatURIPath(String pattern, Object[] parameters) { String formattedPath = null; Object[] finalParameters = null; if (pattern != null) { if (parameters != null && parameters.length == 1 && parameters[0] instanceof CreateFromAuthorizationCodeParameters) { finalParameters = splitParameters(pattern, ((CreateFromAuthorizationCodeParameters) parameters[0]) .getContainerMap()); } else if (parameters != null && parameters.length == 1 && parameters[0] instanceof CreateFromRefreshTokenParameters) { finalParameters = splitParameters(pattern, ((CreateFromRefreshTokenParameters) parameters[0]) .getContainerMap()); } else if (parameters != null && parameters.length == 1 && parameters[0] instanceof UserinfoParameters) { finalParameters = splitParameters(pattern, ((UserinfoParameters) parameters[0]).getContainerMap()); } else if (parameters != null && parameters.length == 1 && parameters[0] instanceof QueryParameters) { finalParameters = splitParameters(pattern, ((QueryParameters) parameters[0]).getContainerMap()); } else if (parameters != null && parameters.length == 1 && parameters[0] instanceof Map<?, ?>) { finalParameters = splitParameters(pattern, ((Map<?, ?>) parameters[0])); } else { finalParameters = parameters; } String fString = MessageFormat.format(pattern, finalParameters); formattedPath = removeNullsInQS(fString); } return formattedPath; } private RESTUtil(); static String formatURIPath(String pattern, Object[] parameters); static String formatURIPath(String pattern, Map<String, String> pathParameters); static String formatURIPath(String pattern, Map<String, String> queryParameters, String... pathParameters); static String formatURIPath(String pattern, Map<String, String> pathParameters, Map<String, String> queryParameters); }
@Test(dependsOnMethods = { "testFormatURIPathTwoQS" }) public void testFormatURIPathMap() throws PayPalRESTException { String pattern = "/a/b/{first}/{second}"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("first", "value1"); pathParameters.put("second", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters); Assert.assertEquals(uriPath, "/a/b/value1/value2"); } @Test(dependsOnMethods = { "testFormatURIPathMap" }) public void testFormatURIPathMapTraillingSlash() throws PayPalRESTException { String pattern = "/a/b/{first}/{second}/"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("first", "value1"); pathParameters.put("second", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters); Assert.assertEquals(uriPath, "/a/b/value1/value2/"); } @Test(dependsOnMethods = { "testFormatURIPathMapTraillingSlash" }) public void testFormatURIPathMapNullMap() throws PayPalRESTException { String pattern = "/a/b/first/second"; String uriPath = RESTUtil.formatURIPath(pattern, (Map<String, String>) null); Assert.assertEquals(uriPath, "/a/b/first/second"); } @Test(dependsOnMethods = { "testFormatURIPathMapNullMap" }) public void testFormatURIPathMapIncorrectMap() throws PayPalRESTException { String pattern = "/a/b/first/second"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("invalid1", "value1"); pathParameters.put("invalid2", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters); Assert.assertEquals(uriPath, "/a/b/first/second"); } @Test(dependsOnMethods = { "testFormatURIPathMapIncorrectMap" }, expectedExceptions = PayPalRESTException.class) public void testFormatURIPathMapInsufficientMap() throws PayPalRESTException { String pattern = "/a/b/{first}/{second}"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("first", "value1"); RESTUtil.formatURIPath(pattern, pathParameters); } @Test(dependsOnMethods = { "testFormatURIPathMapInsufficientMap" }) public void testFormatURIPathMapNullQueryMap() throws PayPalRESTException { String pattern = "/a/b/{first}/{second}"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("first", "value1"); pathParameters.put("second", "value2"); Map<String, String> queryParameters = null; String uriPath = RESTUtil.formatURIPath(pattern, pathParameters, queryParameters); Assert.assertEquals(uriPath, "/a/b/value1/value2"); } @Test(dependsOnMethods = { "testFormatURIPathMapNullQueryMap" }) public void testFormatURIPathMapEmptyQueryMap() throws PayPalRESTException { String pattern = "/a/b/{first}/{second}"; Map<String, String> pathParameters = new HashMap<String, String>(); pathParameters.put("first", "value1"); pathParameters.put("second", "value2"); Map<String, String> queryParameters = new HashMap<String, String>(); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters, queryParameters); Assert.assertEquals(uriPath, "/a/b/value1/value2"); } @Test(dependsOnMethods = { "testFormatURIPathMapEmptyQueryMap" }) public void testFormatURIPathMapQueryMap() throws PayPalRESTException { String pattern = "/a/b/first/second"; Map<String, String> pathParameters = new HashMap<String, String>(); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("query1", "value1"); queryParameters.put("query2", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters, queryParameters); Assert.assertEquals(uriPath, "/a/b/first/second?query1=value1&query2=value2&"); } @Test(dependsOnMethods = { "testFormatURIPathMapQueryMap" }) public void testFormatURIPathMapQueryMapQueryURIPath() throws PayPalRESTException { String pattern = "/a/b/first/second?"; Map<String, String> pathParameters = new HashMap<String, String>(); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("query1", "value1"); queryParameters.put("query2", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters, queryParameters); Assert.assertEquals(uriPath, "/a/b/first/second?query1=value1&query2=value2&"); } @Test(dependsOnMethods = { "testFormatURIPathMapQueryMapQueryURIPath" }) public void testFormatURIPathMapQueryMapQueryURIPathEncode() throws PayPalRESTException { String pattern = "/a/b/first/second"; Map<String, String> pathParameters = new HashMap<String, String>(); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("query1", "value&1"); queryParameters.put("query2", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters, queryParameters); Assert.assertEquals(uriPath, "/a/b/first/second?query1=value%261&query2=value2&"); } @Test(dependsOnMethods = { "testFormatURIPathMapQueryMapQueryURIPathEncode" }) public void testFormatURIPathMapQueryMapQueryValueURIPath() throws PayPalRESTException { String pattern = "/a/b/first/second?alreadypresent=value"; Map<String, String> pathParameters = new HashMap<String, String>(); Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("query1", "value1"); queryParameters.put("query2", "value2"); String uriPath = RESTUtil.formatURIPath(pattern, pathParameters, queryParameters); Assert.assertEquals(uriPath, "/a/b/first/second?alreadypresent=value&query1=value1&query2=value2&"); } @Test() public void testFormatURIPathForNull() { String nullString = RESTUtil.formatURIPath((String) null, (Object[]) null); Assert.assertNull(nullString); } @Test(dependsOnMethods = { "testFormatURIPathForNull" }) public void testFormatURIPathNoPattern() { String pattern = "/a/b/c"; String uriPath = RESTUtil.formatURIPath(pattern, (Object[]) null); Assert.assertEquals(uriPath, pattern); } @Test(dependsOnMethods = { "testFormatURIPathNoPattern" }) public void testFormatURIPathNoQS() { String pattern = "/a/b/{0}"; Object[] parameters = new Object[] { "replace" }; String uriPath = RESTUtil.formatURIPath(pattern, parameters); Assert.assertEquals(uriPath, "/a/b/replace"); } @Test(dependsOnMethods = { "testFormatURIPathNoQS" }) public void testFormatURIPath() { String pattern = "/a/b/{0}?name={1}"; Object[] parameters = new Object[] { "replace", "nameValue" }; String uriPath = RESTUtil.formatURIPath(pattern, parameters); Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue"); } @Test(dependsOnMethods = { "testFormatURIPath" }) public void testFormatURIPathWithNull() { String pattern = "/a/b/{0}?name={1}&age={2}"; Object[] parameters = new Object[] { "replace", "nameValue", null }; String uriPath = RESTUtil.formatURIPath(pattern, parameters); Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue"); } @Test(dependsOnMethods = { "testFormatURIPathWithNull" }) public void testFormatURIPathWithEmpty() { String pattern = "/a/b/{0}?name={1}&age="; Object[] parameters = new Object[] { "replace", "nameValue", null }; String uriPath = RESTUtil.formatURIPath(pattern, parameters); Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue"); } @Test(dependsOnMethods = { "testFormatURIPathWithEmpty" }) public void testFormatURIPathTwoQS() { String pattern = "/a/b/{0}?name={1}&age={2}"; Object[] parameters = new Object[] { "replace", "nameValue", "1" }; String uriPath = RESTUtil.formatURIPath(pattern, parameters); Assert.assertEquals(uriPath, "/a/b/replace?name=nameValue&age=1"); }
SSLUtil { public static SSLContext getSSLContext(KeyManager[] keymanagers) throws SSLConfigurationException { try { SSLContext ctx = null; String protocol = CONFIG_MAP.get(Constants.SSLUTIL_PROTOCOL); try { ctx = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e) { log.warn("WARNING: Your system does not support TLSv1.2. Per PCI Security Council mandate (https: ctx = SSLContext.getInstance(protocol); } ctx.init(keymanagers, null, null); return ctx; } catch (Exception e) { throw new SSLConfigurationException(e.getMessage(), e); } } static SSLContext getSSLContext(KeyManager[] keymanagers); static SSLContext setupClientSSL(String certPath, String certPassword); static boolean validateCertificateChain(Collection<X509Certificate> clientCerts, Collection<X509Certificate> trustCerts, String authType); static InputStream downloadCertificateFromPath(String urlPath); static InputStream downloadCertificateFromPath(String urlPath, Map<String, String> configurations); @SuppressWarnings("unchecked") static Collection<X509Certificate> getCertificateFromStream(InputStream stream); static long crc32(String data); static Boolean validateData(Collection<X509Certificate> clientCerts, String algo, String actualSignatureEncoded, String expectedSignature, String requestBody, String webhookId); }
@Test public void getSSLContextTest() throws SSLConfigurationException { Assert.assertNotNull(SSLUtil.getSSLContext(null)); }
SSLUtil { public static SSLContext setupClientSSL(String certPath, String certPassword) throws SSLConfigurationException { SSLContext sslContext = null; try { KeyStore ks = p12ToKeyStore(certPath, certPassword); KMF.init(ks, certPassword.toCharArray()); sslContext = getSSLContext(KMF.getKeyManagers()); } catch (NoSuchAlgorithmException e) { throw new SSLConfigurationException(e.getMessage(), e); } catch (KeyStoreException e) { throw new SSLConfigurationException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new SSLConfigurationException(e.getMessage(), e); } catch (CertificateException e) { throw new SSLConfigurationException(e.getMessage(), e); } catch (NoSuchProviderException e) { throw new SSLConfigurationException(e.getMessage(), e); } catch (IOException e) { throw new SSLConfigurationException(e.getMessage(), e); } return sslContext; } static SSLContext getSSLContext(KeyManager[] keymanagers); static SSLContext setupClientSSL(String certPath, String certPassword); static boolean validateCertificateChain(Collection<X509Certificate> clientCerts, Collection<X509Certificate> trustCerts, String authType); static InputStream downloadCertificateFromPath(String urlPath); static InputStream downloadCertificateFromPath(String urlPath, Map<String, String> configurations); @SuppressWarnings("unchecked") static Collection<X509Certificate> getCertificateFromStream(InputStream stream); static long crc32(String data); static Boolean validateData(Collection<X509Certificate> clientCerts, String algo, String actualSignatureEncoded, String expectedSignature, String requestBody, String webhookId); }
@Test public void setupClientSSLTest() throws SSLConfigurationException { Assert.assertNotNull(SSLUtil.setupClientSSL( UnitTestConstants.CERT_PATH, UnitTestConstants.CERT_PASSWORD)); } @Test(expectedExceptions = SSLConfigurationException.class) public void setupClientSSLExceptionTest() throws Exception { Assert.assertNotNull(SSLUtil.setupClientSSL("src/sdk_cert.p12", UnitTestConstants.CERT_PASSWORD)); } @Test(expectedExceptions = SSLConfigurationException.class) public void setupClientSSLNoSuchKeyExceptionTest() throws Exception { Assert.assertNotNull(SSLUtil.setupClientSSL("src/sdk_cert.p12", null)); }
ConnectionManager { public HttpConnection getConnection() { if(customSslContext != null) { return new DefaultHttpConnection(customSslContext); } else { return new DefaultHttpConnection(); } } private ConnectionManager(); static ConnectionManager getInstance(); HttpConnection getConnection(); HttpConnection getConnection(HttpConfiguration httpConfig); void configureCustomSslContext(SSLContext sslContext); }
@Test public void getConnectionTest() { Assert.assertNotNull(http); } @Test public void getConnectionWithHttpConfigurationForGoogleAppEngineTest() { HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setGoogleAppEngine(true); Assert.assertEquals(conn.getConnection(httpConfig).getClass(), GoogleAppEngineHttpConnection.class); }
HttpConnection { public abstract void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration) throws IOException; HttpConnection(); Map<String, List<String>> getResponseHeaderMap(); String execute(String url, String payload, Map<String, String> headers); InputStream executeWithStream(String url, String payload, Map<String, String> headers); abstract void setupClientSSL(String certPath, String certKey); abstract void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }
@Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); connection.createAndconfigureHttpConnection(httpConfiguration); }
HttpConnection { public String execute(String url, String payload, Map<String, String> headers) throws InvalidResponseDataException, IOException, InterruptedException, HttpErrorException { BufferedReader reader; String successResponse; InputStream result = executeWithStream(url, payload, headers); reader = new BufferedReader(new InputStreamReader(result, Constants.ENCODING_FORMAT)); successResponse = read(reader); return successResponse; } HttpConnection(); Map<String, List<String>> getResponseHeaderMap(); String execute(String url, String payload, Map<String, String> headers); InputStream executeWithStream(String url, String payload, Map<String, String> headers); abstract void setupClientSSL(String certPath, String certKey); abstract void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }
@Test public void executeTest() throws InvalidResponseDataException, HttpErrorException, ClientActionRequiredException, IOException, InterruptedException { httpConfiguration .setEndPointUrl("https: connection.createAndconfigureHttpConnection(httpConfiguration); String response = connection.execute("url", "payload", null); Assert.assertTrue(response.contains("<ack>Failure</ack>")); }
ConfigManager { public void load(InputStream is) throws IOException { properties = new Properties(); properties.load(is); if (!propertyLoaded) { setPropertyLoaded(true); } } private ConfigManager(); static ConfigManager getInstance(); static Properties getDefaultProperties(); static Map<String, String> getDefaultSDKMap(); static Properties combineDefaultProperties( Properties receivedProperties); void load(InputStream is); void load(Properties properties); Map<String, String> getConfigurationMap(); String getValue(String key); String getValueWithDefault(String key, String defaultValue); Map<String, String> getValuesByCategory(String category); Set<String> getNumOfAcct(); boolean isPropertyLoaded(); }
@Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void loadTest(ConfigManager conf) { Assert.assertEquals(conf.isPropertyLoaded(), true); }
ConfigManager { public Map<String, String> getValuesByCategory(String category) { String key; HashMap<String, String> map = new HashMap<String, String>(); for (Object obj : properties.keySet()) { key = (String) obj; if (key.contains(category)) { map.put(key, properties.getProperty(key)); } } return map; } private ConfigManager(); static ConfigManager getInstance(); static Properties getDefaultProperties(); static Map<String, String> getDefaultSDKMap(); static Properties combineDefaultProperties( Properties receivedProperties); void load(InputStream is); void load(Properties properties); Map<String, String> getConfigurationMap(); String getValue(String key); String getValueWithDefault(String key, String defaultValue); Map<String, String> getValuesByCategory(String category); Set<String> getNumOfAcct(); boolean isPropertyLoaded(); }
@Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void getValuesByCategoryTest(ConfigManager conf) { Map<String, String> map = conf.getValuesByCategory("acct"); Iterator<String> itr = map.keySet().iterator(); while (itr.hasNext()) { assert (((String) itr.next()).contains("acct")); } }
ConfigManager { public Set<String> getNumOfAcct() { String key; Set<String> set = new HashSet<String>(); for (Object obj : properties.keySet()) { key = (String) obj; if (key.contains("acct")) { int pos = key.indexOf('.'); String acct = key.substring(0, pos); set.add(acct); } } return set; } private ConfigManager(); static ConfigManager getInstance(); static Properties getDefaultProperties(); static Map<String, String> getDefaultSDKMap(); static Properties combineDefaultProperties( Properties receivedProperties); void load(InputStream is); void load(Properties properties); Map<String, String> getConfigurationMap(); String getValue(String key); String getValueWithDefault(String key, String defaultValue); Map<String, String> getValuesByCategory(String category); Set<String> getNumOfAcct(); boolean isPropertyLoaded(); }
@Test(dataProvider = "configParams", dataProviderClass = DataProviderClass.class) public void getNumOfAcctTest(ConfigManager conf) { Set<String> set = conf.getNumOfAcct(); Iterator<String> itr = set.iterator(); while (itr.hasNext()) { assert (((String) itr.next()).contains("acct")); } }
HttpConfiguration { public int getConnectionTimeout() { return connectionTimeout; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 0) public void getConnectionTimeoutTest() { Assert.assertEquals(httpConf.getConnectionTimeout(), 0); }
HttpConfiguration { public String getEndPointUrl() { return endPointUrl; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 1) public void getEndPointUrlTest() { Assert.assertEquals(httpConf.getEndPointUrl(), null); }
HttpConfiguration { public int getMaxHttpConnection() { return maxHttpConnection; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 2) public void getMaxHttpConnectionTest() { Assert.assertEquals(httpConf.getMaxHttpConnection(), 10); }
HttpConfiguration { public int getMaxRetry() { return maxRetry; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 3) public void getMaxRetryTest() { Assert.assertEquals(httpConf.getMaxRetry(), 2); }
HttpConfiguration { public String getProxyHost() { return proxyHost; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 4) public void getProxyHostTest() { Assert.assertEquals(httpConf.getProxyHost(), null); }
HttpConfiguration { public int getProxyPort() { return proxyPort; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 5) public void getProxyPortTest() { Assert.assertEquals(httpConf.getProxyPort(), -1); }
HttpConfiguration { public int getReadTimeout() { return readTimeout; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 6) public void getReadTimeoutTest() { Assert.assertEquals(httpConf.getReadTimeout(), 0); }
HttpConfiguration { public int getRetryDelay() { return retryDelay; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 7) public void getRetryDelayTest() { Assert.assertEquals(httpConf.getRetryDelay(), 1000); }
HttpConfiguration { public boolean isProxySet() { return proxySet; } HttpConfiguration(); String getIpAddress(); void setIpAddress(String ipAddress); String getProxyUserName(); void setProxyUserName(String proxyUserName); String getProxyPassword(); void setProxyPassword(String proxyPassword); int getMaxHttpConnection(); void setMaxHttpConnection(int maxHttpConnection); int getRetryDelay(); void setRetryDelay(int retryDelay); String getEndPointUrl(); void setEndPointUrl(String endPointUrl); int getMaxRetry(); void setMaxRetry(int maxRetry); String getProxyHost(); void setProxyHost(String proxyHost); int getProxyPort(); void setProxyPort(int proxyPort); int getReadTimeout(); void setReadTimeout(int readTimeout); int getConnectionTimeout(); void setConnectionTimeout(int connectionTimeout); boolean isProxySet(); void setProxySet(boolean proxySet); boolean isGoogleAppEngine(); void setGoogleAppEngine(boolean googleAppEngine); String getHttpMethod(); void setHttpMethod(String httpMethod); FollowRedirect getInstanceFollowRedirects(); void setInstanceFollowRedirects(FollowRedirect followRedirects); String getContentType(); void setContentType(String contentType); }
@Test(priority = 9) public void isProxySetTest() { Assert.assertEquals(httpConf.isProxySet(), false); }
DefaultHttpConnection extends HttpConnection { @Override public void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration) throws IOException { this.config = clientConfiguration; URL url = new URL(this.config.getEndPointUrl()); Proxy proxy = null; String proxyHost = this.config.getProxyHost(); int proxyPort = this.config.getProxyPort(); if ((proxyHost != null) && (proxyPort > 0)) { SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort); proxy = new Proxy(Proxy.Type.HTTP, addr); } if (proxy != null) { this.connection = (HttpURLConnection) url.openConnection(proxy); } else { this.connection = (HttpURLConnection) url .openConnection(Proxy.NO_PROXY); } if (this.connection instanceof HttpsURLConnection) { ((HttpsURLConnection) this.connection) .setSSLSocketFactory(this.sslContext.getSocketFactory()); } if (this.config.getProxyUserName() != null && this.config.getProxyPassword() != null) { final String username = this.config.getProxyUserName(); final String password = this.config.getProxyPassword(); Authenticator authenticator = new DefaultPasswordAuthenticator( username, password); Authenticator.setDefault(authenticator); } System.setProperty("http.maxConnections", String.valueOf(this.config.getMaxHttpConnection())); System.setProperty("sun.net.http.errorstream.enableBuffering", "true"); this.connection.setDoInput(true); this.connection.setDoOutput(true); setRequestMethodViaJreBugWorkaround(this.connection, config.getHttpMethod()); this.connection.setConnectTimeout(this.config.getConnectionTimeout()); this.connection.setReadTimeout(this.config.getReadTimeout()); switch (config.getInstanceFollowRedirects()) { case NO_DO_NOT_FOLLOW_REDIRECT: connection.setInstanceFollowRedirects(false); break; case YES_FOLLOW_REDIRECT: connection.setInstanceFollowRedirects(true); break; } } DefaultHttpConnection(); DefaultHttpConnection(SSLContext sslContext); @Override void setupClientSSL(String certPath, String certKey); @Override void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }
@Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); defaultHttpConnection .createAndconfigureHttpConnection(httpConfiguration); } @Test(dataProvider = "configParamsForProxy", dataProviderClass = DataProviderClass.class) public void createAndConfigureHttpConnectionForProxyTest( ConfigManager config) throws IOException { httpConfiguration.setGoogleAppEngine(Boolean.parseBoolean(config.getConfigurationMap().get(Constants.GOOGLE_APP_ENGINE))); if (Boolean.parseBoolean(config.getConfigurationMap().get(Constants.USE_HTTP_PROXY))) { httpConfiguration.setProxyPort(Integer.parseInt(config.getConfigurationMap().get(Constants.HTTP_PROXY_PORT))); httpConfiguration.setProxyHost(config.getConfigurationMap().get(Constants.HTTP_PROXY_HOST)); httpConfiguration.setProxyUserName(config.getConfigurationMap().get(Constants.HTTP_PROXY_USERNAME)); httpConfiguration.setProxyPassword(config.getConfigurationMap().get(Constants.HTTP_PROXY_PASSWORD)); } httpConfiguration.setConnectionTimeout(Integer.parseInt(config.getConfigurationMap().get(Constants.HTTP_CONNECTION_TIMEOUT))); httpConfiguration.setMaxRetry(Integer.parseInt(config.getConfigurationMap().get(Constants.HTTP_CONNECTION_RETRY))); httpConfiguration.setReadTimeout(Integer.parseInt(config.getConfigurationMap().get(Constants.HTTP_CONNECTION_READ_TIMEOUT))); httpConfiguration.setMaxHttpConnection(Integer.parseInt(config.getConfigurationMap().get(Constants.HTTP_CONNECTION_MAX_CONNECTION))); httpConfiguration .setEndPointUrl("https: defaultHttpConnection .createAndconfigureHttpConnection(httpConfiguration); Assert.assertEquals( Integer.parseInt(System.getProperty("http.maxConnections")), httpConfiguration.getMaxHttpConnection()); }
DefaultHttpConnection extends HttpConnection { @Override public void setupClientSSL(String certPath, String certKey) throws SSLConfigurationException { try { this.sslContext = SSLUtil.setupClientSSL(certPath, certKey); } catch (Exception e) { throw new SSLConfigurationException(e.getMessage(), e); } } DefaultHttpConnection(); DefaultHttpConnection(SSLContext sslContext); @Override void setupClientSSL(String certPath, String certKey); @Override void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); }
@Test(expectedExceptions = SSLConfigurationException.class) public void checkSSLConfigurationExceptionTest() throws SSLConfigurationException { defaultHttpConnection.setupClientSSL("certPath", "certKey"); }
GoogleAppEngineHttpConnection extends HttpConnection { @Override public void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration) throws IOException { this.config = clientConfiguration; URL url = new URL(this.config.getEndPointUrl()); this.connection = (HttpURLConnection) url .openConnection(Proxy.NO_PROXY); this.connection.setDoInput(true); this.connection.setDoOutput(true); if ("PATCH".equals(config.getHttpMethod().toUpperCase())) { this.connection.setRequestMethod("POST"); this.requestMethod = "PATCH"; } else { this.connection.setRequestMethod(config.getHttpMethod()); } this.connection.setConnectTimeout(this.config.getConnectionTimeout()); this.connection.setReadTimeout(this.config.getReadTimeout()); switch (config.getInstanceFollowRedirects()) { case NO_DO_NOT_FOLLOW_REDIRECT: connection.setInstanceFollowRedirects(false); break; case YES_FOLLOW_REDIRECT: connection.setInstanceFollowRedirects(true); break; } } @Override void setupClientSSL(String certPath, String certKey); @Override void createAndconfigureHttpConnection( HttpConfiguration clientConfiguration); @Override InputStream executeWithStream(String url, String payload, Map<String, String> headers); }
@Test(expectedExceptions = MalformedURLException.class) public void checkMalformedURLExceptionTest() throws Exception { httpConfiguration.setEndPointUrl("ww.paypal.in"); googleAppEngineHttpConnection .createAndconfigureHttpConnection(httpConfiguration); } @Test public void testCreateAndConfigureHttpConnection_setsRequestMethodToPost() throws IOException { httpConfiguration.setEndPointUrl("http: httpConfiguration.setHttpMethod("PATCH"); GoogleAppEngineHttpConnection googleAppEngineHttpConnection = spy(GoogleAppEngineHttpConnection.class); doCallRealMethod().when(googleAppEngineHttpConnection).createAndconfigureHttpConnection((HttpConfiguration) any()); googleAppEngineHttpConnection.createAndconfigureHttpConnection(httpConfiguration); Assert.assertEquals("POST", googleAppEngineHttpConnection.connection.getRequestMethod()); }
NVPUtil { public static Map<String, String> decode(String nvpString) throws UnsupportedEncodingException { String[] nmValPairs = nvpString.split("&"); Map<String, String> response = new HashMap<String, String>(); for (String nmVal : nmValPairs) { String[] field = nmVal.split("="); response.put( URLDecoder.decode(field[0], Constants.ENCODING_FORMAT), (field.length > 1) ? URLDecoder.decode(field[1].trim(), Constants.ENCODING_FORMAT) : ""); } return response; } private NVPUtil(); static Map<String, String> decode(String nvpString); static String encodeUrl(String value); }
@Test public void decodeTest() throws UnsupportedEncodingException { String nvpString = "responseEnvelope.timestamp=2011-05-17T21%3A24%3A44.279-07%3A00&responseEnvelope.ack=Success&responseEnvelope.correlationId=ca0c236593634&responseEnvelope.build=1901705&invoiceID=INV2-AAWE-TAQW-7UXT-ZHBY&invoiceNumber=INV-00404"; Map<String, String> map = NVPUtil.decode(nvpString); Assert.assertEquals(6, map.size()); assert (map.containsValue("Success")); assert (map.containsKey("invoiceID")); assert (map.containsKey("invoiceNumber")); Assert.assertEquals("INV2-AAWE-TAQW-7UXT-ZHBY", map.get("invoiceID")); Assert.assertEquals("INV-00404", map.get("invoiceNumber")); }
NVPUtil { public static String encodeUrl(String value) throws UnsupportedEncodingException { return URLEncoder.encode(value, Constants.ENCODING_FORMAT); } private NVPUtil(); static Map<String, String> decode(String nvpString); static String encodeUrl(String value); }
@Test public void encodeTest() throws UnsupportedEncodingException { String value = "[email protected]"; Assert.assertEquals("jbui-us-personal1%40paypal.com", NVPUtil.encodeUrl(value)); }
Lottery { void run() { List<String> emails = emailsSource.get(); System.out.println("Emails count: " + emails.size()); List<String> winners = machine.setSeed(seedString).draw(emails); System.out.println("Winners:"); winners.forEach(System.out::println); } Lottery(Supplier<List<String>> emailsSource, LotteryMachine machine, String seedString); }
@Test public void mockedWithSpy() { EmailsReader emailsReader = mock(EmailsReader.class); List<String> list = new ArrayList<>(); List<String> spy = spy(list); doReturn(1).when(spy).size(); doReturn("0").when(spy).get(0); when(emailsReader.get()).thenReturn(spy); String seedString = "Test"; LotteryMachine lotteryMachine = new LotteryMachine(5); LotteryMachine spyMachine = spy(lotteryMachine); when(spyMachine.setSeed(seedString)).thenReturn(spyMachine.setSeed(0)); Lottery lottery = new Lottery(emailsReader, spyMachine, seedString); lottery.run(); Assert.assertEquals(0, lotteryMachine.getSeed()); } @Test public void mockedLottery() { EmailsReader emailsReader = mock(EmailsReader.class); LotteryMachine lotteryMachine = mock(LotteryMachine.class); String seedString = "May the Force be with you"; when(emailsReader.get()).thenReturn(Arrays.asList("0", "1", "2", "3", "4")); when(lotteryMachine.setSeed(seedString)).thenReturn(lotteryMachine); Lottery lottery = new Lottery(emailsReader, lotteryMachine, seedString); lottery.run(); verify(emailsReader, times(1)).get(); verify(lotteryMachine, times(1)).setSeed(seedString); verify(lotteryMachine, never()).dispose(); }
LotteryMachine { List<String> draw(List<String> emails) { System.out.println("Draw for the seed: " + seed); Random rnd = new Random(seed); Set<String> winners = new HashSet<>(); while (winners.size() < Math.min(winnersCount, emails.size())) { int index = rnd.nextInt(emails.size()); System.out.println("Ball: " + index); winners.add(emails.get(index)); } return new ArrayList<>(winners); } LotteryMachine(int winnersCount); long getSeed(); }
@Test public void oneEmail() { Assert.assertEquals(1, lotteryMachine.draw(Collections.singletonList("test")).size()); } @Test public void fiveEmails() { List<String> result = lotteryMachine .draw(Arrays.asList("0", "1", "2", "3", "4")); assertEquals(5, result.size()); Assert.assertTrue(result.contains("0")); Assert.assertTrue(result.contains("1")); Assert.assertTrue(result.contains("2")); Assert.assertTrue(result.contains("3")); Assert.assertTrue(result.contains("4")); }
ReflectionHelper { static Object getFieldValue(Object object, String name) { Field field = null; boolean isAccessible = true; try { field = object.getClass().getDeclaredField(name); isAccessible = field.isAccessible(); field.setAccessible(true); return field.get(object); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } finally { if (field != null && !isAccessible) { field.setAccessible(false); } } return null; } private ReflectionHelper(); }
@Test public void getFieldValue() { Assert.assertEquals("A", ReflectionHelper.getFieldValue(new TestClass(1, "A"), "s")); Assert.assertEquals(1, ReflectionHelper.getFieldValue(new TestClass(1, "B"), "a")); }
ReflectionHelper { static void setFieldValue(Object object, String name, Object value) { Field field = null; boolean isAccessible = true; try { field = object.getClass().getDeclaredField(name); isAccessible = field.isAccessible(); field.setAccessible(true); field.set(object, value); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } finally { if (field != null && !isAccessible) { field.setAccessible(false); } } } private ReflectionHelper(); }
@Test public void setFieldValue() { TestClass test = new TestClass(1, "A"); Assert.assertEquals("A", test.getS()); ReflectionHelper.setFieldValue(test, "s", "B"); Assert.assertEquals("B", test.getS()); }
ReflectionHelper { static Object callMethod(Object object, String name, Object... args) { Method method = null; boolean isAccessible = true; try { method = object.getClass().getDeclaredMethod(name, toClasses(args)); isAccessible = method.isAccessible(); method.setAccessible(true); return method.invoke(object, args); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } finally { if (method != null && !isAccessible) { method.setAccessible(false); } } return null; } private ReflectionHelper(); }
@Test public void callMethod() { Assert.assertEquals("A", ReflectionHelper.callMethod(new TestClass(1, "A"), "getS")); TestClass test = new TestClass(1, "A"); ReflectionHelper.callMethod(test, "setDefault"); Assert.assertEquals("", test.getS()); }
LotteryMachine { List<String> draw() { System.out.println("Draw for the seed: " + seed); Random rnd = new Random(seed); Set<String> winners = new HashSet<>(); while (winners.size() < winnersCount) { int index = rnd.nextInt(emails.size()); System.out.println("Ball: " + index); winners.add(emails.get(index)); } return new ArrayList<>(winners); } LotteryMachine(List<String> emails, int winnersCount); }
@Test public void oneEmail() { Assert.assertEquals(1, new LotteryMachine(Collections.singletonList("test"), 5).draw().size()); } @Test public void fiveEmails() { List<String> result = new LotteryMachine(Arrays.asList("0", "1", "2", "3", "4"), 5).draw(); Assert.assertEquals(5, result.size()); Assert.assertTrue(result.contains("0")); Assert.assertTrue(result.contains("1")); Assert.assertTrue(result.contains("2")); Assert.assertTrue(result.contains("3")); Assert.assertTrue(result.contains("4")); }
ATM { public int getBalance() { Iterator<Cell> iterator = first.iterator(); int balance = 0; while (iterator.hasNext()) { balance += iterator.next().getBalance(); } return balance; } ATM(List<Cell> cells); boolean withdraw(int requested); int getBalance(); }
@Test public void balanceSimple() { List<Cell> cells = new ArrayList<>(); cells.add(new Cell(5, 10)); ATM atm = new ATM(cells); Assert.assertEquals(50, atm.getBalance()); }
Cell implements Comparable<Cell>, Iterable<Cell> { public boolean withdraw(int requested) { int expectedCount = Math.min(requested / nominal, count); int expectedCash = expectedCount * nominal; boolean nextCellResult = true; if (requested != expectedCash) { nextCellResult = next != null && next.withdraw(requested - expectedCash); } if(nextCellResult) { count = count - expectedCount; return true; } return false; } Cell(int nominal, int count); boolean withdraw(int requested); int getNominal(); int getCount(); void setNext(Cell next); int getBalance(); @Override int compareTo(Cell o); @Override Iterator<Cell> iterator(); }
@Test public void withdrawToBig() { Cell cell = new Cell(1, 100); Assert.assertFalse(cell.withdraw(101)); } @Test public void withdrawDiscrete() { Cell cell = new Cell(5, 100); Assert.assertFalse(cell.withdraw(43)); }
RecyclingPagerAdapter extends PagerAdapter { @Override public final Object instantiateItem(ViewGroup container, int position) { int viewType = getItemViewType(position); View view = null; if (viewType != IGNORE_ITEM_VIEW_TYPE) { view = recycleBin.getScrapView(position, viewType); } view = getView(position, view, container); container.addView(view); return view; } RecyclingPagerAdapter(); RecyclingPagerAdapter(RecycleBin recycleBin); @Override void notifyDataSetChanged(); @Override final Object instantiateItem(ViewGroup container, int position); @Override final void destroyItem(ViewGroup container, int position, Object object); @Override final boolean isViewFromObject(View view, Object object); int getViewTypeCount(); @SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses. int getItemViewType(int position); abstract View getView(int position, View convertView, ViewGroup container); }
@Test public void recycledViewIsNotAttemptedForIgnoredType() { LinearLayout container = new LinearLayout(context); final TextView child = new TextView(context); RecyclingPagerAdapter adapter = new RecyclingPagerAdapter(recycleBin) { @Override public int getItemViewType(int position) { return IGNORE_ITEM_VIEW_TYPE; } @Override public View getView(int position, View convertView, ViewGroup container) { return child; } @Override public int getCount() { throw new AssertionError("getCount should not have been called."); } }; verify(recycleBin).setViewTypeCount(1); adapter.instantiateItem(container, 0); verifyNoMoreInteractions(recycleBin); }
RecyclingPagerAdapter extends PagerAdapter { @Override public final void destroyItem(ViewGroup container, int position, Object object) { View view = (View) object; container.removeView(view); int viewType = getItemViewType(position); if (viewType != IGNORE_ITEM_VIEW_TYPE) { recycleBin.addScrapView(view, position, viewType); } } RecyclingPagerAdapter(); RecyclingPagerAdapter(RecycleBin recycleBin); @Override void notifyDataSetChanged(); @Override final Object instantiateItem(ViewGroup container, int position); @Override final void destroyItem(ViewGroup container, int position, Object object); @Override final boolean isViewFromObject(View view, Object object); int getViewTypeCount(); @SuppressWarnings("UnusedParameters") // Argument potentially used by subclasses. int getItemViewType(int position); abstract View getView(int position, View convertView, ViewGroup container); }
@Test public void ignoredViewTypeIsNotRecycled() { LinearLayout container = new LinearLayout(context); TextView child = new TextView(context); container.addView(child); RecyclingPagerAdapter adapter = new RecyclingPagerAdapter(recycleBin) { @Override public int getItemViewType(int position) { return IGNORE_ITEM_VIEW_TYPE; } @Override public View getView(int position, View convertView, ViewGroup container) { throw new AssertionError("getView should not have been called."); } @Override public int getCount() { throw new AssertionError("getCount should not have been called."); } }; verify(recycleBin).setViewTypeCount(1); adapter.destroyItem(container, 0, child); verifyNoMoreInteractions(recycleBin); }
BrendaChebiOntology { public static Map<String, Set<String>> getApplicationToMainApplicationsMap( Map<String, Set<String>> isSubtypeOfRelationships, String applicationChebiId) { Set<String> mainApplicationsChebiId = isSubtypeOfRelationships.get(applicationChebiId); ArrayList<String> applicationsToVisit = new ArrayList<>(mainApplicationsChebiId); Map<String, Set<String>> applicationToMainApplicationsMap = applicationsToVisit.stream(). collect(Collectors.toMap(e -> e, Collections::singleton)); int currentIndex = 0; while (currentIndex < applicationsToVisit.size()) { String currentApplication = applicationsToVisit.get(currentIndex); Set<String> subApplications = isSubtypeOfRelationships.get(currentApplication); if (subApplications != null) { applicationsToVisit.addAll(subApplications); for (String subApplication : subApplications) { Set<String> mainApplicationsSet = applicationToMainApplicationsMap.get(subApplication); if (mainApplicationsSet == null) { mainApplicationsSet = new HashSet<>(); applicationToMainApplicationsMap.put(subApplication, mainApplicationsSet); } mainApplicationsSet.addAll(applicationToMainApplicationsMap.get(currentApplication)); } } currentIndex++; } return applicationToMainApplicationsMap; } static Map<String, ChebiOntology> fetchOntologyMap(SQLConnection brendaDB); static Map<String, Set<String>> fetchIsSubtypeOfRelationships(SQLConnection brendaDB); static Map<String, Set<String>> fetchHasRoleRelationships(SQLConnection brendaDB); static Map<String, Set<String>> getApplicationToMainApplicationsMap( Map<String, Set<String>> isSubtypeOfRelationships, String applicationChebiId); static Map<ChebiOntology, ChebiApplicationSet> getApplications( Map<String, ChebiOntology> ontologyMap, Map<String, Set<String>> isSubtypeOfRelationships, Map<String, Set<String>> hasRoleRelationships); void addChebiApplications(MongoDB db, SQLConnection brendaDB); static void main(String[] args); }
@Test public void testApplicationToMainApplicationMapping() { Map<String, Set<String>> isSubtypeOfRelationships = new HashMap<>(); isSubtypeOfRelationships.put("1", new HashSet<>(Arrays.asList("2", "3"))); isSubtypeOfRelationships.put("2", Collections.singleton("4")); isSubtypeOfRelationships.put("3", Collections.singleton("5")); isSubtypeOfRelationships.put("5", new HashSet<>(Arrays.asList("6", "7"))); isSubtypeOfRelationships.put("4", Collections.singleton("7")); isSubtypeOfRelationships.put("6", Collections.singleton("8")); Map<String, Set<String>> applicationToMainApplicationMap = new HashMap<>(); applicationToMainApplicationMap.put("2", Collections.singleton("2")); applicationToMainApplicationMap.put("3", Collections.singleton("3")); applicationToMainApplicationMap.put("4", Collections.singleton("2")); applicationToMainApplicationMap.put("5", Collections.singleton("3")); applicationToMainApplicationMap.put("6", Collections.singleton("3")); applicationToMainApplicationMap.put("7", new HashSet<>(Arrays.asList("2", "3"))); applicationToMainApplicationMap.put("8", Collections.singleton("3")); assertEquals(applicationToMainApplicationMap, BrendaChebiOntology.getApplicationToMainApplicationsMap(isSubtypeOfRelationships, "1")); }
UniprotSeqEntry extends SequenceEntry { public Long getOrgId() { return this.orgId; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testOrgId() { assertEquals("tests whether organism ids are extracted accurately", (Long) 4000000399L, seqEntries.get(0).getOrgId()); }
UniprotSeqEntry extends SequenceEntry { public String getOrg() { return this.org; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testOrg() { assertEquals("tests whether organism names are extracted accurately", "Arabidopsis thaliana", seqEntries.get(0).getOrg()); }
UniprotSeqEntry extends SequenceEntry { public String getSeq() { return this.sequence; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testSeq() { assertEquals("tests whether sequences are extracted accurately", sequences.get(0), seqEntries.get(0).getSeq()); }
UniprotSeqEntry extends SequenceEntry { public String getEc() { return this.ec; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testEc() { assertEquals("tests whether ec_numbers are extracted accurately", "1.1.1.1", seqEntries.get(0).getEc()); }
UniprotSeqEntry extends SequenceEntry { public List<JSONObject> getRefs() { return this.references; } UniprotSeqEntry(Document doc, Map<String, String> minimalPrefixMapping); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<Seq> getMatchingSeqs(); List<JSONObject> getRefs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); String getCatalyticActivity(); Set<Long> getCatalyzedRxns(); }
@Test public void testReferences() { List<JSONObject> pmidRefs = new ArrayList<>(); List<String> pmids = Arrays.asList("2937058", "7851777", "8844162", "8587508", "11018155", "11158375", "11130712", "14593172", "10382288", "3377754", "2277648", "12231733", "8787023", "9522467", "9611167", "9880346", "11402191", "11402202", "11987307", "12509334", "12857811", "16055689", "18433157", "18441225", "19245862", "20508152", "22223895", "23707506", "24395201", "26566261", "25447145"); for (String pmid : pmids) { JSONObject obj = new JSONObject(); obj.put("val", pmid); obj.put("src", "PMID"); pmidRefs.add(obj); } assertEquals("tests whether PMIDs were assigned accurately", pmidRefs.toString(), seqEntries.get(0).getRefs().toString()); }
GenbankSeqEntry extends SequenceEntry { public DBObject getMetadata() { return this.metadata; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testMetadata() { ArrayList<DBObject> metadatas = new ArrayList<>(); List<String> geneSynonyms = Arrays.asList("STP", "STP1", "SULT1A1"); List<String> emptyGeneSynonyms = new ArrayList<>(); JSONObject obj = new JSONObject(); JSONObject accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("CUB13083"))); obj.put("xref", new JSONObject()); obj.put("synonyms", emptyGeneSynonyms); obj.put("product_names", Collections.singletonList("Arylamine N-acetyltransferase")); obj.put("accession", accessionObject); metadatas.add(MongoDBToJSON.conv(obj)); obj = new JSONObject(); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("P50225"))); obj.put("xref", new JSONObject()); obj.put("name", "ST1A1_HUMAN"); obj.put("synonyms", geneSynonyms); obj.put("product_names", Collections.singletonList("Sulfotransferase 1A1")); obj.put("accession", accessionObject); metadatas.add(MongoDBToJSON.conv(obj)); obj = new org.json.JSONObject(); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("BAB21065"))); accessionObject.put("genbank_nucleotide", new JSONArray(Collections.singletonList("AB006984"))); obj.put("xref", new JSONObject()); obj.put("name", "ureA"); obj.put("synonyms", emptyGeneSynonyms); obj.put("product_names", Collections.singletonList("gamma subunit of urase")); obj.put("accession", accessionObject); metadatas.add(MongoDBToJSON.conv(obj)); obj = new org.json.JSONObject(); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("BAB21066"))); accessionObject.put("genbank_nucleotide", new JSONArray(Collections.singletonList("AB006984"))); obj.put("xref", new JSONObject()); obj.put("name", "ureB"); obj.put("synonyms", emptyGeneSynonyms); obj.put("product_names", Collections.singletonList("beta subunit of urease")); obj.put("accession", accessionObject); metadatas.add(MongoDBToJSON.conv(obj)); obj = new org.json.JSONObject(); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("BAB21067"))); accessionObject.put("genbank_nucleotide", new JSONArray(Collections.singletonList("AB006984"))); obj.put("xref", new JSONObject()); obj.put("name", "ureC"); obj.put("synonyms", emptyGeneSynonyms); obj.put("product_names", Collections.singletonList("alpha subunit of urease")); obj.put("accession", accessionObject); metadatas.add(MongoDBToJSON.conv(obj)); assertEquals("tests whether metadata is extracted accurately", metadatas.get(0), proteinSeqEntries.get(0).getMetadata()); assertEquals("tests whether metadata is extracted accurately", metadatas.get(1), proteinSeqEntries.get(1).getMetadata()); assertEquals("tests whether metadata is extracted accurately", metadatas.get(2), dnaSeqEntries.get(0).getMetadata()); assertEquals("tests whether metadata is extracted accurately", metadatas.get(3), dnaSeqEntries.get(1).getMetadata()); assertEquals("tests whether metadata is extracted accurately", metadatas.get(4), dnaSeqEntries.get(2).getMetadata()); }
GenbankSeqEntry extends SequenceEntry { public JSONObject getAccession() { return this.accessions; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testAccession() { JSONObject accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("CUB13083"))); assertEquals("tests whether accession ID is extracted accurately", accessionObject.toString(), proteinSeqEntries.get(0).getAccession().toString()); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("P50225"))); assertEquals("tests whether accession ID is extracted accurately", accessionObject.toString(), proteinSeqEntries.get(1).getAccession().toString()); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("BAB21065"))); accessionObject.put("genbank_nucleotide", new JSONArray(Collections.singletonList("AB006984"))); assertEquals("tests whether accession ID is extracted accurately", accessionObject.toString(), dnaSeqEntries.get(0).getAccession().toString()); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("BAB21066"))); accessionObject.put("genbank_nucleotide", new JSONArray(Collections.singletonList("AB006984"))); assertEquals("tests whether accession ID is extracted accurately", accessionObject.toString(), dnaSeqEntries.get(1).getAccession().toString()); accessionObject = new JSONObject(); accessionObject.put("genbank_protein", new JSONArray(Collections.singletonList("BAB21067"))); accessionObject.put("genbank_nucleotide", new JSONArray(Collections.singletonList("AB006984"))); assertEquals("tests whether accession ID is extracted accurately", accessionObject.toString(), dnaSeqEntries.get(2).getAccession().toString()); }
GenbankSeqEntry extends SequenceEntry { public String getGeneName() { return this.geneName; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testGeneName() { assertEquals("tests whether gene name is extracted accurately", null, proteinSeqEntries.get(0).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ST1A1_HUMAN", proteinSeqEntries.get(1).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ureA", dnaSeqEntries.get(0).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ureB", dnaSeqEntries.get(1).getGeneName()); assertEquals("tests whether gene name is extracted accurately", "ureC", dnaSeqEntries.get(2).getGeneName()); }
GenbankSeqEntry extends SequenceEntry { public List<String> getGeneSynonyms() { return this.geneSynonyms; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testGeneSynonyms() { List<String> geneSynonyms = Arrays.asList("STP", "STP1", "SULT1A1"); assertEquals("tests whether gene synonyms are extracted accurately", geneSynonyms, proteinSeqEntries.get(1).getGeneSynonyms()); geneSynonyms = new ArrayList<>(); assertEquals("tests whether gene synonyms are extracted accurately", geneSynonyms, proteinSeqEntries.get(0).getGeneSynonyms()); assertEquals("tests whether gene synonyms are extrated accurately", geneSynonyms, dnaSeqEntries.get(0).getGeneSynonyms()); assertEquals("tests whether gene synonyms are extrated accurately", geneSynonyms, dnaSeqEntries.get(1).getGeneSynonyms()); assertEquals("tests whether gene synonyms are extrated accurately", geneSynonyms, dnaSeqEntries.get(2).getGeneSynonyms()); }
GenbankSeqEntry extends SequenceEntry { public List<String> getProductName() { return this.productNames; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testProductName() { assertEquals("tests whether product names are extracted accurately", Collections.singletonList("Arylamine N-acetyltransferase"), proteinSeqEntries.get(0).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("Sulfotransferase 1A1"), proteinSeqEntries.get(1).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("gamma subunit of urase"), dnaSeqEntries.get(0).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("beta subunit of urease"), dnaSeqEntries.get(1).getProductName()); assertEquals("tests whether product names are extracted accurately", Collections.singletonList("alpha subunit of urease"), dnaSeqEntries.get(2).getProductName()); }
HMDBParser { protected Chemical extractChemicalFromXMLDocument(Document doc) throws JaxenException, JSONException { String hmdbId = getText(HMDB_XPATH.HMDB_ID_TEXT, doc); String primaryName = getText(HMDB_XPATH.PRIMARY_NAME_TEXT, doc); String iupacName = getText(HMDB_XPATH.IUPAC_NAME_TEXT, doc); List<String> synonyms = getTextFromNodes(HMDB_XPATH.SYNONYMS_NODES, doc); String inchi = getText(HMDB_XPATH.INCHI_TEXT, doc); String smiles = getText(HMDB_XPATH.SMILES_TEXT, doc); if (inchi == null || inchi.isEmpty()) { LOGGER.warn("No InChI found for HMDB chemical %s, aborting", hmdbId); return null; } String ontologyStatus = getText(HMDB_XPATH.ONTOLOGY_STATUS_TEXT, doc); List<String> ontologyOrigins = getTextFromNodes(HMDB_XPATH.ONTOLOGY_ORIGINS_NODES, doc); List<String> ontologyFunctions = getTextFromNodes(HMDB_XPATH.ONTOLOGY_FUNCTIONS_NODES, doc); List<String> ontologyApplications = getTextFromNodes(HMDB_XPATH.ONTOLOGY_APPLICATIONS_NODES, doc); List<String> ontologyLocations = getTextFromNodes(HMDB_XPATH.ONTOLOGY_LOCATIONS_NODES, doc); List<String> locationFluids = getTextFromNodes(HMDB_XPATH.LOCATIONS_FLUID_NODES, doc); List<String> locationTissues = getTextFromNodes(HMDB_XPATH.LOCATIONS_TISSUE_NODES, doc); List<String> pathwayNames = getTextFromNodes(HMDB_XPATH.PATHWAY_NAME_NODES, doc); List<String> diseaseNames = getTextFromNodes(HMDB_XPATH.DISEASE_NAME_NODES, doc); String metlinId = getText(HMDB_XPATH.METLIN_ID_TEXT, doc); String pubchemId = getText(HMDB_XPATH.PUBCHEM_ID_TEXT, doc); String chebiId = getText(HMDB_XPATH.CHEBI_ID_TEXT, doc); List<Node> proteins = getNodes(HMDB_XPATH.PROTEIN_L1_NODES, doc); List<Triple<String, String, String>> proteinAttributes = new ArrayList<>(proteins.size()); for (Node n : proteins) { Document proteinDoc = documentBuilder.newDocument(); proteinDoc.adoptNode(n); proteinDoc.appendChild(n); String name = getText(HMDB_XPATH.PROTEIN_L2_NAME_TEXT, proteinDoc); String uniprotId = getText(HMDB_XPATH.PROTEIN_L2_UNIPROT_ID_TEXT, proteinDoc); String geneName = getText(HMDB_XPATH.PROTEIN_L2_GENE_NAME_TEXT, proteinDoc); proteinAttributes.add(Triple.of(name, uniprotId, geneName)); } Chemical chem = new Chemical(inchi); chem.setSmiles(smiles); chem.setCanon(primaryName); if (pubchemId != null && !pubchemId.isEmpty()) { chem.setPubchem(Long.valueOf(pubchemId)); } synonyms.forEach(chem::addSynonym); chem.addSynonym(iupacName); JSONObject meta = new JSONObject() .put("hmdb_id", hmdbId) .put("ontology", new JSONObject() .put("status", ontologyStatus) .put("origins", new JSONArray(ontologyOrigins)) .put("functions", new JSONArray(ontologyFunctions)) .put("applications", new JSONArray(ontologyApplications)) .put("locations", new JSONArray(ontologyLocations)) ) .put("location", new JSONObject() .put("fluid", new JSONArray(locationFluids)) .put("tissue", new JSONArray(locationTissues)) ) .put("pathway_names", new JSONArray(pathwayNames)) .put("disease_names", new JSONArray(diseaseNames)) .put("metlin_id", metlinId) .put("chebi_id", chebiId) .put("proteins", new JSONArray(proteinAttributes.stream() .map(t -> new JSONObject(). put("name", t.getLeft()). put("uniprot_id", t.getMiddle()). put("gene_name", t.getRight()) ).collect(Collectors.toList()) ) ); chem.putRef(Chemical.REFS.HMDB, meta); return chem; } protected HMDBParser(MongoDB db); static void main(String[] args); void run(File inputDir); static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }
@Test public void testExtractChemicalFromXMLDocument() throws Exception { MockedMongoDB mockedDb = new MockedMongoDB(); HMDBParser parser = HMDBParser.Factory.makeParser(mockedDb.getMockMongoDB()); Chemical chem = parser.extractChemicalFromXMLDocument(doc); assertEquals("Canonical name matches", "acetaminophen", chem.getCanon().toLowerCase()); assertEquals("InChI matches", "InChI=1S/C8H9NO2/c1-6(10)9-7-2-4-8(11)5-3-7/h2-5,11H,1H3,(H,9,10)", chem.getInChI()); assertEquals("SMILES matches", "CC(=O)NC1=CC=C(O)C=C1", chem.getSmiles()); assertTrue("Expected synonyms appear", chem.getSynonyms().containsAll(Arrays.asList( "tylenol", "acetaminophen", "paracetamol", "apap" ))); assertEquals("Pubchem id matches", Long.valueOf(1983), chem.getPubchemID()); JSONObject xref = chem.getRef(Chemical.REFS.HMDB); assertEquals("HMDB ID matches", "HMDB01859", xref.getString("hmdb_id")); assertEquals("Metlin ID matches", "6353", xref.getString("metlin_id")); assertEquals("ChEBI ID matches", "46195", xref.getString("chebi_id")); assertEquals("Fluid length matches", 3, xref.getJSONObject("location").getJSONArray("fluid").length()); assertEquals("First fluid matches", "Blood", xref.getJSONObject("location").getJSONArray("fluid").getString(0)); assertEquals("Tissue length matches", 1, xref.getJSONObject("location").getJSONArray("tissue").length()); assertEquals("First tissue matches", "All Tissues", xref.getJSONObject("location").getJSONArray("tissue").getString(0)); assertEquals("Proteins length matches", 4, xref.getJSONArray("proteins").length()); assertEquals("First protein name matches", "Cytochrome P450 1A2", xref.getJSONArray("proteins").getJSONObject(0).getString("name")); assertEquals("First protein uniprot_id matches", "P05177", xref.getJSONArray("proteins").getJSONObject(0).getString("uniprot_id")); assertEquals("First protein gene name matches", "CYP1A2", xref.getJSONArray("proteins").getJSONObject(0).getString("gene_name")); assertEquals("First ontology origin matches", "Drug", xref.getJSONObject("ontology").getJSONArray("origins").getString(0)); }
GenbankSeqEntry extends SequenceEntry { public Long getOrgId() { return this.orgId; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testOrgId() { assertEquals("tests whether organism ids are extracted accurately", (Long) 4000000648L, proteinSeqEntries.get(0).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000002681L, proteinSeqEntries.get(1).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000005381L, dnaSeqEntries.get(0).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000005381L, dnaSeqEntries.get(1).getOrgId()); assertEquals("tests whether organism ids are extracted accurately", (Long) 4000005381L, dnaSeqEntries.get(2).getOrgId()); }
GenbankSeqEntry extends SequenceEntry { public String getOrg() { return this.org; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testOrg() { assertEquals("tests whether organism names are extracted accurately", "Bacillus cereus", proteinSeqEntries.get(0).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Homo sapiens", proteinSeqEntries.get(1).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Rhodobacter capsulatus", dnaSeqEntries.get(0).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Rhodobacter capsulatus", dnaSeqEntries.get(1).getOrg()); assertEquals("tests whether organism names are extracted accurately", "Rhodobacter capsulatus", dnaSeqEntries.get(2).getOrg()); }
GenbankSeqEntry extends SequenceEntry { public String getSeq() { return this.sequence; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testSeq() { assertEquals("tests whether sequences are extracted accurately", sequences.get(0), proteinSeqEntries.get(0).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(1), proteinSeqEntries.get(1).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(2), dnaSeqEntries.get(0).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(3), dnaSeqEntries.get(1).getSeq()); assertEquals("tests whether sequences are extracted accurately", sequences.get(4), dnaSeqEntries.get(2).getSeq()); }
GenbankSeqEntry extends SequenceEntry { public String getEc() { return this.ec; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testEc() { assertEquals("tests whether ec_numbers are extracted accurately", "2.3.1.5", proteinSeqEntries.get(0).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "2.8.2.1", proteinSeqEntries.get(1).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "3.5.1.5", dnaSeqEntries.get(0).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "3.5.1.5", dnaSeqEntries.get(1).getEc()); assertEquals("tests whether ec_numbers are extracted accurately", "3.5.1.5", dnaSeqEntries.get(2).getEc()); }
GenbankSeqEntry extends SequenceEntry { public List<JSONObject> getPmids() { return this.pmids; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testPMID() { List<JSONObject> pmidRefs = new ArrayList<>(); assertEquals("tests whether PMIDs were assigned accurately", pmidRefs, proteinSeqEntries.get(0).getPmids()); List<String> pmids = Arrays.asList("8363592", "8484775", "8423770", "8033246", "7864863", "7695643", "7581483", "8912648", "8924211", "9855620", "15616553", "15489334", "8288252", "8093002", "8033270", "24275569", "25944712", "12471039", "16221673", "20417180", "21723874", "22069470", "9345314", "10762004", "21269460"); for (String pmid : pmids) { JSONObject obj = new JSONObject(); obj.put("val", pmid); obj.put("src", "PMID"); pmidRefs.add(obj); } assertEquals("tests whether PMIDs were assigned accurately", pmidRefs.toString(), proteinSeqEntries.get(1).getPmids().toString()); pmidRefs = new ArrayList<>(); JSONObject obj = new JSONObject(); obj.put("src", "PMID"); obj.put("val", "9484481"); pmidRefs.add(obj); assertEquals("tests whether PMIDs were assigned accurately", pmidRefs.toString(), dnaSeqEntries.get(0).getPmids().toString()); assertEquals("tests whether PMIDs were assigned accurately", pmidRefs.toString(), dnaSeqEntries.get(1).getPmids().toString()); assertEquals("tests whether PMIDs were assigned accurately", pmidRefs.toString(), dnaSeqEntries.get(2).getPmids().toString()); }
GenbankSeqEntry extends SequenceEntry { public List<JSONObject> getPatents() { return this.patents; } GenbankSeqEntry(AbstractSequence sequence); GenbankSeqEntry(AbstractSequence sequence, Map<String, List<Qualifier>> cdsQualifierMap); DBObject getMetadata(); JSONObject getAccession(); String getGeneName(); List<String> getGeneSynonyms(); List<String> getProductName(); List<JSONObject> getPmids(); List<JSONObject> getPatents(); List<JSONObject> getRefs(); List<Seq> getMatchingSeqs(); Long getOrgId(); String getOrg(); String getSeq(); String getEc(); Set<Long> getCatalyzedRxns(); }
@Test public void testPatents() { List<JSONObject> patentRefs = new ArrayList<>(); assertEquals("tests whether Patent references were assigned accurately", patentRefs, proteinSeqEntries.get(0).getPatents()); JSONObject obj = new JSONObject(); obj.put("src", "Patent"); obj.put("country_code", "JP"); obj.put("patent_number", "2008518610"); obj.put("patent_year", "2008"); patentRefs.add(obj); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), proteinSeqEntries.get(1).getPatents().toString()); JSONObject obj2 = new JSONObject(); obj2.put("src", "Patent"); obj2.put("country_code", "EP"); obj2.put("patent_number", "2904117"); obj2.put("patent_year", "2015"); patentRefs.add(obj2); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), dnaSeqEntries.get(0).getPatents().toString()); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), dnaSeqEntries.get(1).getPatents().toString()); assertEquals("tests whether Patent references were assigned accurately", patentRefs.toString(), dnaSeqEntries.get(2).getPatents().toString()); }
PubchemParser { public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader) throws XMLStreamException, JaxenException { Document bufferDoc = null; Element currentElement = null; StringBuilder textBuffer = null; while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch (event.getEventType()) { case XMLStreamConstants.START_ELEMENT: String eventName = event.asStartElement().getName().getLocalPart(); if (COMPOUND_DOC_TAG.equals(eventName)) { bufferDoc = documentBuilder.newDocument(); currentElement = bufferDoc.createElement(eventName); bufferDoc.appendChild(currentElement); } else if (currentElement != null) { Element newElement = bufferDoc.createElement(eventName); currentElement.appendChild(newElement); currentElement = newElement; } break; case XMLStreamConstants.CHARACTERS: if (currentElement == null) { continue; } Characters chars = event.asCharacters(); if (chars.isWhiteSpace()) { continue; } Text textNode = bufferDoc.createTextNode(chars.getData()); currentElement.appendChild(textNode); break; case XMLStreamConstants.END_ELEMENT: if (currentElement == null) { continue; } eventName = event.asEndElement().getName().getLocalPart(); Node parentNode = currentElement.getParentNode(); if (parentNode instanceof Element) { currentElement = (Element) parentNode; } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) { PubchemEntry entry = extractPCCompoundFeatures(bufferDoc); if (entry != null) { return entry.asChemical(); } else { bufferDoc = null; currentElement = null; } } else { throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element", currentElement.getTagName(), parentNode.getNodeType())); } break; } } return null; } PubchemParser(MongoDB db); void init(); Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader); void openCompressedXMLFileAndWriteChemicals(File file); static void main(String[] args); static final HelpFormatter HELP_FORMATTER; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; }
@Test public void testParserProcessesTheCorrectChemicals() throws Exception { File testFile = new File(this.getClass().getResource("CompoundTest.xml.gz").getFile()); String expectedInchi1 = "InChI=1S/C18H27FN2/c1-2-14-11-17(20-16-5-3-4-6-16)13-21(12-14)18-9-7-15(19)8-10-18/h7-10,14,16-17,20H,2-6,11-13H2,1H3"; String expectedSmiles1 = "CCC1CC(CN(C1)C2=CC=C(C=C2)F)NC3CCCC3"; String expectedCanonicalName1 = "N-cyclopentyl-5-ethyl-1-(4-fluorophenyl)piperidin-3-amine"; Long expectedPubchemId1 = 84000001L; Chemical testChemical1 = new Chemical(1L, expectedPubchemId1, expectedCanonicalName1, expectedSmiles1); testChemical1.setInchi(expectedInchi1); String expectedInchi2 = "InChI=1S/C16H23FN2/c17-13-5-3-9-16(11-13)19-10-4-8-15(12-19)18-14-6-1-2-7-14/h3,5,9,11,14-15,18H,1-2,4,6-8,10,12H2"; String expectedSmiles2 = "C1CCC(C1)NC2CCCN(C2)C3=CC(=CC=C3)F"; String expectedCanonicalName2 = "N-cyclopentyl-1-(3-fluorophenyl)piperidin-3-amine"; Long expectedPubchemId2 = 84000002L; Chemical testChemical2 = new Chemical(2L, expectedPubchemId2, expectedCanonicalName2, expectedSmiles2); testChemical2.setInchi(expectedInchi2); List<Chemical> expectedChemicals = new ArrayList<>(); expectedChemicals.add(testChemical1); expectedChemicals.add(testChemical2); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader eventReader = factory.createXMLEventReader(new GZIPInputStream(new FileInputStream(testFile))); int counter = 0; Chemical actualChemical; while ((actualChemical = pubchemParser.extractNextChemicalFromXMLStream(eventReader)) != null) { Chemical expectedChemical = expectedChemicals.get(counter); assertEquals("Inchis parsed from the xml file should be the same as expected", expectedChemical.getInChI(), actualChemical.getInChI()); assertEquals("Canonical name parsed from the xml file should be the same as expected", expectedChemical.getCanon(), actualChemical.getCanon()); assertEquals("Smiles parsed from the xml file should be the same as expected", expectedChemical.getSmiles(), actualChemical.getSmiles()); assertEquals("Pubchem id parsed from the xml file should be the same as expected", expectedChemical.getPubchemID(), actualChemical.getPubchemID()); counter++; } assertEquals("Two chemicals should be parsed from the xml file", 2, counter); }
MechanisticValidator extends BiointerpretationProcessor { public void init() throws IOException, ReactionException, LicenseProcessingException { erosCorpus = new ErosCorpus(); erosCorpus.loadValidationCorpus(); blacklistedInchisCorpus = new BlacklistedInchisCorpus(); blacklistedInchisCorpus.loadCorpus(); projector = new ReactionProjector(true); initReactors(); markInitialized(); } MechanisticValidator(NoSQLAPI api); @Override String getName(); void init(); void initReactors(); Integer scoreReactionBasedOnRO( Reactor reactor, List<Molecule> substrates, Set<String> expectedProductInchis, Ero ero, Long newRxnId); Map<Integer, List<Ero>> validateOneReaction(Long rxnId); static final String MOL_EXPORTER_INCHI_OPTIONS_FOR_INCHI_COMPARISON; }
@Test public void testMechanisticValidatorIsMatchingTheCorrectROsToReaction() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); idToInchi.put(1L, "InChI=1S/p+1"); idToInchi.put(2L, "InChI=1S/C5H10O/c1-3-4-5(2)6/h3-4H2,1-2H3"); idToInchi.put(3L, "InChI=1S/C5H12O/c1-3-4-5(2)6/h5-6H,3-4H2,1-2H3/t5-/m1/s1"); JSONObject expectedResult = new JSONObject(); expectedResult.put("3", "4"); expectedResult.put("337", "4"); expectedResult.put("340", "4"); Long[] products = {1L, 2L}; Long[] substrates = {3L}; Integer[] substrateCoefficients = {1}; Integer[] productCoefficients = {1, 1}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); MechanisticValidator mechanisticValidator = new MechanisticValidator(mockNoSQLAPI); mechanisticValidator.init(); mechanisticValidator.run(); assertEquals("One reaction should be written to the DB", 1, mockAPI.getWrittenReactions().size()); assertEquals("The mechanistic validator result should be equal to the expected result", expectedResult.toString(), mockAPI.getWrittenReactions().get(0).getMechanisticValidatorResult().toString()); } @Test public void testMechanisticValidatorDoesNotAddAnyROScoresWhenNoMatchesHappen() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); idToInchi.put(1L, "InChI=1S/p+1"); idToInchi.put(2L, "InChI=1S/H2O/h1H2"); Long[] products = {2L}; Long[] substrates = {1L}; Integer[] substrateCoefficients = {1}; Integer[] productCoefficients = {1}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); MechanisticValidator mechanisticValidator = new MechanisticValidator(mockNoSQLAPI); mechanisticValidator.init(); mechanisticValidator.run(); assertEquals("One reaction should be written to the DB", 1, mockAPI.getWrittenReactions().size()); assertEquals("The mechanistic validator result should be null since no ROs should react with the reaction", null, mockAPI.getWrittenReactions().get(0).getMechanisticValidatorResult()); } @Test public void testMechanisticValidatorIsMatchingTheCorrectROsToReactionThatAreNotPerfect() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); idToInchi.put(1L, "InChI=1S/p+1"); idToInchi.put(2L, "InChI=1S/C25H40N7O19P3S/c1-25(2,20(38)23(39)28-6-5-14(33)27-7-8-55-16(36)4-3-15(34)35)10-48-54(45,46)51-53(43,44)47-9-13-19(50-52(40,41)42)18(37)24(49-13)32-12-31-17-21(26)29-11-30-22(17)32/h11-13,18-20,24,37-38H,3-10H2,1-2H3,(H,27,33)(H,28,39)(H,34,35)(H,43,44)(H,45,46)(H2,26,29,30)(H2,40,41,42)/t13-,18-,19-,20+,24-/m1/s1"); idToInchi.put(3L, "InChI=1S/C4H6O3/c5-3-1-2-4(6)7/h3H,1-2H2,(H,6,7)"); Long[] products = {1L, 2L}; Long[] substrates = {3L}; JSONObject expectedResult = new JSONObject(); expectedResult.put("284", "3"); Integer[] substrateCoefficients = {1}; Integer[] productCoefficients = {1, 1}; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); MechanisticValidator mechanisticValidator = new MechanisticValidator(mockNoSQLAPI); mechanisticValidator.init(); mechanisticValidator.run(); assertEquals("One reaction should be written to the DB", 1, mockAPI.getWrittenReactions().size()); assertEquals("The mechanistic validator result should be equal to the expected result", expectedResult.toString(), mockAPI.getWrittenReactions().get(0).getMechanisticValidatorResult().toString()); } @Test public void testMechanisticValidatorIsCorrectlyUsingCoefficients() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); idToInchi.put(1L, "InChI=1S/CH4O/c1-2/h2H,1H3"); idToInchi.put(2L, "InChI=1S/CH5O4P/c1-5-6(2,3)4/h1H3,(H2,2,3,4)"); Long[] products = {1L, 2L}; Long[] substrates = {1L, 2L}; Integer[] substrateCoefficients = {2, 1}; Integer[] productCoefficients = {1, 2}; JSONObject expectedResult = new JSONObject(); expectedResult.put("165", "3"); Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); MechanisticValidator mechanisticValidator = new MechanisticValidator(mockNoSQLAPI); mechanisticValidator.init(); mechanisticValidator.run(); assertEquals("One reaction should be written to the DB", 1, mockAPI.getWrittenReactions().size()); assertEquals("The mechanistic validator result should be equal to the expected result", expectedResult.toString(), mockAPI.getWrittenReactions().get(0).getMechanisticValidatorResult().toString()); } @Test public void testMechanisticValidatorMatchesNonPrimaryReactorPrediction() throws Exception { List<Reaction> testReactions = new ArrayList<>(); Map<Long, String> idToInchi = new HashMap<>(); Long substrateId = 1L; Long productId = 2L; String substrateInchi = "InChI=1S/C15H10O7/c16-7-4-10(19)12-11(5-7)22-15(14(21)13(12)20)6-1-2-8(17)9(18)3-6/h1-5,16-19,21H"; String productInchi = "InChI=1S/C16H12O7/c1-22-11-3-2-7(4-9(11)18)16-15(21)14(20)13-10(19)5-8(17)6-12(13)23-16/h2-6,17-19,21H,1H3"; idToInchi.put(substrateId, substrateInchi); idToInchi.put(productId, productInchi); Long[] substrates = {substrateId}; Long[] products = {productId}; Integer[] substrateCoefficients = {1}; Integer[] productCoefficients = {1}; String expectedRo = "358"; String expectedScore = "4"; Reaction testReaction = utilsObject.makeTestReaction(substrates, products, substrateCoefficients, productCoefficients, true); testReactions.add(testReaction); MockedNoSQLAPI mockAPI = new MockedNoSQLAPI(); mockAPI.installMocks(testReactions, utilsObject.SEQUENCES, utilsObject.ORGANISM_NAMES, idToInchi); NoSQLAPI mockNoSQLAPI = mockAPI.getMockNoSQLAPI(); MechanisticValidator mechanisticValidator = new MechanisticValidator(mockNoSQLAPI); mechanisticValidator.init(); mechanisticValidator.run(); assertEquals("One reaction should be written to the DB", 1, mockAPI.getWrittenReactions().size()); assertTrue("The mechanistic validator result should contain the expected RO as a key.", mockAPI.getWrittenReactions().get(0).getMechanisticValidatorResult().has(expectedRo)); assertEquals("The mechanistic validator result should contain the correct score for that RO.", expectedScore, mockAPI.getWrittenReactions().get(0).getMechanisticValidatorResult().get(expectedRo)); }
ImportantChemicalsWikipedia { public String formatInchiString(String inchi) { String tmpInchi = inchi.replaceAll("\\s+",""); String formattedInchi = tmpInchi.replaceAll("InChI[0-9]?", "InChI"); return formattedInchi; } ImportantChemicalsWikipedia(); String extractInchiFromLine(String line); String formatInchiString(String inchi); boolean isChemaxonValidInchi(String inchi); void processInchiLine(String line); void processLine(String line); void writeToTSV(String outputPath); void writeToJSON(String outputPath); static void main(final String[] args); static final CSVFormat TSV_FORMAT; static final String OPTION_WIKIPEDIA_DUMP_FULL_PATH; static final String OPTION_OUTPUT_PATH; static final String OPTION_TSV_OUTPUT; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }
@Test public void testFormatInchiString() throws Exception { ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia(); for (InchiFormattingTestCase testcase : INCHI_FORMATTING_TEST_CASES) { assertEquals( "Testing case: " + testcase.getDescription(), importantChemicalsWikipedia.formatInchiString(testcase.getMatchedInchi()), testcase.getExpectedInchi() ); } }
ErosCorpus implements Iterable<Ero> { public void filterCorpusBySubstrateCount(Integer count) { filterCorpus(ro -> ro.getSubstrate_count().equals(count)); } ErosCorpus(List<Ero> ros); ErosCorpus(); List<Ero> getRos(); void setRos(List<Ero> eros); void loadValidationCorpus(); void loadCorpus(InputStream erosStream); List<Integer> getRoIds(); void filterCorpus(Predicate<Ero> filter); void filterCorpusById(List<Integer> roIdList); void filterCorpusByIdFile(File roIdFile); void filterCorpusBySubstrateCount(Integer count); void filterCorpusByProductCount(Integer count); void retainNamedRos(); Ero getEro(Integer roId); @Override Iterator<Ero> iterator(); }
@Test public void filterCorpusBySubstrateCount() throws Exception { ErosCorpus fullCorpus = new ErosCorpus(); fullCorpus.loadValidationCorpus(); ErosCorpus corpusOneSubstrate = new ErosCorpus(); corpusOneSubstrate.loadValidationCorpus(); corpusOneSubstrate.filterCorpusBySubstrateCount(1); assertEquals("One substrate ERO lists match in size", fullCorpus.getRos().stream(). filter(ero -> ero.getSubstrate_count().equals(1)).collect(Collectors.toList()).size(), corpusOneSubstrate.getRos().size() ); assertEquals("Re-filtering substrate count filtered eros yields same list", corpusOneSubstrate.getRos().stream(). filter(ero -> ero.getSubstrate_count().equals(1)).collect(Collectors.toList()), corpusOneSubstrate.getRos() ); ErosCorpus corpusTwoSubstrates = new ErosCorpus(); corpusTwoSubstrates.loadValidationCorpus(); corpusTwoSubstrates.filterCorpusBySubstrateCount(2); assertEquals("Two substrates ERO lists match in size", fullCorpus.getRos().stream(). filter(ero -> ero.getSubstrate_count().equals(2)).collect(Collectors.toList()).size(), corpusTwoSubstrates.getRos().size() ); assertEquals("Re-filtering substrate count filtered eros yields same list", corpusTwoSubstrates.getRos().stream(). filter(ero -> ero.getSubstrate_count().equals(2)).collect(Collectors.toList()), corpusTwoSubstrates.getRos() ); }
FullReactionBuilder { public Reactor buildReaction(List<RxnMolecule> rxnMolecules, Reactor seedReactor) throws ReactionException { if (!DbAPI.areAllOneSubstrate(rxnMolecules) || !DbAPI.areAllOneProduct(rxnMolecules)) { throw new IllegalArgumentException("FullReactionBuilder only handles one substrate, one product reactions."); } List<Molecule> allSubstrates = rxnMolecules.stream() .map(rxn -> getOnlySubstrate(rxn)).collect(Collectors.toList()); Molecule substructure = mcsCalculator.getMCS(allSubstrates); Molecule firstSubstrate = allSubstrates.get(0); Molecule expectedProduct = getOnlyProduct(rxnMolecules.get(0)); try { searcher.initSearch(seedReactor, firstSubstrate, expectedProduct, substructure); } catch (SearchException e) { LOGGER.warn("SearchException on ExpandedReactionSearcher.init(): %s", e.getMessage()); throw new ReactionException(e.getMessage()); } Reactor fullReactor; while ((fullReactor = searcher.getNextReactor()) != null) { if (checkReactorAgainstReactions(fullReactor, rxnMolecules)) { return fullReactor; } } LOGGER.warn("Didn't find an expansion that fit all reactions. Returning seed reactor only."); return seedReactor; } FullReactionBuilder( McsCalculator mcsCalculator, ExpandedReactionSearcher searcher, ReactionProjector projector); Reactor buildReaction(List<RxnMolecule> rxnMolecules, Reactor seedReactor); boolean checkReactorAgainstReactions(Reactor fullReactor, List<RxnMolecule> reactions); Molecule getOnlySubstrate(RxnMolecule molecule); Molecule getOnlyProduct(RxnMolecule molecule); }
@Test public void testTwoReactionsOneReactorMatchesBoth() throws ReactionException, IOException { Mockito.when(mockSearcher.getNextReactor()) .thenReturn(reactorMatch) .thenReturn(null); FullReactionBuilder reactionBuilder = new FullReactionBuilder(mockMcs, mockSearcher, PROJECTOR); Reactor fullReactor = reactionBuilder.buildReaction(rxnMoleculeList, DUMMY_SEED_REACTOR); assertEquals("Reaction should be as returned by the searcher.", reactorMatch, fullReactor); } @Test public void testTwoReactionsOneReactorMatchesOnlyOne() throws ReactionException { Mockito.when(mockSearcher.getNextReactor()) .thenReturn(reactorMismatch) .thenReturn(null); FullReactionBuilder reactionBuilder = new FullReactionBuilder(mockMcs, mockSearcher, PROJECTOR); Reactor fullReactor = reactionBuilder.buildReaction(rxnMoleculeList, DUMMY_SEED_REACTOR); assertEquals("Reaction should return seed reactor only.", DUMMY_SEED_REACTOR, fullReactor); } @Test public void testTwoReactionsTwoReactorsSecondMatches() throws ReactionException { Mockito.when(mockSearcher.getNextReactor()) .thenReturn(reactorMismatch) .thenReturn(reactorMatch) .thenReturn(null); FullReactionBuilder reactionBuilder = new FullReactionBuilder(mockMcs, mockSearcher, PROJECTOR); Reactor fullReactor = reactionBuilder.buildReaction(rxnMoleculeList, DUMMY_SEED_REACTOR); assertEquals("Reaction should be the one that matches the reactions.", reactorMatch, fullReactor); }
OneSubstrateSubstructureSar implements Sar { @Override public boolean test(List<Molecule> substrates) { if (substrates.size() != 1) { return false; } searcher.setTarget(substrates.get(0)); try { return searcher.findFirst() != null; } catch (SearchException e) { LOGGER.error("Error on testing substrates with SAR %s", getSubstructureInchi()); return false; } } private OneSubstrateSubstructureSar(); OneSubstrateSubstructureSar(Molecule substructure, MolSearchOptions searchOptions); OneSubstrateSubstructureSar(Molecule substructure); @Override boolean test(List<Molecule> substrates); }
@Test public void oneSubstrateContainsSubstructure() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = Arrays.asList(containsBenzene); assertTrue("Substrate contains substructure.", sar.test(substrates)); } @Test public void oneSubstrateDoesntContainsSubstructure() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = Arrays.asList(noBenzene); assertFalse("Substrate does not contain substructure.", sar.test(substrates)); } @Test public void twoSubstratesRejects() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = Arrays.asList(noBenzene, containsBenzene); assertFalse("Can't operate on two substrates", sar.test(substrates)); } @Test public void NoSubstratesRejects() throws SearchException { Sar sar = new OneSubstrateSubstructureSar(benzene); List<Molecule> substrates = new ArrayList<>(); assertFalse("Can't operate on no substrates", sar.test(substrates)); }
ImportantChemicalsWikipedia { public String extractInchiFromLine(String line) { Matcher inchiMatcher = INCHI_PATTERN.matcher(line); if (inchiMatcher.matches()) { return inchiMatcher.group(1); } return null; } ImportantChemicalsWikipedia(); String extractInchiFromLine(String line); String formatInchiString(String inchi); boolean isChemaxonValidInchi(String inchi); void processInchiLine(String line); void processLine(String line); void writeToTSV(String outputPath); void writeToJSON(String outputPath); static void main(final String[] args); static final CSVFormat TSV_FORMAT; static final String OPTION_WIKIPEDIA_DUMP_FULL_PATH; static final String OPTION_OUTPUT_PATH; static final String OPTION_TSV_OUTPUT; static final String HELP_MESSAGE; static final List<Option.Builder> OPTION_BUILDERS; static final HelpFormatter HELP_FORMATTER; }
@Test public void testExtractInchiFromLine() throws Exception { ImportantChemicalsWikipedia importantChemicalsWikipedia = new ImportantChemicalsWikipedia(); for (InchiFormattingTestCase testcase : INCHI_FORMATTING_TEST_CASES) { assertEquals( "Testing case: " + testcase.getDescription(), importantChemicalsWikipedia.extractInchiFromLine(testcase.getExtractedLine()), testcase.getMatchedInchi() ); } }
McsCalculator { public Molecule getMCS(List<Molecule> molecules) { if (molecules.isEmpty()) { throw new IllegalArgumentException("Cannot get MCS of empty list of molecules."); } Molecule substructure = molecules.get(0); for (Molecule mol : molecules.subList(1, molecules.size())) { substructure = getMcsOfPair(substructure, mol); } return substructure; } McsCalculator(McsSearchOptions mcsOptions); Molecule getMCS(List<Molecule> molecules); static final McsSearchOptions REACTION_BUILDING_OPTIONS; static final McsSearchOptions SAR_OPTIONS; }
@Test public void testMcsCalculatorSimplePairs() throws IOException { McsCalculator calculator = new McsCalculator(McsCalculator.SAR_OPTIONS); Molecule mcs12 = calculator.getMCS(Arrays.asList(methylPyreneMol1, methylPyreneMol2)); Molecule mcs13 = calculator.getMCS(Arrays.asList(methylPyreneMol1, methylPyreneMol3)); Molecule mcs23 = calculator.getMCS(Arrays.asList(methylPyreneMol2, methylPyreneMol3)); String mcsInchi12 = MolExporter.exportToFormat(mcs12, INCHI_EXPORT_SETTINGS); String mcsInchi13 = MolExporter.exportToFormat(mcs13, INCHI_EXPORT_SETTINGS); String mcsInchi23 = MolExporter.exportToFormat(mcs23, INCHI_EXPORT_SETTINGS); assertEquals("MCS of one and two should be as expected.", METHYLPYRENE_INCHI, mcsInchi12); assertEquals("MCS of one and three should be as expected.", METHYLPYRENE_INCHI, mcsInchi13); assertEquals("MCS of two and three should be as expected.", METHYLPYRENE_INCHI, mcsInchi23); } @Test public void testSarOptionsMatchDifferentBondTypes() throws IOException { String firstSubstrateInchi = "InChI=1S/C7H12O2/c8-7(9)6-4-2-1-3-5-6/h6H,1-5H2,(H,8,9)"; String secondSubstrateInchi = "InChI=1S/C7H10O2/c8-7(9)6-4-2-1-3-5-6/h4H,1-3,5H2,(H,8,9)"; String expectedMcs = "InChI=1S/C7H10O2/c8-7(9)6-4-2-1-3-5-6/h4H,1-3,5H2,(H,8,9)"; Molecule firstSubstrate = MolImporter.importMol(firstSubstrateInchi, INCHI_IMPORT_SETTINGS); Molecule secondSubstrate = MolImporter.importMol(secondSubstrateInchi, INCHI_IMPORT_SETTINGS); McsCalculator calculator = new McsCalculator(McsCalculator.SAR_OPTIONS); Molecule mcs = calculator.getMCS(Arrays.asList(firstSubstrate, secondSubstrate)); String mcsInchi = MolExporter.exportToFormat(mcs, INCHI_EXPORT_SETTINGS); assertEquals("MCS should contain the ring despite different bond types in substrates.", expectedMcs, mcsInchi); } @Test public void testReactionOptionsMismatchDifferentBondTypes() throws IOException { String firstSubstrateInchi = "InChI=1S/C7H12O2/c8-7(9)6-4-2-1-3-5-6/h6H,1-5H2,(H,8,9)"; String secondSubstrateInchi = "InChI=1S/C7H10O2/c8-7(9)6-4-2-1-3-5-6/h4H,1-3,5H2,(H,8,9)"; String expectedMcs = "InChI=1S/C2H4O2/c1-2(3)4/h1H3,(H,3,4)"; Molecule firstSubstrate = MolImporter.importMol(firstSubstrateInchi, INCHI_IMPORT_SETTINGS); Molecule secondSubstrate = MolImporter.importMol(secondSubstrateInchi, INCHI_IMPORT_SETTINGS); McsCalculator calculator = new McsCalculator(McsCalculator.REACTION_BUILDING_OPTIONS); Molecule mcs = calculator.getMCS(Arrays.asList(firstSubstrate, secondSubstrate)); String mcsInchi = MolExporter.exportToFormat(mcs, INCHI_EXPORT_SETTINGS); assertEquals("MCS should not contain the ring due to different bond types in substrates.", expectedMcs, mcsInchi); } @Test public void testMcsCalculatorManyMolecules() throws IOException { List<Molecule> molecules = Arrays.asList(methylPyreneMol1, methylPyreneMol1, methylPyreneMol, methylPyreneMol2, methylPyreneMol3, methylPyreneMol1, methylPyreneMol3, methylPyreneMol, methylPyreneMol2); McsCalculator calculator = new McsCalculator(McsCalculator.SAR_OPTIONS); Molecule mcs = calculator.getMCS(molecules); String mcsInchi = MolExporter.exportToFormat(mcs, INCHI_EXPORT_SETTINGS); assertEquals("MCS of all molecules should be as expected.", METHYLPYRENE_INCHI, mcsInchi); } @Test public void testMcsCalculatorRingDoesntMatchChain() throws IOException { String benzeneInchi = "InChI=1/C6H6/c1-2-4-6-5-3-1/h1-6H"; String chainInchi = "InChI=1S/C5H12/c1-3-5-4-2/h3-5H2,1-2H3"; String expectedMcs = "InChI=1S Molecule benzene = MolImporter.importMol(benzeneInchi, INCHI_IMPORT_SETTINGS); Molecule chain = MolImporter.importMol(chainInchi, INCHI_IMPORT_SETTINGS); List<Molecule> inputMolecules = Arrays.asList(benzene, chain); McsCalculator calculator = new McsCalculator(McsCalculator.SAR_OPTIONS); Molecule mcs = calculator.getMCS(inputMolecules); String mcsInchi = MolExporter.exportToFormat(mcs, INCHI_EXPORT_SETTINGS); assertEquals("Mcs should be empty.", expectedMcs, mcsInchi); }