method2testcases
stringlengths
118
6.63k
### Question: PingLoopbackLinkFactory implements LinkFactory { @Override public boolean supports(LinkType linkType) { return PingLoopbackLink.LINK_TYPE.equals(linkType); } Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override boolean supports(LinkType linkType); }### Answer: @Test public void supports() { assertThat(pingLoopbackLinkFactory.supports(PingLoopbackLink.LINK_TYPE)).isEqualTo(true); assertThat(pingLoopbackLinkFactory.supports(LinkType.of("foo"))).isEqualTo(false); }
### Question: AsnInterledgerAddressCodec extends AsnIA5StringBasedObjectCodec<InterledgerAddress> { @Override public void encode(InterledgerAddress value) { setCharString(value == null ? "" : value.getValue()); } AsnInterledgerAddressCodec(); @Override InterledgerAddress decode(); @Override void encode(InterledgerAddress value); }### Answer: @Test public void encode() { codec.encode(InterledgerAddress.of(G_FOO)); assertThat(codec.getCharString()).isEqualTo(G_FOO); }
### Question: PingLoopbackLinkFactory implements LinkFactory { public Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ) { Objects.requireNonNull(operatorAddressSupplier, "operatorAddressSupplier must not be null"); Objects.requireNonNull(linkSettings, "linkSettings must not be null"); if (!this.supports(linkSettings.getLinkType())) { throw new LinkException( String.format("LinkType not supported by this factory. linkType=%s", linkSettings.getLinkType()), LinkId.of("n/a") ); } if (lazyPingLoopbackLink != null) { return lazyPingLoopbackLink; } else { synchronized (this) { if (lazyPingLoopbackLink == null) { lazyPingLoopbackLink = new PingLoopbackLink(operatorAddressSupplier, linkSettings); } return lazyPingLoopbackLink; } } } Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override boolean supports(LinkType linkType); }### Answer: @Test(expected = NullPointerException.class) public void constructLinkWithNullOperator() { try { pingLoopbackLinkFactory.constructLink(null, linkSettingsMock); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("operatorAddressSupplier must not be null"); throw e; } } @Test(expected = NullPointerException.class) public void constructLinkWithNullLinkSettings() { try { pingLoopbackLinkFactory.constructLink(() -> OPERATOR_ADDRESS, null); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("linkSettings must not be null"); throw e; } } @Test(expected = LinkException.class) public void constructLinkWithUnsupportedLinkType() { try { LinkSettings linkSettings = LinkSettings.builder() .linkType(LinkType.of("foo")) .build(); pingLoopbackLinkFactory.constructLink(() -> OPERATOR_ADDRESS, linkSettings); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("LinkType not supported by this factory. linkType=LinkType(FOO)"); throw e; } } @Test public void constructLink() { LinkSettings linkSettings = LinkSettings.builder() .linkType(PingLoopbackLink.LINK_TYPE) .build(); Link<?> link = pingLoopbackLinkFactory.constructLink(() -> OPERATOR_ADDRESS, linkSettings); link.setLinkId(LINK_ID); assertThat(link.getLinkId()).isEqualTo(LINK_ID); }
### Question: AbstractStatefulLink extends AbstractLink<L> implements StatefulLink<L> { @Override public final CompletableFuture<Void> connect() { try { if (this.connected.compareAndSet(NOT_CONNECTED, CONNECTED)) { logger.debug("[linktype={}] (operatorIlpAddress={}) connecting to linkId={}...", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId() ); return this.doConnect() .whenComplete(($, error) -> { if (error == null) { this.linkConnectionEventEmitter.emitEvent(LinkConnectedEvent.of(this)); logger.debug("[linktype={}] (Operator operatorIlpAddress={}) connected to linkId={}", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId() ); } else { this.connected.set(NOT_CONNECTED); final String errorMessage = String.format( "[linktype=%s] (Operator operatorIlpAddress=%s) was unable to connect to linkId=%s", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId().value() ); logger.error(errorMessage, error); } }); } else { logger.debug("[linktype={}] (Operator operatorIlpAddress={}) already connected to linkId={}", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId() ); return CompletableFuture.completedFuture(null); } } catch (RuntimeException e) { this.disconnect().join(); throw e; } catch (Exception e) { this.disconnect().join(); throw new RuntimeException(e.getMessage(), e); } } protected AbstractStatefulLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings, final LinkConnectionEventEmitter linkConnectionEventEmitter ); @Override final CompletableFuture<Void> connect(); abstract CompletableFuture<Void> doConnect(); @Override void close(); @Override final CompletableFuture<Void> disconnect(); abstract CompletableFuture<Void> doDisconnect(); @Override boolean isConnected(); @Override void addLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); @Override void removeLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); }### Answer: @Test public void connect() { assertThat(doConnectCalled.get()).isEqualTo(false); assertThat(link.isConnected()).isEqualTo(false); link.connect(); assertThat(doConnectCalled.get()).isEqualTo(true); assertThat(link.isConnected()).isEqualTo(true); verify(linkConnectionEventEmitterMock).emitEvent(Mockito.<LinkConnectedEvent>any()); verifyNoMoreInteractions(linkConnectionEventEmitterMock); }
### Question: AbstractStatefulLink extends AbstractLink<L> implements StatefulLink<L> { @Override public void close() { this.disconnect().join(); } protected AbstractStatefulLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings, final LinkConnectionEventEmitter linkConnectionEventEmitter ); @Override final CompletableFuture<Void> connect(); abstract CompletableFuture<Void> doConnect(); @Override void close(); @Override final CompletableFuture<Void> disconnect(); abstract CompletableFuture<Void> doDisconnect(); @Override boolean isConnected(); @Override void addLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); @Override void removeLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); }### Answer: @Test public void close() { assertThat(doConnectCalled.get()).isEqualTo(false); assertThat(link.isConnected()).isEqualTo(false); link.connect(); assertThat(doConnectCalled.get()).isEqualTo(true); assertThat(link.isConnected()).isEqualTo(true); link.close(); assertThat(doConnectCalled.get()).isEqualTo(true); assertThat(doDisconnectCalled.get()).isEqualTo(true); assertThat(link.isConnected()).isEqualTo(false); }
### Question: AbstractStatefulLink extends AbstractLink<L> implements StatefulLink<L> { @Override public final CompletableFuture<Void> disconnect() { try { if (this.connected.compareAndSet(CONNECTED, NOT_CONNECTED)) { logger.debug("[linktype={}] (ILPAddress={}) disconnecting from linkId={}...", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId() ); return this.doDisconnect() .whenComplete(($, error) -> { if (error == null) { this.linkConnectionEventEmitter.emitEvent(LinkDisconnectedEvent.of(this)); logger.debug("[linktype={}] (ILPAddress={}) disconnected from linkId={}", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId() ); } else { final String errorMessage = String.format( "[linktype=%s] While trying to disconnect linkId=%s from operatorIlpAddress=%s error=%s", this.getLinkSettings().getLinkType(), this.getLinkId(), this.operatorAddressAsString(), error.getMessage() ); logger.error(errorMessage, error); } }) .thenAccept(($) -> logger.debug("[linktype={}] (ILPAddress={}) disconnected from linkId={}", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId() )); } else { logger.debug("[linktype={}] (ILPAddress={}) already disconnected from linkId={}", this.getLinkSettings().getLinkType(), this.operatorAddressAsString(), this.getLinkId()); return CompletableFuture.completedFuture(null); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } protected AbstractStatefulLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings, final LinkConnectionEventEmitter linkConnectionEventEmitter ); @Override final CompletableFuture<Void> connect(); abstract CompletableFuture<Void> doConnect(); @Override void close(); @Override final CompletableFuture<Void> disconnect(); abstract CompletableFuture<Void> doDisconnect(); @Override boolean isConnected(); @Override void addLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); @Override void removeLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); }### Answer: @Test public void disconnect() { assertThat(doDisconnectCalled.get()).isEqualTo(false); assertThat(link.isConnected()).isEqualTo(false); link.connect(); assertThat(doConnectCalled.get()).isEqualTo(true); assertThat(link.isConnected()).isEqualTo(true); }
### Question: AbstractStatefulLink extends AbstractLink<L> implements StatefulLink<L> { @Override public void addLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener) { Objects.requireNonNull(linkConnectionEventListener); this.linkConnectionEventEmitter.addLinkConnectionEventListener(linkConnectionEventListener); } protected AbstractStatefulLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings, final LinkConnectionEventEmitter linkConnectionEventEmitter ); @Override final CompletableFuture<Void> connect(); abstract CompletableFuture<Void> doConnect(); @Override void close(); @Override final CompletableFuture<Void> disconnect(); abstract CompletableFuture<Void> doDisconnect(); @Override boolean isConnected(); @Override void addLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); @Override void removeLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); }### Answer: @Test public void addLinkEventListener() { final LinkConnectionEventListener linkConnectionEventListenerMock = new LinkConnectionEventListener() { @Override @Subscribe public void onConnect(LinkConnectedEvent event) { onConnectCalled.set(true); } @Override @Subscribe public void onDisconnect(LinkDisconnectedEvent event) { onDisconnectCalled.set(true); } }; final EventBus eventBus = new EventBus(); this.link = new TestAbstractStatefulLink( () -> OPERATOR_ADDRESS, LINK_SETTINGS, new EventBusConnectionEventEmitter(eventBus) ); link.setLinkId(LINK_ID); link.addLinkEventListener(linkConnectionEventListenerMock); assertThat(onConnectCalled.get()).isEqualTo(false); assertThat(onDisconnectCalled.get()).isEqualTo(false); link.connect(); assertThat(onConnectCalled.get()).isEqualTo(true); assertThat(onDisconnectCalled.get()).isEqualTo(false); link.sendPacket(mock(InterledgerPreparePacket.class)); assertThat(onConnectCalled.get()).isEqualTo(true); assertThat(onDisconnectCalled.get()).isEqualTo(false); link.disconnect(); assertThat(onConnectCalled.get()).isEqualTo(true); assertThat(onDisconnectCalled.get()).isEqualTo(true); link.sendPacket(mock(InterledgerPreparePacket.class)); assertThat(onConnectCalled.get()).isEqualTo(true); assertThat(onDisconnectCalled.get()).isEqualTo(true); } @Test public void sendWhenDisconnected() { LinkConnectionEventListener linkConnectionEventListenerMock = mock(LinkConnectionEventListener.class); link.addLinkEventListener(linkConnectionEventListenerMock); link.sendPacket(mock(InterledgerPreparePacket.class)); assertThat(onConnectCalled.get()).isEqualTo(false); assertThat(onDisconnectCalled.get()).isEqualTo(false); }
### Question: AbstractStatefulLink extends AbstractLink<L> implements StatefulLink<L> { @Override public void removeLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener) { Objects.requireNonNull(linkConnectionEventListener); this.linkConnectionEventEmitter.removeLinkConnectionEventListener(linkConnectionEventListener); } protected AbstractStatefulLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings, final LinkConnectionEventEmitter linkConnectionEventEmitter ); @Override final CompletableFuture<Void> connect(); abstract CompletableFuture<Void> doConnect(); @Override void close(); @Override final CompletableFuture<Void> disconnect(); abstract CompletableFuture<Void> doDisconnect(); @Override boolean isConnected(); @Override void addLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); @Override void removeLinkEventListener(final LinkConnectionEventListener linkConnectionEventListener); }### Answer: @Test public void removeLinkEventListener() { LinkConnectionEventListener linkConnectionEventListenerMock = mock(LinkConnectionEventListener.class); link.addLinkEventListener(linkConnectionEventListenerMock); link.removeLinkEventListener(linkConnectionEventListenerMock); link.connect(); link.disconnect(); verifyNoMoreInteractions(linkConnectionEventListenerMock); }
### Question: AsnBtpErrorDataCodec extends AsnBtpPacketDataCodec<BtpError> { @Override public BtpError decode() { return BtpError.builder() .requestId(getRequestId()) .errorCode(BtpErrorCode.fromCodeAsString(getValueAt(0))) .triggeredAt(getValueAt(2)) .errorData(getValueAt(3)) .subProtocols(getValueAt(4)) .build(); } AsnBtpErrorDataCodec(long requestId); @Override BtpError decode(); @Override void encode(final BtpError value); }### Answer: @Test public void decode() { final AsnUint8Codec uint8Codec = new AsnUint8Codec(); uint8Codec.encode((short) 2); codec.setValueAt(0, (short) 2); codec.setValueAt(1, 123L); codec.setValueAt(2, btpError); final BtpError decodedBtpError = codec.decode(); assertThat(decodedBtpError).isEqualTo(btpError); }
### Question: LoopbackLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void registerLinkHandler(LinkHandler ilpDataHandler) throws LinkHandlerAlreadyRegisteredException { throw new RuntimeException( "Loopback links never have incoming data, and thus should not have a registered DataHandler." ); } LoopbackLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings, final PacketRejector packetRejector ); @Override void registerLinkHandler(LinkHandler ilpDataHandler); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override String toString(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; static final InterledgerFulfillment LOOPBACK_FULFILLMENT; static final String SIMULATED_REJECT_ERROR_CODE; }### Answer: @Test(expected = RuntimeException.class) public void registerLinkHandler() { try { link.registerLinkHandler(incomingPreparePacket -> null); } catch (Exception e) { assertThat(e.getMessage()) .isEqualTo("Loopback links never have incoming data, and thus should not have a registered DataHandler."); throw e; } }
### Question: LoopbackLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @VisibleForTesting InterledgerResponsePacket sleepAndReject(InterledgerPreparePacket preparePacket, int sleepDuraction) { try { Thread.sleep(sleepDuraction); } catch (InterruptedException e) { throw new RuntimeException(e); } return packetRejector.reject(this.getLinkId(), preparePacket, InterledgerErrorCode.T03_CONNECTOR_BUSY, "Loopback set to exceed timeout via simulate_timeout=T03"); } LoopbackLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings, final PacketRejector packetRejector ); @Override void registerLinkHandler(LinkHandler ilpDataHandler); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override String toString(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; static final InterledgerFulfillment LOOPBACK_FULFILLMENT; static final String SIMULATED_REJECT_ERROR_CODE; }### Answer: @Test public void sendT03Packet() { final Map<String, String> customSettings = Maps.newHashMap(); customSettings.put(SIMULATED_REJECT_ERROR_CODE, InterledgerErrorCode.T03_CONNECTOR_BUSY_CODE); this.link = new LoopbackLink( () -> OPERATOR_ADDRESS, LinkSettings.builder().linkType(LoopbackLink.LINK_TYPE).customSettings(customSettings).build(), packetRejector ); link.setLinkId(LinkId.of("foo")); link.sleepAndReject(preparePacket(), 1).handle( fulfillPacket -> { logger.error("interledgerRejectPacket={}", fulfillPacket); fail("Expected a Reject"); }, rejectPacket -> assertThat(rejectPacket.getCode()).isEqualTo(InterledgerErrorCode.T03_CONNECTOR_BUSY) ); }
### Question: AbstractLink implements Link<L> { @Override public LinkId getLinkId() { if (linkId.get() == null) { throw new IllegalStateException("The LinkId must be set before using a Link"); } return linkId.get(); } protected AbstractLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings ); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override L getLinkSettings(); @Override void registerLinkHandler(final LinkHandler ilpDataHandler); @Override void unregisterLinkHandler(); @Override Optional<LinkHandler> getLinkHandler(); @Override String toString(); }### Answer: @Test(expected = IllegalStateException.class) public void getLinkIdWhenNull() { this.link = new TestAbstractLink( () -> OPERATOR_ADDRESS, LinkSettings.builder().linkType(LinkType.of("foo")).build() ); try { link.getLinkId(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("The LinkId must be set before using a Link"); throw e; } } @Test public void getLinkId() { assertThat(link.getLinkId()).isEqualTo(LINK_ID); }
### Question: AsnBtpErrorDataCodec extends AsnBtpPacketDataCodec<BtpError> { @Override public void encode(final BtpError value) { Objects.requireNonNull(value); setValueAt(0, value.getErrorCode().getCodeIdentifier()); setValueAt(1, value.getErrorCode().getCodeName()); setValueAt(2, value.getTriggeredAt()); setValueAt(3, value.getErrorData()); setValueAt(4, value.getSubProtocols()); } AsnBtpErrorDataCodec(long requestId); @Override BtpError decode(); @Override void encode(final BtpError value); }### Answer: @Test public void encode() { codec.encode(btpError); assertThat((short) codec.getValueAt(0)).isEqualTo(btpError.getType().getCode()); assertThat((long) codec.getValueAt(1)).isEqualTo(btpError.getRequestId()); assertThat((BtpError) codec.getValueAt(2)).isEqualTo(btpError); final BtpError decodedBtpError = codec.decode(); assertThat(decodedBtpError).isEqualTo(btpError); }
### Question: AbstractLink implements Link<L> { @Override public void setLinkId(final LinkId linkId) { if (!this.linkId.compareAndSet(null, Objects.requireNonNull(linkId))) { throw new IllegalStateException("LinkId may only be set once"); } } protected AbstractLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings ); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override L getLinkSettings(); @Override void registerLinkHandler(final LinkHandler ilpDataHandler); @Override void unregisterLinkHandler(); @Override Optional<LinkHandler> getLinkHandler(); @Override String toString(); }### Answer: @Test(expected = IllegalStateException.class) public void setLinkIdWhenAlreadySet() { try { link.setLinkId(LinkId.of("bar")); fail(); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("LinkId may only be set once"); throw e; } }
### Question: AbstractLink implements Link<L> { @Override public Supplier<InterledgerAddress> getOperatorAddressSupplier() { return operatorAddressSupplier; } protected AbstractLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings ); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override L getLinkSettings(); @Override void registerLinkHandler(final LinkHandler ilpDataHandler); @Override void unregisterLinkHandler(); @Override Optional<LinkHandler> getLinkHandler(); @Override String toString(); }### Answer: @Test public void getOperatorAddressSupplier() { assertThat(link.getOperatorAddressSupplier().get()).isEqualTo(OPERATOR_ADDRESS); }
### Question: AbstractLink implements Link<L> { @Override public L getLinkSettings() { return this.linkSettings; } protected AbstractLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final L linkSettings ); @Override LinkId getLinkId(); @Override void setLinkId(final LinkId linkId); @Override Supplier<InterledgerAddress> getOperatorAddressSupplier(); @Override L getLinkSettings(); @Override void registerLinkHandler(final LinkHandler ilpDataHandler); @Override void unregisterLinkHandler(); @Override Optional<LinkHandler> getLinkHandler(); @Override String toString(); }### Answer: @Test public void getLinkSettings() { assertThat(link.getLinkSettings()).isEqualTo(LINK_SETTINGS); }
### Question: LinkFactoryProvider { public LinkFactory getLinkFactory(final LinkType linkType) { Objects.requireNonNull(linkType, "linkType must not be null"); return Optional.ofNullable(this.linkFactories.get(linkType)) .orElseThrow(() -> new LinkException( String.format("No registered LinkFactory linkType=%s", linkType), LinkId.of("n/a")) ); } LinkFactoryProvider(); LinkFactoryProvider(final Map<LinkType, LinkFactory> linkFactories); LinkFactory getLinkFactory(final LinkType linkType); LinkFactory registerLinkFactory(final LinkType linkType, final LinkFactory linkFactory); }### Answer: @Test(expected = LinkException.class) public void getUnregisteredLinkFactory() { try { linkFactoryProvider.getLinkFactory(TEST_LINK_TYPE); } catch (LinkException e) { assertThat(e.getMessage()).isEqualTo("No registered LinkFactory linkType=LinkType(FOO)"); throw e; } }
### Question: LinkFactoryProvider { public LinkFactory registerLinkFactory(final LinkType linkType, final LinkFactory linkFactory) { Objects.requireNonNull(linkType, "linkType must not be null"); Objects.requireNonNull(linkFactory, "linkFactory must not be null"); return this.linkFactories.put(linkType, linkFactory); } LinkFactoryProvider(); LinkFactoryProvider(final Map<LinkType, LinkFactory> linkFactories); LinkFactory getLinkFactory(final LinkType linkType); LinkFactory registerLinkFactory(final LinkType linkType, final LinkFactory linkFactory); }### Answer: @Test(expected = NullPointerException.class) public void registerLinkFactoryWithNullLinkType() { try { linkFactoryProvider.registerLinkFactory(null, linkFactoryMock); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("linkType must not be null"); throw e; } } @Test(expected = NullPointerException.class) public void registerLinkFactoryWithNullLinkFactory() { try { linkFactoryProvider.registerLinkFactory(TEST_LINK_TYPE, null); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("linkFactory must not be null"); throw e; } }
### Question: LoopbackLinkFactory implements LinkFactory { @Override public boolean supports(LinkType linkType) { return LoopbackLink.LINK_TYPE.equals(linkType); } LoopbackLinkFactory(final PacketRejector packetRejector); Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override boolean supports(LinkType linkType); }### Answer: @Test public void supports() { assertThat(loopbackLinkFactory.supports(LoopbackLink.LINK_TYPE)).isEqualTo(true); assertThat(loopbackLinkFactory.supports(LinkType.of("foo"))).isEqualTo(false); }
### Question: LoopbackLinkFactory implements LinkFactory { public Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ) { Objects.requireNonNull(operatorAddressSupplier, "operatorAddressSupplier must not be null"); Objects.requireNonNull(linkSettings, "linkSettings must not be null"); if (!this.supports(linkSettings.getLinkType())) { throw new LinkException( String.format("LinkType not supported by this factory. linkType=%s", linkSettings.getLinkType()), LinkId.of("n/a") ); } return new LoopbackLink(operatorAddressSupplier, linkSettings, packetRejector); } LoopbackLinkFactory(final PacketRejector packetRejector); Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override boolean supports(LinkType linkType); }### Answer: @Test(expected = NullPointerException.class) public void constructLinkWithNullOperator() { try { loopbackLinkFactory.constructLink(null, linkSettingsMock); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("operatorAddressSupplier must not be null"); throw e; } } @Test(expected = NullPointerException.class) public void constructLinkWithNullLinkSettings() { try { loopbackLinkFactory.constructLink(() -> OPERATOR_ADDRESS, null); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("linkSettings must not be null"); throw e; } } @Test(expected = LinkException.class) public void constructLinkWithUnsupportedLinkType() { try { LinkSettings linkSettings = LinkSettings.builder() .linkType(LinkType.of("foo")) .build(); loopbackLinkFactory.constructLink(() -> OPERATOR_ADDRESS, linkSettings); fail(); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("LinkType not supported by this factory. linkType=LinkType(FOO)"); throw e; } } @Test public void constructLink() { LinkSettings linkSettings = LinkSettings.builder() .linkType(LoopbackLink.LINK_TYPE) .build(); Link<?> link = loopbackLinkFactory.constructLink(() -> OPERATOR_ADDRESS, linkSettings); link.setLinkId(linkId); assertThat(link.getLinkId()).isEqualTo(linkId); }
### Question: AsnIldcpResponseCodec extends AsnSequenceCodec<IldcpResponse> { @Override public IldcpResponse decode() { return IldcpResponse.builder() .clientAddress(getValueAt(0)) .assetScale(getValueAt(1)) .assetCode(getValueAt(2)) .build(); } AsnIldcpResponseCodec(); @Override IldcpResponse decode(); @Override void encode(IldcpResponse value); }### Answer: @Test public void decode() { codec.encode(RESPONSE); assertThat(codec.getCodecAt(0).decode()).isEqualTo(FOO_ADDRESS); assertThat(codec.getCodecAt(1).decode()).isEqualTo((short) 9); assertThat(codec.getCodecAt(2).decode()).isEqualTo(BTC); }
### Question: StatelessSpspReceiverLinkFactory implements LinkFactory { @Override public boolean supports(LinkType linkType) { return StatelessSpspReceiverLink.LINK_TYPE.equals(linkType); } StatelessSpspReceiverLinkFactory( final PacketRejector packetRejector, final StatelessStreamReceiver statelessStreamReceiver ); @Override Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override boolean supports(LinkType linkType); }### Answer: @Test public void supports() { assertThat(statelessSpspReceiverLinkFactory.supports(StatelessSpspReceiverLink.LINK_TYPE)).isEqualTo(true); assertThat(statelessSpspReceiverLinkFactory.supports(LinkType.of("foo"))).isEqualTo(false); }
### Question: StatelessSpspReceiverLinkFactory implements LinkFactory { @Override public Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ) { Objects.requireNonNull(operatorAddressSupplier, "operatorAddressSupplier must not be null"); Objects.requireNonNull(linkSettings, "linkSettings must not be null"); if (!this.supports(linkSettings.getLinkType())) { throw new LinkException( String.format("LinkType not supported by this factory. linkType=%s", linkSettings.getLinkType()), LinkId.of("n/a") ); } Preconditions.checkArgument( StatelessSpspReceiverLinkSettings.class.isAssignableFrom(linkSettings.getClass()), "Constructing an instance of StatelessSpspReceiverLink requires an instance of StatelessSpspReceiverLinkSettings" ); return new StatelessSpspReceiverLink( operatorAddressSupplier, (StatelessSpspReceiverLinkSettings) linkSettings, statelessStreamReceiver ); } StatelessSpspReceiverLinkFactory( final PacketRejector packetRejector, final StatelessStreamReceiver statelessStreamReceiver ); @Override Link<?> constructLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings ); @Override boolean supports(LinkType linkType); }### Answer: @Test public void constructLinkWithNullOperator() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("operatorAddressSupplier must not be null"); statelessSpspReceiverLinkFactory.constructLink(null, linkSettingsMock); } @Test public void constructLinkWithNullLinkSettings() { expectedException.expect(NullPointerException.class); expectedException.expectMessage("linkSettings must not be null"); statelessSpspReceiverLinkFactory.constructLink(() -> OPERATOR_ADDRESS, null); } @Test public void constructLinkWithUnsupportedLinkType() { expectedException.expect(LinkException.class); expectedException.expectMessage("LinkType not supported by this factory. linkType=LinkType(FOO)"); LinkSettings linkSettings = LinkSettings.builder() .linkType(LinkType.of("foo")) .build(); statelessSpspReceiverLinkFactory.constructLink(() -> OPERATOR_ADDRESS, linkSettings); } @Test public void constructLink() { LinkSettings linkSettings = StatelessSpspReceiverLinkSettings.builder() .assetCode("USD") .assetScale((short) 9) .build(); StatelessSpspReceiverLink link = (StatelessSpspReceiverLink) statelessSpspReceiverLinkFactory .constructLink(() -> OPERATOR_ADDRESS, linkSettings); assertThat(link.getLinkSettings().assetCode()).isEqualTo("USD"); assertThat(link.getLinkSettings().assetScale()).isEqualTo(9); assertThat(link.getOperatorAddressSupplier().get()).isEqualTo(OPERATOR_ADDRESS); }
### Question: StatelessSpspReceiverLink extends AbstractLink<StatelessSpspReceiverLinkSettings> implements Link<StatelessSpspReceiverLinkSettings> { @Override public void registerLinkHandler(final LinkHandler ilpDataHandler) throws LinkHandlerAlreadyRegisteredException { throw new RuntimeException( "StatelessSpspReceiver links never emit data, and thus should not have a registered DataHandler." ); } StatelessSpspReceiverLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final StatelessSpspReceiverLinkSettings linkSettings, final StreamReceiver streamReceiver ); @Override void registerLinkHandler(final LinkHandler ilpDataHandler); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override String toString(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; }### Answer: @Test(expected = RuntimeException.class) public void registerLinkHandler() { try { link.registerLinkHandler(incomingPreparePacket -> null); } catch (Exception e) { assertThat(e.getMessage()) .isEqualTo("StatelessSpspReceiver links never emit data, and thus should not have a registered DataHandler."); throw e; } }
### Question: StatelessSpspReceiverLink extends AbstractLink<StatelessSpspReceiverLinkSettings> implements Link<StatelessSpspReceiverLinkSettings> { @Override public InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket) { Objects.requireNonNull(preparePacket, "preparePacket must not be null"); return streamReceiver.receiveMoney(preparePacket, this.getOperatorAddressSupplier().get(), this.denomination) .map(fulfillPacket -> { if (logger.isDebugEnabled()) { logger.debug("Packet fulfilled! preparePacket={} fulfillPacket={}", preparePacket, fulfillPacket); } return fulfillPacket; }, rejectPacket -> { if (logger.isDebugEnabled()) { logger.debug("Packet rejected! preparePacket={} rejectPacket={}", preparePacket, rejectPacket); } return rejectPacket; } ); } StatelessSpspReceiverLink( final Supplier<InterledgerAddress> operatorAddressSupplier, final StatelessSpspReceiverLinkSettings linkSettings, final StreamReceiver streamReceiver ); @Override void registerLinkHandler(final LinkHandler ilpDataHandler); @Override InterledgerResponsePacket sendPacket(final InterledgerPreparePacket preparePacket); @Override String toString(); static final String LINK_TYPE_STRING; static final LinkType LINK_TYPE; }### Answer: @Test(expected = NullPointerException.class) public void sendPacketWithNull() { try { link.sendPacket(null); } catch (NullPointerException e) { assertThat(e.getMessage()).isEqualTo("preparePacket must not be null"); throw e; } } @Test public void sendPacket() { final InterledgerFulfillPacket actualFulfillPacket = InterledgerFulfillPacket.builder() .fulfillment(ALL_ZEROS_FULFILLMENT) .build(); when(streamReceiverMock.receiveMoney(any(), any(), any())).thenReturn(actualFulfillPacket); final InterledgerPreparePacket preparePacket = preparePacket(); link.sendPacket(preparePacket).handle( fulfillPacket -> { assertThat(fulfillPacket).isEqualTo(actualFulfillPacket); }, rejectPacket -> { logger.error("rejectPacket={}", rejectPacket); fail("Expected a Fulfill"); } ); }
### Question: AsnIldcpResponseCodec extends AsnSequenceCodec<IldcpResponse> { @Override public void encode(IldcpResponse value) { setValueAt(0, value.getClientAddress()); setValueAt(1, value.getAssetScale()); setValueAt(2, value.getAssetCode()); } AsnIldcpResponseCodec(); @Override IldcpResponse decode(); @Override void encode(IldcpResponse value); }### Answer: @Test public void encode() { codec.encode(RESPONSE); final IldcpResponse actual = codec.decode(); assertThat(actual).isEqualTo(RESPONSE); }
### Question: AsnIldcpResponsePacketDataCodec extends AsnSequenceCodec<IldcpResponsePacket> { @Override public void encode(IldcpResponsePacket value) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); try { IldcpCodecContextFactory.oer().write(value.getIldcpResponse(), os); } catch (IOException e) { throw new IldcpCodecException(e.getMessage(), e); } setValueAt(0, value.getFulfillment()); setValueAt(1, os.toByteArray()); } AsnIldcpResponsePacketDataCodec(); @Override IldcpResponsePacket decode(); @Override void encode(IldcpResponsePacket value); }### Answer: @Test public void encode() { codec.encode(packet); assertThat((InterledgerFulfillment) codec.getValueAt(0)) .isEqualTo(InterledgerFulfillment.of(new byte[32])); final byte[] encodedIldcpResponseBytes = codec.getValueAt(1); assertThat(Base64.getEncoder().encodeToString(encodedIldcpResponseBytes)).isEqualTo("C2V4YW1wbGUuZm9vCQNCVEM="); }
### Question: JsonParser { public static String serialize(Object object) { try { return new ObjectMapper().writeValueAsString(object); } catch (JsonProcessingException ex) { log.error(ex.getMessage(),ex); } return null; } static String serialize(Object object); static T deserialize(String json, Class<T> type); static T deserialize(String json, Class<?> type, Class<?> genericType); static String getValue(String key, String json); }### Answer: @Test public void serialize_JsonRole_shouldReturnOk() { Role role = getDefaultRole(); String expectedJsonRole = getJsonRole(getDefaultRole()); String jsonRole = JsonParser.serialize(role); assertTrue(jsonRole.equals(expectedJsonRole)); }
### Question: WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC); if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); } log.info("Web application fully configured"); } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); }### Answer: @Test public void testStartUpProdServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); webConfigurer.onStartup(servletContext); verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class)); } @Test public void testStartUpDevServletContext() throws ServletException { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT); webConfigurer.onStartup(servletContext); verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class)); }
### Question: WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> { @Override public void customize(WebServerFactory server) { setMimeMappings(server); if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) && server instanceof UndertowServletWebServerFactory) { ((UndertowServletWebServerFactory) server) .addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true)); } } WebConfigurer(Environment env, JHipsterProperties jHipsterProperties); @Override void onStartup(ServletContext servletContext); @Override void customize(WebServerFactory server); @Bean CorsFilter corsFilter(); }### Answer: @Test public void testCustomizeServletContainer() { env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg"); assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8"); assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8"); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull(); } @Test public void testUndertowHttp2Enabled() { props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0); UndertowServletWebServerFactory container = new UndertowServletWebServerFactory(); webConfigurer.customize(container); Builder builder = Undertow.builder(); container.getBuilderCustomizers().forEach(c -> c.customize(builder)); OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions"); assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue(); }
### Question: JsonParser { public static <T> T deserialize(String json, Class<T> type) { try { return new ObjectMapper().readValue(json,type); } catch (Exception ex) { log.error(ex.getMessage(),ex); } return null; } static String serialize(Object object); static T deserialize(String json, Class<T> type); static T deserialize(String json, Class<?> type, Class<?> genericType); static String getValue(String key, String json); }### Answer: @Test public void deserialize_RoleClass_shouldReturnOk() { String jsonRole = getJsonRole(getDefaultRole()); Role expectedRole = getDefaultRole(); Role role = JsonParser.deserialize(jsonRole,Role.class); assertTrue(role.getId().equals(expectedRole.getId())); assertTrue(role.getName().equals(expectedRole.getName())); }
### Question: IncomingMessageFormDefinitionDAOImpl extends HibernateGenericDAOImpl<IncomingMessageFormDefinitionImpl> implements IncomingMessageFormDefinitionDAO<IncomingMessageFormDefinitionImpl> { public IncomingMessageFormDefinition getByCode(String formCode) { logger.debug("variable passed to getByCode: " + formCode); try { Criterion code = Restrictions.eq("formCode", formCode); IncomingMessageFormDefinition definition = (IncomingMessageFormDefinition)this.getSessionFactory().getCurrentSession().createCriteria(this.getPersistentClass()) .add(code) .setMaxResults(1) .uniqueResult(); logger.debug(definition); return definition; } catch (HibernateException he) { logger.error("Persistence or JDBC Exception in getByCode", he); return null; } catch (Exception ex) { logger.error("Exception in getByCode", ex); return null; } } IncomingMessageFormDefinition getByCode(String formCode); }### Answer: @Test public void testGetByCode() { System.out.println("getByCode"); IncomingMessageFormDefinition result = imfDAO.getByCode(formCode); assertNotNull(result); assertEquals(result.getFormCode(), formCode); System.out.println(result.toString()); }
### Question: RancardGatewayMessageHandlerImpl implements GatewayMessageHandler { public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse) { logger.debug("Parsing message gateway response"); logger.debug(gatewayResponse); if(message == null) return null; if(gatewayResponse.isEmpty()) return null; Set<GatewayResponse> responses = new HashSet<GatewayResponse>(); String[] responseLines = gatewayResponse.trim().split("\n"); for(String line : responseLines){ if(line.trim().isEmpty()) continue; String[] responseParts = line.split(" "); if (responseParts[0].trim().equals("Status:")) continue; GatewayResponse response = getCoreManager().createGatewayResponse(); response.setRequestId(message.getRequestId()); response.setGatewayRequest(message); response.setDateCreated(new Date()); if(responseParts[0].equalsIgnoreCase("OK:")){ handleResponseOk(message, responseParts, response); } else if(responseParts[0].equalsIgnoreCase("ERROR:")){ logger.error("Gateway returned error: " + gatewayResponse); handleResponseError(message, responseParts, response); } else{ response.setResponseText(line.trim()); response.setMessageStatus(MStatus.RETRY); } responses.add(response); } logger.debug(responses); return responses; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); void setOkMessageStatus(MStatus okMessageStatus); }### Answer: @Test public void shouldSetMessageStatusToCannotConnectWhenResponseMessageHasErrorWithCode901() { Set<GatewayResponse> responses = messageHandler.parseMessageResponse(gatewayRequest, "Status: Retry Sending\nERROR: 901"); assertNotNull(responses); assertEquals(1, responses.size()); Iterator<GatewayResponse> iterator = responses.iterator(); GatewayResponse errorResponse = iterator.next(); assertEquals(MStatus.CANNOT_CONNECT, errorResponse.getMessageStatus()); assertEquals(recipientNumber, errorResponse.getRecipientNumber()); } @Test public void shouldSetMessageStatusToSentWhenResponseMessageHasOk() { Set<GatewayResponse> responses = messageHandler.parseMessageResponse(gatewayRequest, "Status: Sent\nOK: " + recipientNumber); assertNotNull(responses); assertEquals(1, responses.size()); Iterator<GatewayResponse> iterator = responses.iterator(); GatewayResponse sentResponse = iterator.next(); assertEquals(MStatus.SENT, sentResponse.getMessageStatus()); assertEquals(recipientNumber, sentResponse.getRecipientNumber()); } @Test public void shouldSetMessageStatusToFailedWhenResponseMessageHasErrorWithCode() { Set<GatewayResponse> responses = messageHandler.parseMessageResponse(gatewayRequest, "Status: Retry Sending\nERROR: 111"); assertNotNull(responses); assertEquals(1, responses.size()); Iterator<GatewayResponse> iterator = responses.iterator(); GatewayResponse errorResponse = iterator.next(); assertEquals(MStatus.FAILED, errorResponse.getMessageStatus()); assertEquals(recipientNumber, errorResponse.getRecipientNumber()); } @Test public void shouldSetMessageStatusToRetryWhenResponseMessageHasErrorWithUnknownCode() { Set<GatewayResponse> responses = messageHandler.parseMessageResponse(gatewayRequest, "Status: Retry Sending\nERROR: Unknown"); assertNotNull(responses); assertEquals(1, responses.size()); Iterator<GatewayResponse> iterator = responses.iterator(); GatewayResponse errorResponse = iterator.next(); assertEquals(MStatus.RETRY, errorResponse.getMessageStatus()); assertEquals(recipientNumber, errorResponse.getRecipientNumber()); }
### Question: DummyGatewayMessageHandlerImpl implements GatewayMessageHandler { public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse) { if(message == null) return null; if(gatewayResponse.isEmpty()) return null; Set<GatewayResponse> responseList = new HashSet<GatewayResponse>(); GatewayResponse response = coreManager.createGatewayResponse(); response.setGatewayRequest(message); response.setMessageStatus(MStatus.DELIVERED); response.setRecipientNumber(message.getRecipientsNumber()); response.setGatewayMessageId(MotechIDGenerator.generateID(10).toString()); response.setRequestId(message.getRequestId()); response.setResponseText(gatewayResponse); response.setDateCreated(new Date()); responseList.add(response); return responseList; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testParseMessageResponse() { System.out.println("parseMessageResponse"); GatewayRequest message = null; String gatewayResponse = ""; GatewayRequest expResult = null; Set<GatewayResponse> result = dummyHandler.parseMessageResponse(message, gatewayResponse); assertEquals(expResult, result); }
### Question: DummyGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus parseMessageStatus(String gatewayResponse) { String status; String[] responseParts = gatewayResponse.split(" "); if(responseParts.length == 4){ status = responseParts[3]; } else{ status = ""; } return lookupStatus(status); } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testParseMessageStatus() { System.out.println("parseMessageStatus"); String messageStatus = "004"; MStatus expResult = MStatus.PENDING; MStatus result = dummyHandler.parseMessageStatus(messageStatus); assertEquals(expResult, result); }
### Question: DummyGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus lookupStatus(String code) { if(code.isEmpty()){ return MStatus.PENDING; } for(Entry<MStatus, String> entry: codeStatusMap.entrySet()){ if(entry.getValue().contains(code)){ return entry.getKey(); } } return MStatus.PENDING; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testLookupStatus() { System.out.println("lookupStatus"); String messageStatus = "004"; MStatus expResult = MStatus.DELIVERED; MStatus result = dummyHandler.lookupStatus(messageStatus); assertEquals(expResult, result); }
### Question: DummyGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus lookupResponse(String code) { if(code.isEmpty()){ return MStatus.SCHEDULED; } for(Entry<MStatus, String> entry: codeResponseMap.entrySet()){ if(entry.getValue().contains(code)){ return entry.getKey(); } } return MStatus.SCHEDULED; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testLookupResponse() { System.out.println("lookupResponse"); String messageStatus = "ID: somestatus"; MStatus expResult = MStatus.SCHEDULED; MStatus result = dummyHandler.lookupResponse(messageStatus); assertEquals(expResult, result); }
### Question: IVRNotificationMapping { public void setType(String type) { this.type = null; if ( type.equalsIgnoreCase(INFORMATIONAL) || type.equalsIgnoreCase(REMINDER) ) this.type = type; } long getId(); void setId(long id); String getType(); void setType(String type); String getIvrEntityName(); void setIvrEntityName(String ivrEntityName); @Override int hashCode(); @Override boolean equals(Object obj); static String INFORMATIONAL; static String REMINDER; }### Answer: @Test public void testSetType() { IVRNotificationMapping mapping = new IVRNotificationMapping(); mapping.setType(IVRNotificationMapping.INFORMATIONAL); assertEquals(IVRNotificationMapping.INFORMATIONAL, mapping.getType()); mapping.setType(IVRNotificationMapping.REMINDER); assertEquals(IVRNotificationMapping.REMINDER, mapping.getType()); mapping.setType("blah"); assertNull(mapping.getType()); }
### Question: IMPManagerImpl implements ApplicationContextAware, IMPManager { public CommandAction createCommandAction() { return (CommandAction)context.getBean("formCmdAxn"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test public void testCreateCommandAction() { System.out.println("createCommandAction"); CommandAction result = impManager.createCommandAction(); assertNotNull(result); }
### Question: IntellIVRGatewayMessageHandler implements GatewayMessageHandler { public MStatus lookupStatus(String code) { MStatus status = responseMap.get(code); return status != null ? status : defaultStatus; } Set<GatewayResponse> parseMessageResponse(GatewayRequest gatewayRequest, String statusMessage); MStatus parseMessageStatus(String messageStatus); MStatus lookupResponse(String code); MStatus lookupStatus(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<String, MStatus> getStatusMap(); void setStatusMap(Map<String, MStatus> statusMap); Map<String, MStatus> getResponseMap(); void setResponseMap(Map<String, MStatus> responseMap); }### Answer: @Test public void testLookupStatus() { for ( String code : statusCodes.keySet()) assertEquals(statusCodes.get(code), intellIVRMessageHandler.lookupStatus(code)); }
### Question: IntellIVRGatewayMessageHandler implements GatewayMessageHandler { public MStatus lookupResponse(String code) { MStatus responseStatus = responseMap.get(code); return responseStatus != null ? responseStatus : defaultResponse; } Set<GatewayResponse> parseMessageResponse(GatewayRequest gatewayRequest, String statusMessage); MStatus parseMessageStatus(String messageStatus); MStatus lookupResponse(String code); MStatus lookupStatus(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<String, MStatus> getStatusMap(); void setStatusMap(Map<String, MStatus> statusMap); Map<String, MStatus> getResponseMap(); void setResponseMap(Map<String, MStatus> responseMap); }### Answer: @Test public void testLookupResponse() { for ( String code : statusCodes.keySet()) assertEquals(statusCodes.get(code), intellIVRMessageHandler.lookupResponse(code)); }
### Question: IntellIVRGatewayMessageHandler implements GatewayMessageHandler { public MStatus parseMessageStatus(String messageStatus) { return lookupStatus(messageStatus); } Set<GatewayResponse> parseMessageResponse(GatewayRequest gatewayRequest, String statusMessage); MStatus parseMessageStatus(String messageStatus); MStatus lookupResponse(String code); MStatus lookupStatus(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<String, MStatus> getStatusMap(); void setStatusMap(Map<String, MStatus> statusMap); Map<String, MStatus> getResponseMap(); void setResponseMap(Map<String, MStatus> responseMap); }### Answer: @Test public void testParseMessageStatus() { for ( String code : statusCodes.keySet()) assertEquals(statusCodes.get(code), intellIVRMessageHandler.parseMessageStatus(code)); }
### Question: IntellIVRGatewayMessageHandler implements GatewayMessageHandler { public Set<GatewayResponse> parseMessageResponse(GatewayRequest gatewayRequest, String statusMessage) { Set<GatewayResponse> responses = new HashSet<GatewayResponse>(); GatewayResponse gwResponse = coreManager.createGatewayResponse(); gwResponse.setGatewayRequest(gatewayRequest); gwResponse.setGatewayMessageId(gatewayRequest.getMessageRequest().getId().toString()); gwResponse.setRecipientNumber(gatewayRequest.getRecipientsNumber()); gwResponse.setRequestId(gatewayRequest.getRequestId()); gwResponse.setResponseText(statusMessage); gwResponse.setMessageStatus(lookupStatus(statusMessage)); gwResponse.setDateCreated(new Date()); responses.add(gwResponse); return responses; } Set<GatewayResponse> parseMessageResponse(GatewayRequest gatewayRequest, String statusMessage); MStatus parseMessageStatus(String messageStatus); MStatus lookupResponse(String code); MStatus lookupStatus(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<String, MStatus> getStatusMap(); void setStatusMap(Map<String, MStatus> statusMap); Map<String, MStatus> getResponseMap(); void setResponseMap(Map<String, MStatus> responseMap); }### Answer: @Test public void testParseMessageResponse() { MessageRequest mr1 = new MessageRequestImpl(); mr1.setId(31000000001l); mr1.setRecipientId("123456789"); mr1.setRequestId("mr1"); GatewayRequest r1 = new GatewayRequestImpl(); r1.setId(31000000002l); r1.setMessageRequest(mr1); r1.setRequestId(mr1.getRequestId()); r1.setMessageStatus(MStatus.PENDING); r1.setRecipientsNumber("15555555555"); for ( String code : statusCodes.keySet()) { Set<GatewayResponse> responses = intellIVRMessageHandler.parseMessageResponse(r1, code); for ( GatewayResponse response : responses ) { assertTrue(response.getDateCreated()!= null); assertEquals(r1, response.getGatewayRequest()); assertEquals(mr1.getId().toString(), response.getGatewayMessageId()); assertEquals(statusCodes.get(code), response.getMessageStatus()); assertEquals("15555555555", response.getRecipientNumber()); assertEquals("mr1", response.getRequestId()); assertEquals(code, response.getResponseText()); } } }
### Question: OMPManagerImpl implements OMPManager, ApplicationContextAware { public GatewayMessageHandler createGatewayMessageHandler() { try{ return (GatewayMessageHandler)context.getBean("orserveHandler"); } catch(Exception ex){ logger.error("GatewayMessageHandler creation failed", ex); return null; } } void setApplicationContext(ApplicationContext applicationContext); GatewayMessageHandler createGatewayMessageHandler(); GatewayManager createGatewayManager(); CacheService createCacheService(); MobileMessagingService createMessagingService(); }### Answer: @Test public void testCreateGatewayMessageHandler() { System.out.println("createGatewayMessageHandler"); GatewayMessageHandler result = ompManager.createGatewayMessageHandler(); assertNotNull(result); }
### Question: OMPManagerImpl implements OMPManager, ApplicationContextAware { public GatewayManager createGatewayManager() { try{ return (GatewayManager)context.getBean("orserveGateway"); } catch(Exception ex){ logger.fatal("GatewayManager creation failed", ex); throw new RuntimeException("Unable to create gateway"); } } void setApplicationContext(ApplicationContext applicationContext); GatewayMessageHandler createGatewayMessageHandler(); GatewayManager createGatewayManager(); CacheService createCacheService(); MobileMessagingService createMessagingService(); }### Answer: @Test public void testCreateGatewayManager() { System.out.println("createGatewayManager"); GatewayManager result = ompManager.createGatewayManager(); assertNotNull(result); }
### Question: FormDefinitionServiceImpl implements FormDefinitionService, StudyDefinitionService, UserDefinitionService { public void init() throws Exception { for (String resource : getOxdFormDefResources()) { int index = resource.lastIndexOf("/"); String studyName = resource.substring(index + 1); List<File> fileList = getFileList(resource); if (fileList == null || fileList.isEmpty()) throw new FileNotFoundException(" No files in the directory " + resource); List<Integer> formIdList = new ArrayList<Integer>(); for (File fileName : fileList) { String formDefinition = getFileContent(fileName.getAbsolutePath()); Integer extractedFormId = extractFormId(formDefinition); formMap.put(extractedFormId, formDefinition); formIdList.add(extractedFormId); } studyForms.put(studyName, formIdList); studies.add(studyName); } } FormDefinitionServiceImpl(); void init(); List<File> getFileList(String directorySource); Map<Integer, String> getXForms(); Set<String> getOxdFormDefResources(); void setOxdFormDefResources(Set<String> oxdFormDefResources); void addOxdFormDefResources(String oxdFormDefResource); List<Object[]> getStudies(); void setPasswordEncoder(PasswordEncoder encoder); List<Object[]> getUsers(); void setUsers(List<String[]> users); String getStudyName(int id); List<String> getStudyForms(int studyId); }### Answer: @Test public void testInit() throws Exception { String resource = "MoTechDataEntry"; FormDefinitionServiceImpl fds = new FormDefinitionServiceImpl(); Set resources = new HashSet(); resources.add(resource); fds.setOxdFormDefResources(resources); fds.init(); Assert.assertEquals(1, fds.getStudies().size()); Assert.assertEquals(9, fds.getStudyForms(0).size()); }
### Question: OMPManagerImpl implements OMPManager, ApplicationContextAware { public CacheService createCacheService() { try{ return (CacheService)context.getBean("smsCache"); } catch(Exception ex){ logger.fatal("CacheService creation failed", ex); throw new RuntimeException("Unable to initialize cache"); } } void setApplicationContext(ApplicationContext applicationContext); GatewayMessageHandler createGatewayMessageHandler(); GatewayManager createGatewayManager(); CacheService createCacheService(); MobileMessagingService createMessagingService(); }### Answer: @Test public void testCreateCacheService() { System.out.println("createCacheService"); CacheService result = ompManager.createCacheService(); assertNotNull(result); }
### Question: OMPManagerImpl implements OMPManager, ApplicationContextAware { public MobileMessagingService createMessagingService() { try{ return (MobileMessagingService)context.getBean("smsService"); } catch(Exception ex){ logger.fatal("MobileMessagingService creation failed", ex); throw new RuntimeException("Unable to initialize messaging service"); } } void setApplicationContext(ApplicationContext applicationContext); GatewayMessageHandler createGatewayMessageHandler(); GatewayManager createGatewayManager(); CacheService createCacheService(); MobileMessagingService createMessagingService(); }### Answer: @Test public void testCreateMessagingService() { System.out.println("createMessagingService"); MobileMessagingService result = ompManager.createMessagingService(); assertNotNull(result); }
### Question: CompositeGatewayMessageHandler implements GatewayMessageHandler { @SuppressWarnings("unchecked") public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse) { if ( message .getMessageRequest() .getMessageType() == MessageType.VOICE) return voiceHandler.parseMessageResponse(message, gatewayResponse); if ( message .getMessageRequest() .getMessageType() == MessageType.TEXT) return textHandler.parseMessageResponse(message, gatewayResponse); return null; } MStatus lookupResponse(String code); MStatus lookupStatus(String code); @SuppressWarnings("unchecked") Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String messageStatus); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); GatewayMessageHandler getVoiceHandler(); void setVoiceHandler(GatewayMessageHandler voiceHandler); GatewayMessageHandler getTextHandler(); void setTextHandler(GatewayMessageHandler textHandler); }### Answer: @SuppressWarnings("unchecked") @Test public void testParseMessageResponse(){ Set<GatewayResponse> response = new HashSet<GatewayResponse>(); expect(voiceHandler.parseMessageResponse(voiceGatewayRequest, "OK")).andReturn(response); replay(voiceHandler); compositeHandler.parseMessageResponse(voiceGatewayRequest, "OK"); verify(voiceHandler); reset(voiceHandler); expect(textHandler.parseMessageResponse(textGatewayRequest, "OK")).andReturn(response); replay(textHandler); compositeHandler.parseMessageResponse(textGatewayRequest, "OK"); verify(textHandler); reset(textHandler); }
### Question: DummyGatewayManagerImpl implements GatewayManager { public Set<GatewayResponse> sendMessage(GatewayRequest messageDetails) { if (log.isInfoEnabled()) { log.info(messageDetails.getId() + "|" + messageDetails.getRecipientsNumber() + "|" + messageDetails.getMessage()); } String msgResponse = (messageDetails.getRecipientsNumber().length() < 8) ? "failed" : "ID: " + MotechIDGenerator.generateID(10); if (sleepTime > 0) { try { log.debug("going to sleep to simulate latency"); Thread.sleep(sleepTime); log.debug("finished simulated latency"); } catch (InterruptedException ie) { log.debug("interrupted while sleeping"); } } if(isThrowRandomExceptions() && getExceptionPoints().contains(new Integer((int)(Math.random() * exceptionPointRange)))){ log.error("Throwing Exception to mimic possible fault behaviour"); throw new RuntimeException("Arbitrary exception thrown to mimic fault behaviour"); } return messageHandler.parseMessageResponse(messageDetails, msgResponse); } Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); void setSleepTime(long sleepTime); long getSleepTime(); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); boolean isThrowRandomExceptions(); void setThrowRandomExceptions(boolean throwRandomExceptions); ArrayList<Integer> getExceptionPoints(); void setExceptionPoints(ArrayList<Integer> exceptionPoints); int getExceptionPointRange(); void setExceptionPointRange(int exceptionPointRange); }### Answer: @Test public void testSendMessage() { System.out.println("sendMessage"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); expect( mockHandler.parseMessageResponse((GatewayRequest) anyObject(), (String) anyObject()) ).andReturn(new HashSet<GatewayResponse>()); replay(mockHandler); Set<GatewayResponse> result = instance.sendMessage(messageDetails); assertNotNull(result); verify(mockHandler); }
### Question: DummyGatewayManagerImpl implements GatewayManager { public String getMessageStatus(GatewayResponse response) { return "004"; } Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); void setSleepTime(long sleepTime); long getSleepTime(); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); boolean isThrowRandomExceptions(); void setThrowRandomExceptions(boolean throwRandomExceptions); ArrayList<Integer> getExceptionPoints(); void setExceptionPoints(ArrayList<Integer> exceptionPoints); int getExceptionPointRange(); void setExceptionPointRange(int exceptionPointRange); }### Answer: @Test public void testGetMessageStatus() { System.out.println("getMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setGatewayMessageId("testId"); String result = instance.getMessageStatus(response); assertNotNull(result); }
### Question: DummyGatewayManagerImpl implements GatewayManager { public MStatus mapMessageStatus(GatewayResponse response) { return messageHandler.parseMessageStatus(response.getResponseText()); } Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); void setSleepTime(long sleepTime); long getSleepTime(); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); boolean isThrowRandomExceptions(); void setThrowRandomExceptions(boolean throwRandomExceptions); ArrayList<Integer> getExceptionPoints(); void setExceptionPoints(ArrayList<Integer> exceptionPoints); int getExceptionPointRange(); void setExceptionPointRange(int exceptionPointRange); }### Answer: @Test public void testMapMessageStatus() { System.out.println("mapMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setResponseText("Some gateway response message"); expect( mockHandler.parseMessageStatus((String) anyObject()) ).andReturn(MStatus.DELIVERED); replay(mockHandler); MStatus result = instance.mapMessageStatus(response); assertEquals(result, MStatus.DELIVERED); verify(mockHandler); }
### Question: PostData { public String toString(){ StringBuilder builder = new StringBuilder(); for(String key : data.keySet()){ builder.append("&").append(key).append("=").append(data.get(key)); } return builder.toString(); } void add(String attribute, String value, String urlEncoding); void add(String attribute, String value); String toString(); String without(String... values); }### Answer: @Test public void shouldReturnStringRepresentation() throws UnsupportedEncodingException { PostData data = postData(); assertEquals("&user=john&password=password&sender=1982&text=hello+world",data.toString()); }
### Question: PostData { public String without(String... values){ List<String> ignoreList = Arrays.asList(values); StringBuilder builder = new StringBuilder(); for(String key : data.keySet()){ if(! ignoreList.contains(key)){ builder.append("&").append(key).append("=").append(data.get(key)); } } return builder.toString(); } void add(String attribute, String value, String urlEncoding); void add(String attribute, String value); String toString(); String without(String... values); }### Answer: @Test public void shouldNotIncludeRestrictedValuesInStringRepresentation() throws UnsupportedEncodingException { PostData data = postData(); assertEquals("&sender=1982&text=hello+world",data.without("password","user")); }
### Question: InMemoryMessageStatusStore implements MessageStatusStore { public void updateStatus(String id, String status) { try { if (status == null) { statusMap.remove(id); return; } MessageStatusEntry statusEntry = statusMap.get(id); if (statusEntry == null) statusMap.put(id, statusEntry = new MessageStatusEntry()); statusEntry.setStatus(status); statusEntry.setLastUpdate(System.currentTimeMillis()); } finally { requestCleanup(); } } void setTtl(long ttl); long getTtl(); long getCleanupInterval(); void setCleanupInterval(long cleanupInterval); Map<String, MessageStatusEntry> getStatusMap(); void setStatusMap(Map<String, MessageStatusEntry> statusMap); void updateStatus(String id, String status); String getStatus(String id); }### Answer: @Test public void testUpdateStatusNull() { store.updateStatus(id, newStatus); store.updateStatus(id, null); assertFalse("Should not contain entry " + id, store.statusMap .containsKey(id)); }
### Question: InMemoryMessageStatusStore implements MessageStatusStore { public String getStatus(String id) { try { MessageStatusEntry statusEntry = statusMap.get(id); return statusEntry == null ? null : statusEntry.getStatus(); } finally { requestCleanup(); } } void setTtl(long ttl); long getTtl(); long getCleanupInterval(); void setCleanupInterval(long cleanupInterval); Map<String, MessageStatusEntry> getStatusMap(); void setStatusMap(Map<String, MessageStatusEntry> statusMap); void updateStatus(String id, String status); String getStatus(String id); }### Answer: @Test public void testGetStatus() { store.updateStatus(id, newStatus); assertTrue("Map should contain key " + id, store.statusMap .containsKey(id)); assertEquals(newStatus, store.statusMap.get(id).getStatus()); }
### Question: CompositeGatewayManager implements GatewayManager { public String getMessageStatus(GatewayResponse response) { if ( response .getGatewayRequest() .getMessageRequest() .getMessageType() == MessageType.VOICE ) { return voiceGatewayManager.getMessageStatus(response); } if ( response .getGatewayRequest() .getMessageRequest() .getMessageType() == MessageType.TEXT ) { return textGatewayManager.getMessageStatus(response); } return null; } String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); @Transactional @SuppressWarnings("unchecked") Set<GatewayResponse> sendMessage(GatewayRequest gatewayRequest); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); CompositeGatewayMessageHandler getCompositeMessageHandler(); void setCompositeMessageHandler( CompositeGatewayMessageHandler compositeMessageHandler); GatewayManager getVoiceGatewayManager(); void setVoiceGatewayManager(GatewayManager voiceGatewayManager); GatewayManager getTextGatewayManager(); void setTextGatewayManager(GatewayManager textGatewayManager); }### Answer: @Test public void testGetMessageStatus(){ expect(voiceManager.getMessageStatus(voiceGatewayResponse)).andReturn("OK"); replay(voiceManager); compositeGateway.getMessageStatus(voiceGatewayResponse); verify(voiceManager); reset(voiceManager); expect(textManager.getMessageStatus(textGatewayResponse)).andReturn("OK"); replay(textManager); compositeGateway.getMessageStatus(textGatewayResponse); verify(textManager); reset(textManager); }
### Question: CompositeGatewayManager implements GatewayManager { public MStatus mapMessageStatus(GatewayResponse response) { if ( response .getGatewayRequest() .getMessageRequest() .getMessageType() == MessageType.VOICE ) { return voiceGatewayManager.mapMessageStatus(response); } if ( response .getGatewayRequest() .getMessageRequest() .getMessageType() == MessageType.TEXT ) { return textGatewayManager.mapMessageStatus(response); } return null; } String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); @Transactional @SuppressWarnings("unchecked") Set<GatewayResponse> sendMessage(GatewayRequest gatewayRequest); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); CompositeGatewayMessageHandler getCompositeMessageHandler(); void setCompositeMessageHandler( CompositeGatewayMessageHandler compositeMessageHandler); GatewayManager getVoiceGatewayManager(); void setVoiceGatewayManager(GatewayManager voiceGatewayManager); GatewayManager getTextGatewayManager(); void setTextGatewayManager(GatewayManager textGatewayManager); }### Answer: @Test public void testMapMessageStatus(){ expect(voiceManager.mapMessageStatus(voiceGatewayResponse)).andReturn(MStatus.PENDING); replay(voiceManager); compositeGateway.mapMessageStatus(voiceGatewayResponse); verify(voiceManager); reset(voiceManager); expect(textManager.mapMessageStatus(textGatewayResponse)).andReturn(MStatus.PENDING); replay(textManager); compositeGateway.mapMessageStatus(textGatewayResponse); verify(textManager); reset(textManager); }
### Question: CompositeGatewayManager implements GatewayManager { @Transactional @SuppressWarnings("unchecked") public Set<GatewayResponse> sendMessage(GatewayRequest gatewayRequest) { if ( gatewayRequest .getMessageRequest() .getMessageType() == MessageType.VOICE ) { return voiceGatewayManager.sendMessage(gatewayRequest); } if ( gatewayRequest .getMessageRequest() .getMessageType() == MessageType.TEXT ) { return textGatewayManager.sendMessage(gatewayRequest); } return new HashSet<GatewayResponse>(); } String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); @Transactional @SuppressWarnings("unchecked") Set<GatewayResponse> sendMessage(GatewayRequest gatewayRequest); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); CompositeGatewayMessageHandler getCompositeMessageHandler(); void setCompositeMessageHandler( CompositeGatewayMessageHandler compositeMessageHandler); GatewayManager getVoiceGatewayManager(); void setVoiceGatewayManager(GatewayManager voiceGatewayManager); GatewayManager getTextGatewayManager(); void setTextGatewayManager(GatewayManager textGatewayManager); }### Answer: @SuppressWarnings("unchecked") @Test public void testSendMessage() { Set<GatewayResponse> voiceResponseSet = new HashSet<GatewayResponse>(); voiceResponseSet.add(voiceGatewayResponse); expect(voiceManager.sendMessage(voiceGatewayRequest)).andReturn(voiceResponseSet); replay(voiceManager); compositeGateway.sendMessage(voiceGatewayRequest); verify(voiceManager); Set<GatewayResponse> textResponseSet = new HashSet<GatewayResponse>(); textResponseSet.add(textGatewayResponse); expect(textManager.sendMessage(textGatewayRequest)).andReturn(textResponseSet); replay(textManager); compositeGateway.sendMessage(textGatewayRequest); verify(textManager); }
### Question: ORServeGatewayManagerImpl implements GatewayManager { public Set<GatewayResponse> sendMessage(GatewayRequest messageDetails) { String gatewayResponse; if(messageDetails == null) return null; logger.debug("Building ORServe message gateway webservice proxy class"); URL wsdlURL = null; try { wsdlURL = new URL("http: } catch ( MalformedURLException e ) { logger.error("Error creating web service client", e); throw new MotechException(e.getMessage()); } logger.debug("Calling sendMessage method of ORServe message gateway"); logger.debug(messageDetails); try{ SMSMessenger messenger = new SMSMessenger(wsdlURL, new QName("http: SMSMessengerSoap soap = messenger.getSMSMessengerSoap(); gatewayResponse = soap.sendMessage(messageDetails.getMessage(), messageDetails.getRecipientsNumber(), getSenderId(), getProductCode(), String.valueOf(messageDetails.getGatewayRequestDetails().getNumberOfPages())); } catch(Exception ex){ logger.error("Error sending message", ex); throw new MotechException(ex.getMessage()); } messageDetails.setDateSent(new Date()); logger.debug("Parsing gateway response"); return messageHandler.parseMessageResponse(messageDetails, gatewayResponse); } Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); String getProductCode(); void setProductCode(String productCode); String getSenderId(); void setSenderId(String senderId); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); }### Answer: @Ignore @Test public void testSendMessage() { System.out.println("sendMessage"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); expect( mockHandler.parseMessageResponse((GatewayRequest) anyObject(), (String) anyObject()) ).andReturn(new HashSet<GatewayResponse>()); replay(mockHandler); Set<GatewayResponse> result = instance.sendMessage(messageDetails); assertNotNull(result); verify(mockHandler); }
### Question: ORServeGatewayManagerImpl implements GatewayManager { public String getMessageStatus(GatewayResponse response) { String gatewayResponse; logger.debug("Building ORServe message gateway webservice proxy class"); URL wsdlURL = null; try { wsdlURL = new URL("http: } catch ( MalformedURLException e ) { logger.error("Error creating web service client", e); gatewayResponse = e.getMessage(); } SMSMessenger messenger = new SMSMessenger(wsdlURL, new QName("http: SMSMessengerSoap soap = messenger.getSMSMessengerSoap(); logger.debug("Calling getMessageStatus method of ORServe message gateway"); try{ gatewayResponse = soap.getMessageStatus(response.getGatewayMessageId(), productCode); } catch(Exception ex){ logger.error("Error querying message", ex); gatewayResponse = ex.getMessage(); } return gatewayResponse; } Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); String getProductCode(); void setProductCode(String productCode); String getSenderId(); void setSenderId(String senderId); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); }### Answer: @Ignore @Test public void testGetMessageStatus() { System.out.println("getMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setGatewayMessageId("testId"); String result = instance.getMessageStatus(response); System.out.println("Gateway Response: " + result); assertNotNull(result); }
### Question: ORServeGatewayManagerImpl implements GatewayManager { public MStatus mapMessageStatus(GatewayResponse response) { return messageHandler.parseMessageStatus(response.getResponseText()); } Set<GatewayResponse> sendMessage(GatewayRequest messageDetails); String getMessageStatus(GatewayResponse response); MStatus mapMessageStatus(GatewayResponse response); String getProductCode(); void setProductCode(String productCode); String getSenderId(); void setSenderId(String senderId); GatewayMessageHandler getMessageHandler(); void setMessageHandler(GatewayMessageHandler messageHandler); }### Answer: @Ignore @Test public void testMapMessageStatus() { System.out.println("mapMessageStatus"); GatewayResponseImpl response = new GatewayResponseImpl(); response.setResponseText("Some gateway response message"); expect( mockHandler.parseMessageStatus((String) anyObject()) ).andReturn(MStatus.DELIVERED); replay(mockHandler); MStatus result = instance.mapMessageStatus(response); assertEquals(result, MStatus.DELIVERED); verify(mockHandler); }
### Question: ORServeGatewayMessageHandlerImpl implements GatewayMessageHandler { public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse) { logger.debug("Parsing message gateway response"); logger.debug(gatewayResponse); if(message == null) return null; if(gatewayResponse.isEmpty()) return null; Set<GatewayResponse> responses = new HashSet<GatewayResponse>(); if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){ gatewayResponse = gatewayResponse.trim().replace("\n", ""); } String[] responseLines = gatewayResponse.split("\n"); for(String line : responseLines){ String[] responseParts = line.split(" "); if(responseParts[0].equalsIgnoreCase("ID:")){ GatewayResponse response = getCoreManager().createGatewayResponse(); response.setGatewayMessageId(responseParts[1]); response.setRequestId(message.getRequestId()); response.setMessageStatus(MStatus.PENDING); response.setGatewayRequest(message); response.setResponseText(gatewayResponse); response.setDateCreated(new Date()); if(responseParts.length == 4) response.setRecipientNumber(responseParts[3]); else response.setRecipientNumber(message.getRecipientsNumber()); responses.add(response); } else{ logger.error("Gateway returned error: " + gatewayResponse); String errorCode = responseParts[1]; errorCode.replaceAll(",", ""); errorCode.trim(); MStatus status = lookupResponse(errorCode); GatewayResponse response = getCoreManager().createGatewayResponse(); response.setRequestId(message.getRequestId()); response.setMessageStatus(status); response.setGatewayRequest(message); response.setResponseText(gatewayResponse); response.setDateCreated(new Date()); responses.add(response); } } logger.debug(responses); return responses; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testParseMessageResponse() { System.out.println("parseMessageResponse"); GatewayRequest message = null; String gatewayResponse = ""; GatewayRequest expResult = null; Set<GatewayResponse> result = messageHandler.parseMessageResponse(message, gatewayResponse); assertEquals(expResult, result); }
### Question: ORServeGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus parseMessageStatus(String gatewayResponse) { logger.debug("Parsing message gateway status response"); String status; String[] responseParts = gatewayResponse.split(" "); if(responseParts.length == 4){ status = responseParts[3]; } else{ status = ""; } return lookupStatus(status); } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testParseMessageStatus() { System.out.println("parseMessageStatus"); String messageStatus = " "; MStatus expResult = MStatus.PENDING; MStatus result = messageHandler.parseMessageStatus(messageStatus); assertEquals(expResult, result); }
### Question: ORServeGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus lookupStatus(String code){ if(code.isEmpty()){ return MStatus.PENDING; } for(Entry<MStatus, String> entry: codeStatusMap.entrySet()){ if(entry.getValue().contains(code)){ return entry.getKey(); } } return MStatus.PENDING; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testLookupStatus() { System.out.println("lookupStatus"); String messageStatus = " "; MStatus expResult = MStatus.PENDING; MStatus result = messageHandler.lookupStatus(messageStatus); assertEquals(expResult, result); messageStatus = "004"; expResult = MStatus.DELIVERED; result = messageHandler.lookupStatus(messageStatus); assertEquals(expResult, result); messageStatus = "007"; expResult = MStatus.FAILED; result = messageHandler.lookupStatus(messageStatus); assertEquals(expResult, result); messageStatus = "002"; expResult = MStatus.PENDING; result = messageHandler.lookupStatus(messageStatus); assertEquals(expResult, result); messageStatus = "006"; expResult = MStatus.CANCELLED; result = messageHandler.lookupStatus(messageStatus); assertEquals(expResult, result); messageStatus = "120"; expResult = MStatus.EXPIRED; result = messageHandler.lookupStatus(messageStatus); assertEquals(expResult, result); }
### Question: ORServeGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus lookupResponse(String code){ if(code.isEmpty()){ return MStatus.SCHEDULED; } for(Entry<MStatus, String> entry: codeResponseMap.entrySet()){ if(entry.getValue().contains(code)){ return entry.getKey(); } } return MStatus.SCHEDULED; } Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse); MStatus parseMessageStatus(String gatewayResponse); MStatus lookupStatus(String code); MStatus lookupResponse(String code); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); Map<MStatus, String> getCodeStatusMap(); void setCodeStatusMap(Map<MStatus, String> codeStatusMap); Map<MStatus, String> getCodeResponseMap(); void setCodeResponseMap(Map<MStatus, String> codeResponseMap); }### Answer: @Test public void testLookupResponse() { System.out.println("lookupResponse"); String messageStatus = " "; MStatus expResult = MStatus.SCHEDULED; MStatus result = messageHandler.lookupResponse(messageStatus); assertEquals(expResult, result); messageStatus = "103"; expResult = MStatus.RETRY; result = messageHandler.lookupResponse(messageStatus); assertEquals(expResult, result); messageStatus = "param:"; expResult = MStatus.FAILED; result = messageHandler.lookupResponse(messageStatus); assertEquals(expResult, result); messageStatus = "116"; expResult = MStatus.EXPIRED; result = messageHandler.lookupResponse(messageStatus); assertEquals(expResult, result); }
### Question: SMSCacheServiceImpl implements CacheService { public void saveMessage(GatewayRequest gatewayRequest) { logger.debug("Initializing DAO"); GatewayRequestDAO gatewayRequestDAO = coreManager.createGatewayRequestDAO(); logger.debug("Caching message"); logger.debug(gatewayRequest); gatewayRequestDAO.save(gatewayRequest); } void saveMessage(GatewayRequest gatewayRequest); void mergeMessage(GatewayRequest gatewayRequest); void mergeMessage(MessageRequest messageRequest); void saveMessage(GatewayRequestDetails gatewayRequestDetails); void saveResponse(GatewayResponse gatewayResponse); List<GatewayRequest> getMessages(GatewayRequest gatewayRequest); List<GatewayRequest> getMessagesByStatus(MStatus mStatus); List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date); List<GatewayResponse> getResponses(GatewayResponse gatewayResponse); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); }### Answer: @Test public void testSaveMessage() { System.out.println("saveMessage"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); messageDetails.setMessageStatus(MStatus.PENDING); mockMessageDAO = createMock(GatewayRequestDAO.class); expect( mockCore.createGatewayRequestDAO() ).andReturn(mockMessageDAO); expect( mockMessageDAO.save(messageDetails) ).andReturn(messageDetails); replay(mockCore, mockMessageDAO); instance.saveMessage(messageDetails); verify(mockCore, mockMessageDAO); }
### Question: SMSCacheServiceImpl implements CacheService { public void saveResponse(GatewayResponse gatewayResponse) { logger.debug("Initializing DAO"); GatewayResponseDAO gatewayResponseDAO = coreManager.createGatewayResponseDAO(); logger.debug("Caching response"); logger.debug(gatewayResponse); gatewayResponseDAO.merge(gatewayResponse); } void saveMessage(GatewayRequest gatewayRequest); void mergeMessage(GatewayRequest gatewayRequest); void mergeMessage(MessageRequest messageRequest); void saveMessage(GatewayRequestDetails gatewayRequestDetails); void saveResponse(GatewayResponse gatewayResponse); List<GatewayRequest> getMessages(GatewayRequest gatewayRequest); List<GatewayRequest> getMessagesByStatus(MStatus mStatus); List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date); List<GatewayResponse> getResponses(GatewayResponse gatewayResponse); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); }### Answer: @Test public void testSaveResponse() { System.out.println("saveResponse"); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.PENDING); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(32000000001l); mockResponseDAO = createMock(GatewayResponseDAO.class); expect( mockCore.createGatewayResponseDAO() ).andReturn(mockResponseDAO); expect( mockResponseDAO.merge((GatewayRequest) anyObject()) ).andReturn(response); replay(mockCore, mockResponseDAO); instance.saveResponse(response); verify(mockCore, mockResponseDAO); }
### Question: SMSCacheServiceImpl implements CacheService { public List<GatewayRequest> getMessages(GatewayRequest gatewayRequest) { GatewayRequestDAO gatewayRequestDAO = coreManager.createGatewayRequestDAO(); return gatewayRequestDAO.findByExample(gatewayRequest); } void saveMessage(GatewayRequest gatewayRequest); void mergeMessage(GatewayRequest gatewayRequest); void mergeMessage(MessageRequest messageRequest); void saveMessage(GatewayRequestDetails gatewayRequestDetails); void saveResponse(GatewayResponse gatewayResponse); List<GatewayRequest> getMessages(GatewayRequest gatewayRequest); List<GatewayRequest> getMessagesByStatus(MStatus mStatus); List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date); List<GatewayResponse> getResponses(GatewayResponse gatewayResponse); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); }### Answer: @Test public void testGetMessages() { System.out.println("getMessages"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); mockMessageDAO = createMock(GatewayRequestDAO.class); expect( mockCore.createGatewayRequestDAO() ).andReturn(mockMessageDAO); expect( mockMessageDAO.findByExample((GatewayRequest) anyObject()) ).andReturn(new ArrayList<GatewayRequest>()); replay(mockCore, mockMessageDAO); List<GatewayRequest> result = instance.getMessages(messageDetails); assertNotNull(result); verify(mockCore, mockMessageDAO); }
### Question: SMSCacheServiceImpl implements CacheService { public List<GatewayResponse> getResponses(GatewayResponse gatewayResponse) { GatewayResponseDAO responseDao = coreManager.createGatewayResponseDAO(); return responseDao.findByExample(gatewayResponse); } void saveMessage(GatewayRequest gatewayRequest); void mergeMessage(GatewayRequest gatewayRequest); void mergeMessage(MessageRequest messageRequest); void saveMessage(GatewayRequestDetails gatewayRequestDetails); void saveResponse(GatewayResponse gatewayResponse); List<GatewayRequest> getMessages(GatewayRequest gatewayRequest); List<GatewayRequest> getMessagesByStatus(MStatus mStatus); List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date); List<GatewayResponse> getResponses(GatewayResponse gatewayResponse); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); }### Answer: @Test public void testGetResponses() { System.out.println("getResponses"); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.PENDING); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); mockResponseDAO = createMock(GatewayResponseDAO.class); expect( mockCore.createGatewayResponseDAO() ).andReturn(mockResponseDAO); expect( mockResponseDAO.findByExample((GatewayResponse) anyObject()) ).andReturn(new ArrayList<GatewayResponse>()); replay(mockCore, mockResponseDAO); List<GatewayResponse> result = instance.getResponses(response); assertNotNull(result); verify(mockCore, mockResponseDAO); }
### Question: SMSCacheServiceImpl implements CacheService { public List<GatewayRequest> getMessagesByStatus(MStatus mStatus) { GatewayRequestDAO gatewayRequestDAO = coreManager.createGatewayRequestDAO(); return gatewayRequestDAO.getByStatus(mStatus); } void saveMessage(GatewayRequest gatewayRequest); void mergeMessage(GatewayRequest gatewayRequest); void mergeMessage(MessageRequest messageRequest); void saveMessage(GatewayRequestDetails gatewayRequestDetails); void saveResponse(GatewayResponse gatewayResponse); List<GatewayRequest> getMessages(GatewayRequest gatewayRequest); List<GatewayRequest> getMessagesByStatus(MStatus mStatus); List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date); List<GatewayResponse> getResponses(GatewayResponse gatewayResponse); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); }### Answer: @Test public void testGetMessagesByStatus() { System.out.println("getMessagesByStatus"); mockMessageDAO = createMock(GatewayRequestDAO.class); expect( mockCore.createGatewayRequestDAO() ).andReturn(mockMessageDAO); expect( mockMessageDAO.getByStatus((MStatus) anyObject()) ).andReturn(new ArrayList<GatewayRequest>()); replay(mockCore, mockMessageDAO); List<GatewayRequest> result = instance.getMessagesByStatus(MStatus.CANCELLED); assertNotNull(result); verify(mockCore, mockMessageDAO); }
### Question: SMSCacheServiceImpl implements CacheService { public List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date) { GatewayRequestDAO gatewayRequestDAO = coreManager.createGatewayRequestDAO(); return gatewayRequestDAO.getByStatusAndSchedule(mStatus, date); } void saveMessage(GatewayRequest gatewayRequest); void mergeMessage(GatewayRequest gatewayRequest); void mergeMessage(MessageRequest messageRequest); void saveMessage(GatewayRequestDetails gatewayRequestDetails); void saveResponse(GatewayResponse gatewayResponse); List<GatewayRequest> getMessages(GatewayRequest gatewayRequest); List<GatewayRequest> getMessagesByStatus(MStatus mStatus); List<GatewayRequest> getMessagesByStatusAndSchedule(MStatus mStatus, Date date); List<GatewayResponse> getResponses(GatewayResponse gatewayResponse); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); }### Answer: @Test public void testGetMessagesByStatusAndSchedule() { System.out.println("getMessagesByStatusAndSchedule"); mockMessageDAO = createMock(GatewayRequestDAO.class); expect( mockCore.createGatewayRequestDAO() ).andReturn(mockMessageDAO); expect( mockMessageDAO.getByStatusAndSchedule((MStatus) anyObject(), (Date) anyObject()) ).andReturn(new ArrayList<GatewayRequest>()); replay(mockCore, mockMessageDAO); List<GatewayRequest> result = instance.getMessagesByStatusAndSchedule(MStatus.CANCELLED, new Date()); assertNotNull(result); verify(mockCore, mockMessageDAO); }
### Question: SMSMessagingServiceImpl implements MobileMessagingService { @Transactional public void scheduleMessage(GatewayRequest gatewayRequest) { cache.saveMessage(gatewayRequest.getGatewayRequestDetails()); } @Transactional void scheduleMessage(GatewayRequest gatewayRequest); @Transactional void scheduleMessage(GatewayRequestDetails gatewayRequestDetails); @Transactional void scheduleTransactionalMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void sendScheduledMessages(); Map<Boolean, Set<GatewayResponse>> sendTransactionalMessage(GatewayRequest gatewayRequest); @Transactional Map<Boolean, Set<GatewayResponse>> sendMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void updateMessageStatuses(); CacheService getCache(); void setCache(CacheService cache); GatewayManager getGatewayManager(); void setGatewayManager(GatewayManager gatewayManager); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); SMSMessagingServiceWorker getWorker(); void setWorker(SMSMessagingServiceWorker worker); }### Answer: @Test public void testScheduleMessage() { System.out.println("scheduleMessage"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); mockCache.saveMessage((GatewayRequestDetails) anyObject()); expectLastCall(); replay(mockCache); instance.scheduleMessage(messageDetails); verify(mockCache); }
### Question: SMSMessagingServiceImpl implements MobileMessagingService { @Transactional(readOnly = true) public void sendScheduledMessages() { logger.info("Fetching cached GatewayRequests"); List<GatewayRequest> scheduledMessages = cache.getMessagesByStatusAndSchedule(MStatus.SCHEDULED, new Date()); if (scheduledMessages != null && scheduledMessages.size() > 0) { logger.info("Sending messages"); for (GatewayRequest message : scheduledMessages) { try { sendTransactionalMessage(message); } catch (Exception e) { logger.error("SMS message sending error: ", e); } } logger.info("Sending completed successfully"); } else { logger.info("No scheduled messages Found"); } } @Transactional void scheduleMessage(GatewayRequest gatewayRequest); @Transactional void scheduleMessage(GatewayRequestDetails gatewayRequestDetails); @Transactional void scheduleTransactionalMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void sendScheduledMessages(); Map<Boolean, Set<GatewayResponse>> sendTransactionalMessage(GatewayRequest gatewayRequest); @Transactional Map<Boolean, Set<GatewayResponse>> sendMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void updateMessageStatuses(); CacheService getCache(); void setCache(CacheService cache); GatewayManager getGatewayManager(); void setGatewayManager(GatewayManager gatewayManager); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); SMSMessagingServiceWorker getWorker(); void setWorker(SMSMessagingServiceWorker worker); }### Answer: @Test public void testSendScheduledMessages() { System.out.println("sendScheduledMessages"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); List<GatewayRequest> messages = new ArrayList<GatewayRequest>(); messages.add(messageDetails); expect( mockCache.getMessagesByStatusAndSchedule((MStatus) anyObject(), (Date) anyObject()) ).andReturn(messages); expect( mockWorker.sendMessage((GatewayRequest) anyObject()) ).andReturn(null); replay(mockCore, mockCache, mockWorker); instance.sendScheduledMessages(); verify(mockCore, mockCache, mockWorker); }
### Question: SMSMessagingServiceImpl implements MobileMessagingService { @Transactional public Map<Boolean, Set<GatewayResponse>> sendMessage(GatewayRequest gatewayRequest) { logger.debug("Sending message to gateway"); Set<GatewayResponse> responseList = null; Map<Boolean, Set<GatewayResponse>> result = new HashMap<Boolean, Set<GatewayResponse>>(); try { if ((gatewayRequest.getRecipientsNumber() == null || gatewayRequest.getRecipientsNumber().isEmpty()) && !ContactNumberType.PUBLIC.toString().equals(gatewayRequest.getMessageRequest().getPhoneNumberType())) { gatewayRequest.setMessageStatus(MStatus.INVALIDNUM); } else { responseList = this.getGatewayManager().sendMessage(gatewayRequest); result.put(true, responseList); logger.debug(responseList); logger.debug("Updating message status"); gatewayRequest.setResponseDetails(responseList); gatewayRequest.setMessageStatus(MStatus.SENT); } } catch (MotechException me) { logger.error("Error sending message", me); gatewayRequest.setMessageStatus(MStatus.SCHEDULED); GatewayMessageHandler orHandler = getGatewayManager().getMessageHandler(); responseList = orHandler.parseMessageResponse(gatewayRequest, "error: 901 - Cannot Connect to gateway | Details: " + me.getMessage()); result.put(false, responseList); } this.getCache().saveMessage(gatewayRequest); return result; } @Transactional void scheduleMessage(GatewayRequest gatewayRequest); @Transactional void scheduleMessage(GatewayRequestDetails gatewayRequestDetails); @Transactional void scheduleTransactionalMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void sendScheduledMessages(); Map<Boolean, Set<GatewayResponse>> sendTransactionalMessage(GatewayRequest gatewayRequest); @Transactional Map<Boolean, Set<GatewayResponse>> sendMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void updateMessageStatuses(); CacheService getCache(); void setCache(CacheService cache); GatewayManager getGatewayManager(); void setGatewayManager(GatewayManager gatewayManager); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); SMSMessagingServiceWorker getWorker(); void setWorker(SMSMessagingServiceWorker worker); }### Answer: @Test public void testSendMessage() { System.out.println("sendMessage"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); Map<Boolean, Set<GatewayResponse>> expResult = new HashMap<Boolean, Set<GatewayResponse>>(); expResult.put(true, new HashSet<GatewayResponse>()); expect( mockWorker.sendMessage((GatewayRequest) anyObject()) ).andReturn(expResult); replay(mockWorker); Map<Boolean, Set<GatewayResponse>> result = instance.sendTransactionalMessage(messageDetails); assertEquals(expResult.get(true), result.get(true)); verify(mockWorker); }
### Question: SMSMessagingServiceImpl implements MobileMessagingService { @Transactional(readOnly = true) public void updateMessageStatuses() { logger.info("Updating GatewayResponse objects"); GatewayResponse gwResp = coreManager.createGatewayResponse(); gwResp.setMessageStatus(MStatus.PENDING); List<GatewayResponse> pendingMessages = cache.getResponses(gwResp); for (GatewayResponse response : pendingMessages) { try { updateMessageStatus(response); } catch (Exception e) { logger.error("SMS message update error"); } } } @Transactional void scheduleMessage(GatewayRequest gatewayRequest); @Transactional void scheduleMessage(GatewayRequestDetails gatewayRequestDetails); @Transactional void scheduleTransactionalMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void sendScheduledMessages(); Map<Boolean, Set<GatewayResponse>> sendTransactionalMessage(GatewayRequest gatewayRequest); @Transactional Map<Boolean, Set<GatewayResponse>> sendMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void updateMessageStatuses(); CacheService getCache(); void setCache(CacheService cache); GatewayManager getGatewayManager(); void setGatewayManager(GatewayManager gatewayManager); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); SMSMessagingServiceWorker getWorker(); void setWorker(SMSMessagingServiceWorker worker); }### Answer: @Test public void testUpdateMessageStatuses() { System.out.println("updateMessageStatuses"); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.PENDING); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); List<GatewayResponse> responses = new ArrayList<GatewayResponse>(); responses.add(response); expect( mockCore.createGatewayResponse() ).andReturn(new GatewayResponseImpl()); expect( mockCache.getResponses((GatewayResponse) anyObject()) ).andReturn(responses); mockWorker.updateMessageStatus((GatewayResponse)anyObject()); expectLastCall(); replay(mockCore, mockCache, mockGateway, mockWorker); instance.updateMessageStatuses(); verify(mockCore, mockCache, mockGateway, mockWorker); }
### Question: SMSMessagingServiceImpl implements MobileMessagingService { String getMessageStatus(GatewayResponse response) { logger.info("Calling GatewayManager.getMessageStatus"); return gatewayManager.getMessageStatus(response); } @Transactional void scheduleMessage(GatewayRequest gatewayRequest); @Transactional void scheduleMessage(GatewayRequestDetails gatewayRequestDetails); @Transactional void scheduleTransactionalMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void sendScheduledMessages(); Map<Boolean, Set<GatewayResponse>> sendTransactionalMessage(GatewayRequest gatewayRequest); @Transactional Map<Boolean, Set<GatewayResponse>> sendMessage(GatewayRequest gatewayRequest); @Transactional(readOnly = true) void updateMessageStatuses(); CacheService getCache(); void setCache(CacheService cache); GatewayManager getGatewayManager(); void setGatewayManager(GatewayManager gatewayManager); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); SMSMessagingServiceWorker getWorker(); void setWorker(SMSMessagingServiceWorker worker); }### Answer: @Test public void testGetMessageStatus() { System.out.println("getMessageStatus"); String expResult = "delivered"; expect( mockGateway.getMessageStatus((GatewayResponse) anyObject()) ).andReturn("delivered"); replay(mockGateway); String result = instance.getMessageStatus(new GatewayResponseImpl()); assertEquals(expResult, result); verify(mockGateway); }
### Question: IMPServiceImpl implements IMPService { public String formatPhoneNumber( String requesterPhone) { if (requesterPhone == null || requesterPhone.isEmpty()) { return null; } String formattedNumber = requesterPhone; if (Pattern.matches(localNumberExpression, requesterPhone)) { formattedNumber = defaultCountryCode + requesterPhone.substring(1); } return formattedNumber; } @SuppressWarnings("unchecked") IncomingMessageResponse processRequest(String message, String requesterPhone, boolean isDemo); String processRequest(String message); ArrayList<String> processXForms(ArrayList<String> xForms); String processXForm(String xForm); String formatPhoneNumber( String requesterPhone); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); IncomingMessageParser getParser(); void setParser(IncomingMessageParser parser); Map<String, CommandAction> getCmdActionMap(); void setCmdActionMap(Map<String, CommandAction> cmdActionMap); IMPManager getImpManager(); void setImpManager(IMPManager impManager); IncomingMessageXMLParser getXmlParser(); void setXmlParser(IncomingMessageXMLParser xmlParser); String getFormProcessSuccess(); void setFormProcessSuccess(String formProcessSuccess); void setOmiManager(OMIManager omiManager); void setMaxConcat(int maxConcat); void setCharsPerSMS(int charsPerSMS); void setConcatAllowance(int concatAllowance); void setMaxSMS(int maxSMS); void setLocalNumberExpression(String localNumberExpression); void setDefaultCountryCode(String defaultCountryCode); void setMessageRegistry(MessageRegistry messageRegistry); }### Answer: @Test public void testFormatPhoneNumber(){ String number = "0244000000"; String expResult = "233244000000"; instance.setDefaultCountryCode("233"); instance.setLocalNumberExpression("0[0-9]{9}"); String result = instance.formatPhoneNumber(number); assertEquals(result, expResult); number = "1234567890"; result = instance.formatPhoneNumber(number); assertEquals(number, result); number = "01234567890"; result = instance.formatPhoneNumber(number); assertEquals(number, result); }
### Question: IncomingMessageFormParameterValidatorImpl implements IncomingMessageFormParameterValidator { public boolean validate(IncomingMessageFormParameter param) { if (!param.getMessageFormParamStatus().equals(IncMessageFormParameterStatus.NEW)) { return param.getMessageFormParamStatus().equals(IncMessageFormParameterStatus.VALID); } String paramRegex = getParamTypeMap().get(param.getIncomingMsgFormParamDefinition().getParamType()); if (param.getIncomingMsgFormParamDefinition().getParamType().toUpperCase().equals("DATE")) { try { new SimpleDateFormat(paramRegex).parse(param.getValue()); param.setMessageFormParamStatus(IncMessageFormParameterStatus.VALID); } catch (ParseException ex) { param.setErrCode(1); param.setErrText("wrong format"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); } } else if (!Pattern.matches(paramRegex, param.getValue().trim())) { param.setErrCode(1); param.setErrText("wrong format"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); } else if (param.getValue().trim().length() > param.getIncomingMsgFormParamDefinition().getLength()) { param.setErrCode(2); param.setErrText("too long"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); } else { if(param.getIncomingMsgFormParamDefinition().getParamType().toUpperCase().equals("BOOLEAN")) param.setValue(param.getValue().toLowerCase().equals("y") ? "true" : "false"); else if(param.getIncomingMsgFormParamDefinition().getParamType().toUpperCase().equals("GENDER")) param.setValue(param.getValue().toLowerCase().equals("m") ? "MALE" : "FEMALE"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.VALID); } param.setLastModified(new Date()); return param.getMessageFormParamStatus().equals(IncMessageFormParameterStatus.VALID); } boolean validate(IncomingMessageFormParameter param); Map<String, String> getParamTypeMap(); void setParamTypeMap(Map<String, String> paramTypeMap); }### Answer: @Ignore @Test public void testValidate() { System.out.println("validate"); }
### Question: MotechIDGenerator { public static Long generateID(int length) { logger.info("Calling generateID with specify length"); Long result = null; if (length > 0) { StringBuilder id = new StringBuilder(length); for (int i = 0; i < length; i++) { id.append(NUMS[(int) Math.floor(Math.random() * 20)]); } result = Long.parseLong(id.toString()); } return result; } static Long generateID(int length); static Long generateID(); static String generateUUID(); static final int DEFUALT_ID_LENGTH; }### Answer: @Test public void testGenerateID() { Long result = MotechIDGenerator.generateID(MotechIDGenerator.DEFUALT_ID_LENGTH); System.out.println("ID: " + result); assertNotNull(result); }
### Question: GatewayResponseDAOImpl extends HibernateGenericDAOImpl<GatewayResponseImpl> implements GatewayResponseDAO<GatewayResponseImpl> { public GatewayResponse getMostRecentResponseByMessageId(Long messageId) { logger.debug("variable passed to getMostRecentResponseByRequestId: " + messageId); try { GatewayResponse response = null; String query = "from GatewayResponseImpl g where g.gatewayRequest.messageRequest.id = :reqId and g.gatewayRequest.messageStatus != 'PENDING' and g.gatewayRequest.messageStatus != 'PROCESSING' "; List responses = this.getSessionFactory().getCurrentSession().createQuery(query).setParameter("reqId", messageId).list(); logger.debug(responses); return responses != null && responses.size() > 0 ? (GatewayResponse) responses.get(0) : null; } catch (HibernateException he) { logger.error("Persistence or JDBC Exception in getMostRecentResponseByRequestId", he); return null; } catch (Exception ex) { logger.error("Exception in getMostRecentResponseByRequestId", ex); return new GatewayResponseImpl(); } } GatewayResponseDAOImpl(); GatewayResponse getMostRecentResponseByMessageId(Long messageId); List getByPendingMessageAndMaxTries(int maxTries); }### Answer: @Test public void testGetMostRecentResponseByRequestId() { System.out.println("getMostRecentResponseByRequestId"); GatewayResponse result = rDDAO.getMostRecentResponseByMessageId(grq1.getMessageRequest().getId()); System.out.println(result.getId()); Assert.assertNotNull(result); Assert.assertEquals(gr7, result); Assert.assertEquals(gr7.getId(), result.getId()); System.out.println("===================================================================================================="); System.out.println(result.toString()); }
### Question: GatewayRequestDAOImpl extends HibernateGenericDAOImpl<GatewayRequestImpl> implements GatewayRequestDAO<GatewayRequestImpl> { public List<GatewayRequest> getByStatusAndSchedule(MStatus status, Date schedule) { logger.debug("variables passed to getByStatusAndSchedule. status: " + status + "And schedule: " + schedule); try { List<GatewayRequest> allbystatandSdule; Criteria criteria = this.getSessionFactory().getCurrentSession().createCriteria(getPersistentClass()); if (schedule == null) { criteria = criteria.add(Restrictions.isNull("dateTo")).add(Restrictions.isNull("dateFrom")).add(Restrictions.eq("messageStatus", status)); } else { criteria = criteria.add(Restrictions.eq("messageStatus", status)).add(Restrictions.or(Restrictions.isNull("dateFrom"),Restrictions.lt("dateFrom", schedule))).add(Restrictions.or(Restrictions.isNull("dateTo"),Restrictions.gt("dateTo", schedule))); } allbystatandSdule = (List<GatewayRequest>) criteria.add(Restrictions.isNotNull("gatewayRequestDetails")).list(); logger.debug(allbystatandSdule); return allbystatandSdule; } catch (HibernateException he) { logger.error("Persistence or JDBC Exception in Method getByStatusAndSchedule", he); return null; } catch (Exception ex) { logger.error("Exception in Method getByStatusAndSchedule", ex); return null; } } GatewayRequestDAOImpl(); List<GatewayRequest> getByStatus(MStatus status); List<GatewayRequest> getByStatusAndSchedule(MStatus status, Date schedule); }### Answer: @Ignore @Test public void testGetByStatusAndSchedule() { System.out.println("getByStatusAndSchedule"); List<GatewayRequest> expResult = new ArrayList<GatewayRequest>(); md4.setGatewayRequestDetails(grd4); md5.setGatewayRequestDetails(grd5); expResult.add(md4); expResult.add(md5); MStatus status = MStatus.FAILED; List result = mDDAO.getByStatusAndSchedule(status, schedule); Assert.assertFalse(result.isEmpty()); Assert.assertEquals(expResult.size(), result.size()); Assert.assertEquals(true, result.contains(md4)); Assert.assertEquals(true, result.contains(md5)); }
### Question: LanguageDAOImpl extends HibernateGenericDAOImpl<LanguageImpl> implements LanguageDAO<LanguageImpl> { public Language getByCode(String code) { logger.debug("variable passed to getByCode: " + code); try { Language lang = (Language) this.getSessionFactory().getCurrentSession().createCriteria(LanguageImpl.class).add(Restrictions.eq("code", code)).uniqueResult(); logger.debug(lang); return lang; } catch (NonUniqueResultException ne) { logger.error("getByCode returned more than one object", ne); return null; } catch (HibernateException he) { logger.error("Persistence or jdbc Exception in Method getByCode", he); return null; } catch (Exception e) { logger.error("Exception in getByCode", e); return null; } } LanguageDAOImpl(); Language getByCode(String code); }### Answer: @Test public void testGeByCode() { System.out.print("test getIdByCode"); Language expResult = l2; Language Result = lDao.getByCode(code); Assert.assertNotNull(Result); Assert.assertEquals(expResult, Result); } @Test public void testGetByUnexistantCode() { System.out.print("test Language getByCode with unexistant code"); String code = "dd"; Language result = lDao.getByCode(code); Assert.assertNull(result); }
### Question: FormProcessorImpl implements FormProcessor { public void parseValidationErrors(IncomingMessageForm form, ValidationException ex) { List<String> errors = ex.getFaultInfo().getErrors(); form.setErrors(errors); } String processForm(IncomingMessageForm form); void parseValidationErrors(IncomingMessageForm form, ValidationException ex); void setDefaultDateFormat(String defaultDateFormat); void setRegWS(RegistrarService regWS); void setOmiManager(OMIManager omiManager); void setCoreManager(CoreManager coreManager); void setServerErrors(Map<Integer, String> serverErrors); Map<String, MethodSignature> getServiceMethods(); void setServiceMethods(Map<String, MethodSignature> serviceMethods); }### Answer: @Test public void testParseValidationErrors() { }
### Question: ParamRangeValidator implements IncomingMessageFormParameterValidator { public boolean validate(IncomingMessageFormParameter param) { Float value; if(param.getValue().isEmpty()) return true; try { value = Float.parseFloat(param.getValue()); } catch (NumberFormatException ex) { param.setErrCode(1); param.setErrText("wrong format"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); return false; } if (minValue != null && value < minValue){ param.setErrCode(3); param.setErrText("too small"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); } else if (maxValue != null && value > maxValue){ param.setErrCode(3); param.setErrText("too large"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); } else { param.setMessageFormParamStatus(IncMessageFormParameterStatus.VALID); } param.setLastModified(new Date()); return param.getMessageFormParamStatus().equals(IncMessageFormParameterStatus.VALID); } boolean validate(IncomingMessageFormParameter param); void setMinValue(Float minValue); void setMaxValue(Float maxValue); }### Answer: @Test public void testValidate() { System.out.println("validate"); IncomingMessageFormParameter param = new IncomingMessageFormParameterImpl(); param.setValue("10"); ParamRangeValidator instance = new ParamRangeValidator(); instance.setMaxValue(5f); instance.setMinValue(0f); boolean expResult = false; boolean result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.INVALID); assertEquals(param.getErrCode(), 3); assertEquals(param.getErrText(), "too large"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.NEW); instance.setMaxValue(20f); expResult = true; result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.VALID); }
### Question: ConditionalRequirementValidator { public boolean validate(IncomingMessageForm form, List<SubField> subFields, CoreManager coreManager) { boolean valid = true; for(SubField sf : subFields) { if(!form.getIncomingMsgFormParameters().containsKey(sf.getParentField().toLowerCase())) continue; IncomingMessageFormParameter parent = form.getIncomingMsgFormParameters().get(sf.getParentField().toLowerCase()); if (sf.getReplaceOn().equals("*") || parent.getValue().equalsIgnoreCase(sf.getReplaceOn())) { if (!form.getIncomingMsgFormParameters().containsKey(sf.getFieldName().toLowerCase())) { valid = false; IncomingMessageFormParameter param = coreManager.createIncomingMessageFormParameter(); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); param.setName(sf.getFieldName().toLowerCase()); param.setErrText("missing"); param.setValue(""); param.setErrCode(0); form.getIncomingMsgFormParameters().put(sf.getFieldName().toLowerCase(), param); form.setMessageFormStatus(IncMessageFormStatus.INVALID); form.setLastModified(new Date()); } } } return valid; } boolean validate(IncomingMessageForm form, List<SubField> subFields, CoreManager coreManager); }### Answer: @Test public void testValidate() { System.out.println("validate"); IncomingMessageFormParameter param1 = new IncomingMessageFormParameterImpl(); param1.setDateCreated(new Date()); param1.setName("parent"); param1.setValue("value"); IncomingMessageForm form = new IncomingMessageFormImpl(); form.setIncomingMsgFormParameters(new HashMap<String, IncomingMessageFormParameter>()); SubField sf = new SubField(); sf.setFieldName("subfield"); sf.setParentField("parent"); sf.setReplaceOn("require"); List<SubField> subFields = new ArrayList(); subFields.add(sf); boolean expResult = true; boolean result = instance.validate(form, subFields, mockCore); assertEquals(expResult, result); form.getIncomingMsgFormParameters().put(param1.getName(), param1); expResult = true; result = instance.validate(form, subFields, mockCore); assertEquals(expResult, result); param1.setValue("require"); expResult = false; expect( mockCore.createIncomingMessageFormParameter() ).andReturn(new IncomingMessageFormParameterImpl()); replay(mockCore); result = instance.validate(form, subFields, mockCore); verify(mockCore); assertEquals(result, expResult); assertEquals(form.getMessageFormStatus(), IncMessageFormStatus.INVALID); }
### Question: ParamValueValidator implements IncomingMessageFormParameterValidator { public boolean validate(IncomingMessageFormParameter param) { String value = caseSensitive ? param.getValue().trim() : param.getValue().trim().toUpperCase(); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); param.setValue(value); if (!values.isEmpty()){ String[] valArr = values.split(","); for(String val : valArr){ if(val.equals(param.getValue())){ param.setMessageFormParamStatus(IncMessageFormParameterStatus.VALID); break; } } } else param.setMessageFormParamStatus(IncMessageFormParameterStatus.VALID); if(param.getMessageFormParamStatus() == IncMessageFormParameterStatus.INVALID){ param.setErrCode(3); param.setErrText("out of range"); } else if (conversions != null && conversions.containsKey(value)) { param.setValue(conversions.get(value)); } param.setLastModified(new Date()); return param.getMessageFormParamStatus().equals(IncMessageFormParameterStatus.VALID); } boolean validate(IncomingMessageFormParameter param); void setValues(String values); void setConversions(Map<String, String> conversions); void setCaseSensitive(boolean caseSensitive); }### Answer: @Test public void testValidate() { System.out.println("validate"); IncomingMessageFormParameter param = new IncomingMessageFormParameterImpl(); param.setIncomingMsgFormParamDefinition(new IncomingMessageFormParameterDefinitionImpl()); param.getIncomingMsgFormParamDefinition().setParamType("BOOLEAN"); param.setValue("y"); ParamValueValidator instance = new ParamValueValidator(); instance.setCaseSensitive(true); instance.setValues("Y,N"); boolean expResult = false; boolean result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.INVALID); assertEquals(param.getErrCode(), 3); assertEquals(param.getErrText(), "out of range"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.NEW); instance.setCaseSensitive(false); expResult = true; result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.VALID); param.setMessageFormParamStatus(IncMessageFormParameterStatus.NEW); HashMap<String,String> conversions = new HashMap<String,String>(); conversions.put("Y", "true"); instance.setConversions(new HashMap<String,String>()); instance.setConversions(conversions); expResult = true; result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getValue(), "true"); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.VALID); }
### Question: ParamSizeValidator implements IncomingMessageFormParameterValidator { public boolean validate(IncomingMessageFormParameter param) { param.setMessageFormParamStatus(IncMessageFormParameterStatus.VALID); int paramLength = param.getValue().trim().length(); int maxLength = param.getIncomingMsgFormParamDefinition().getLength(); if (paramLength > maxLength) { param.setErrCode(2); param.setErrText("too long"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.INVALID); } param.setLastModified(new Date()); return param.getMessageFormParamStatus().equals(IncMessageFormParameterStatus.VALID); } boolean validate(IncomingMessageFormParameter param); }### Answer: @Test public void testValidate() { System.out.println("validate"); IncomingMessageFormParameter param = new IncomingMessageFormParameterImpl(); param.setValue("2010.12.10"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.NEW); param.setIncomingMsgFormParamDefinition(new IncomingMessageFormParameterDefinitionImpl()); param.getIncomingMsgFormParamDefinition().setLength(8); ParamSizeValidator instance = new ParamSizeValidator(); boolean expResult = false; boolean result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.INVALID); assertEquals(param.getErrCode(), 2); assertEquals(param.getErrText(), "too long"); param.setMessageFormParamStatus(IncMessageFormParameterStatus.NEW); param.getIncomingMsgFormParamDefinition().setLength(10); expResult = true; result = instance.validate(param); assertEquals(expResult, result); assertEquals(param.getMessageFormParamStatus(), IncMessageFormParameterStatus.VALID); }
### Question: FormCommandAction implements CommandAction, ApplicationContextAware { public IncomingMessageSession initializeSession(IncomingMessage message, String requesterPhone) { String formCode = parser.getFormCode(message.getContent()); IncomingMessageSession imSession = (IncomingMessageSession) applicationContext.getBean("incomingMessageSession", IncomingMessageSession.class); imSession.setFormCode(formCode); imSession.setRequesterPhone(requesterPhone); imSession.setMessageSessionStatus(IncMessageSessionStatus.STARTED); imSession.setDateStarted(new Date()); imSession.setLastActivity(new Date()); imSession.addIncomingMessage(message); IncomingMessageSessionDAO sessionDao = (IncomingMessageSessionDAO) applicationContext.getBean("incomingMessageSessionDAO", IncomingMessageSessionDAO.class); try { sessionDao.save(imSession); } catch (Exception ex) { logger.error("Error initializing incoming message session", ex); } return imSession; } IncomingMessageResponse execute(IncomingMessage message, String requesterPhone); IncomingMessageSession initializeSession(IncomingMessage message, String requesterPhone); IncomingMessageForm initializeForm(IncomingMessage message, String formCode); IncomingMessageResponse prepareResponse(IncomingMessage message, String wsResponse); IncomingMessageParser getParser(); void setParser(IncomingMessageParser parser); IncomingMessageFormValidator getFormValidator(); void setFormValidator(IncomingMessageFormValidator formValidator); void setFormProcessor(FormProcessor formProcessor); String getSenderFieldName(); void setSenderFieldName(String senderFieldName); void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test public void testInitializeSession() { System.out.println("initializeSession"); IncomingMessage message = new IncomingMessageImpl(); String requesterPhone = "000000000000"; mockSessDao = createMock(IncomingMessageSessionDAO.class); expect( applicationContext.getBean("incomingMessageSession", IncomingMessageSession.class) ).andReturn(new IncomingMessageSessionImpl()); expect( mockParser.getFormCode((String) anyObject()) ).andReturn("GENERAL"); expect( applicationContext.getBean("incomingMessageSessionDAO", IncomingMessageSessionDAO.class) ).andReturn(mockSessDao); expectLastCall(); expect( mockSessDao.save((IncomingMessageSession) anyObject()) ).andReturn(null); expectLastCall(); replay(applicationContext,mockParser,mockSessDao); IncomingMessageSession result = instance.initializeSession(message, requesterPhone); verify(applicationContext,mockParser,mockSessDao); assertNotNull(result); }
### Question: FormCommandAction implements CommandAction, ApplicationContextAware { public IncomingMessageForm initializeForm(IncomingMessage message, String formCode) { IncomingMessageFormDefinition formDefn = ((IncomingMessageFormDefinitionDAO)applicationContext.getBean("incomingMessageFormDefinitionDAO", IncomingMessageFormDefinitionDAO.class)).getByCode(formCode); if (formDefn == null) { return null; } IncomingMessageForm form = (IncomingMessageForm) applicationContext.getBean("incomingMessageForm", IncomingMessageForm.class); form.setIncomingMsgFormDefinition(formDefn); form.setMessageFormStatus(IncMessageFormStatus.NEW); form.setDateCreated(new Date()); form.setIncomingMsgFormParameters(new HashMap<String, IncomingMessageFormParameter>()); form.getIncomingMsgFormParameters().putAll(parser.getParams(message.getContent())); IncomingMessageFormDAO formDao = (IncomingMessageFormDAO) applicationContext.getBean("incomingMessageFormDAO", IncomingMessageFormDAO.class); try { formDao.save(form); } catch (Exception ex) { logger.error("Error initializing form", ex); } return form; } IncomingMessageResponse execute(IncomingMessage message, String requesterPhone); IncomingMessageSession initializeSession(IncomingMessage message, String requesterPhone); IncomingMessageForm initializeForm(IncomingMessage message, String formCode); IncomingMessageResponse prepareResponse(IncomingMessage message, String wsResponse); IncomingMessageParser getParser(); void setParser(IncomingMessageParser parser); IncomingMessageFormValidator getFormValidator(); void setFormValidator(IncomingMessageFormValidator formValidator); void setFormProcessor(FormProcessor formProcessor); String getSenderFieldName(); void setSenderFieldName(String senderFieldName); void setApplicationContext(ApplicationContext applicationContext); }### Answer: @Test public void testInitializeForm() { System.out.println("initializeForm"); IncomingMessage message = new IncomingMessageImpl(); message.setContent("test content"); String formCode = "GENERAL"; mockFormDefDao = createMock(IncomingMessageFormDefinitionDAO.class); mockFormDao = createMock(IncomingMessageFormDAO.class); expect( applicationContext.getBean("incomingMessageFormDefinitionDAO", IncomingMessageFormDefinitionDAO.class) ).andReturn(mockFormDefDao); expect( mockFormDefDao.getByCode((String) anyObject()) ).andReturn(new IncomingMessageFormDefinitionImpl()); expect( applicationContext.getBean("incomingMessageForm", IncomingMessageForm.class) ).andReturn(new IncomingMessageFormImpl()); expect( mockParser.getParams((String)anyObject()) ).andReturn(new HashMap<String,IncomingMessageFormParameter>()); expect( applicationContext.getBean("incomingMessageFormDAO", IncomingMessageFormDAO.class) ).andReturn(mockFormDao); expectLastCall(); expect( mockFormDao.save((IncomingMessageForm) anyObject()) ).andReturn(null); expectLastCall(); replay(applicationContext,mockFormDefDao,mockParser,mockFormDao); IncomingMessageForm result = instance.initializeForm(message, formCode); verify(applicationContext,mockFormDefDao,mockParser,mockFormDao); assertNotNull(result); }
### Question: IncomingMessageParserImpl implements IncomingMessageParser { public IncomingMessage parseRequest(String message) { IncomingMessage inMsg = coreManager.createIncomingMessage(); inMsg.setContent(message.trim()); inMsg.setDateCreated(new Date()); inMsg.setMessageStatus(IncMessageStatus.PROCESSING); return inMsg; } IncomingMessage parseRequest(String message); String getCommand(String message); String getFormCode(String message); Map<String, IncomingMessageFormParameter> getParams(String message); void setCoreManager(CoreManager coreManager); void setDelimiter(String delimiter); void setCmdRegex(String cmdRegex); void setTypeRegex(String typeRegex); void setParamRegex(String paramRegex); void setSeparator(String separator); }### Answer: @Test public void testParseRequest() { System.out.println("parseRequest"); String message = "Type=GENERAL\naction=test\nmessage=Test,, Tester"; expect( mockCore.createIncomingMessage() ).andReturn(new IncomingMessageImpl()); replay(mockCore); IncomingMessage result = imParser.parseRequest(message); verify(mockCore); assertNotNull(result); assertEquals(message, result.getContent()); }
### Question: IncomingMessageParserImpl implements IncomingMessageParser { public String getCommand(String message) { String command = ""; Pattern pattern = Pattern.compile(cmdRegex); Matcher matcher = pattern.matcher(message.trim()); if (matcher.find()) { command = matcher.group(); } return command.toLowerCase(); } IncomingMessage parseRequest(String message); String getCommand(String message); String getFormCode(String message); Map<String, IncomingMessageFormParameter> getParams(String message); void setCoreManager(CoreManager coreManager); void setDelimiter(String delimiter); void setCmdRegex(String cmdRegex); void setTypeRegex(String typeRegex); void setParamRegex(String paramRegex); void setSeparator(String separator); }### Answer: @Test public void testGetComand() { System.out.println("getComand"); String message = "Type=GENERAL\naction=test\nmessage=Test,, Tester"; String expResult = "type"; String result = imParser.getCommand(message); assertEquals(expResult, result); message = "someting=test Type"; expResult = ""; result = imParser.getCommand(message); assertEquals(expResult, result); }
### Question: IncomingMessageParserImpl implements IncomingMessageParser { public String getFormCode(String message) { String command = ""; String formCode = ""; Pattern pattern = Pattern.compile(typeRegex); Matcher matcher = pattern.matcher(message.trim()); if (matcher.find()) { command = matcher.group(); String[] formCodeParts = command.trim().split("="); if (formCodeParts.length == 2) { formCode = formCodeParts[1].trim(); } } return formCode; } IncomingMessage parseRequest(String message); String getCommand(String message); String getFormCode(String message); Map<String, IncomingMessageFormParameter> getParams(String message); void setCoreManager(CoreManager coreManager); void setDelimiter(String delimiter); void setCmdRegex(String cmdRegex); void setTypeRegex(String typeRegex); void setParamRegex(String paramRegex); void setSeparator(String separator); }### Answer: @Test public void testGetFormCode() { System.out.println("getFormCode"); String message = "Type=GENERAL\naction=test\nmessage=Test,, Tester"; String expResult = "GENERAL"; String result = imParser.getFormCode(message); assertEquals(expResult, result); }
### Question: IncomingMessageParserImpl implements IncomingMessageParser { public Map<String, IncomingMessageFormParameter> getParams(String message) { Map<String, IncomingMessageFormParameter> params = new HashMap<String, IncomingMessageFormParameter>(); List<String> pList = new ArrayList<String>(); if (delimiter != null && !delimiter.equals("")) { String[] paramArr = message.split(delimiter); for (String p : paramArr) { if (Pattern.matches(paramRegex, p) && !Pattern.matches(typeRegex, p)) { pList.add(p); } } } else { Pattern pattern = Pattern.compile(paramRegex); Matcher matcher = pattern.matcher(message.trim()); while (matcher.find()) { String match = matcher.group(); pList.add(match); } } for (String param : pList) { param = param.trim(); param = param.replace(delimiter + delimiter, delimiter); String[] paramParts = param.split(separator); if (paramParts.length == 2) { IncomingMessageFormParameter imParam = coreManager.createIncomingMessageFormParameter(); imParam.setDateCreated(new Date()); imParam.setMessageFormParamStatus(IncMessageFormParameterStatus.NEW); imParam.setName(paramParts[0].trim()); imParam.setValue(paramParts[1].trim()); params.put(imParam.getName().toLowerCase(), imParam); } } return params; } IncomingMessage parseRequest(String message); String getCommand(String message); String getFormCode(String message); Map<String, IncomingMessageFormParameter> getParams(String message); void setCoreManager(CoreManager coreManager); void setDelimiter(String delimiter); void setCmdRegex(String cmdRegex); void setTypeRegex(String typeRegex); void setParamRegex(String paramRegex); void setSeparator(String separator); }### Answer: @Test public void testGetParams() { System.out.println("getParams"); String message = "Type=GENERAL\naction=test\nmessage=Test, Dream Tester\ndob = 01.01.01\ndue-date=right. now\ntest_format=all"; List<IncomingMessageFormParameter> expResult = new ArrayList<IncomingMessageFormParameter>(); IncomingMessageFormParameter param1 = new IncomingMessageFormParameterImpl(); param1.setName("action"); param1.setValue("test"); expResult.add(param1); IncomingMessageFormParameter param2 = new IncomingMessageFormParameterImpl(); param1.setName("message"); param1.setValue("Test, Dream Tester"); expResult.add(param2); IncomingMessageFormParameter param3 = new IncomingMessageFormParameterImpl(); param1.setName("dob"); param1.setValue("01.01.01"); expResult.add(param3); IncomingMessageFormParameter param4 = new IncomingMessageFormParameterImpl(); param1.setName("due-date"); param1.setValue("right. now"); expResult.add(param4); IncomingMessageFormParameter param5 = new IncomingMessageFormParameterImpl(); param1.setName("test_format"); param1.setValue("all"); expResult.add(param5); expect( mockCore.createIncomingMessageFormParameter() ).andReturn(new IncomingMessageFormParameterImpl()).times(expResult.size()); replay(mockCore); Map<String,IncomingMessageFormParameter> result = imParser.getParams(message); verify(mockCore); assertNotNull(result); assertEquals(result.size(), expResult.size()); }
### Question: XMLUtil { public Element getElement(Document doc, String tagName) { Element result = null; if (tagName != null) { Element root = doc.getRootElement(); if (tagName.equals(root.getName())) { result = root; } else { List children = root.getChildren(); for(Object o : children) { Element e = (Element) o; if (e.getName() != null && e.getName().equals(tagName)) { result = e; break; } } } } return result; } Element getElement(Document doc, String tagName); }### Answer: @Test public void testGetElement() { System.out.println("getElement"); String xml = "<?xml version='1.0' encoding='UTF-8' ?><rootElement><sample>sometest</sample></rootElement>"; InputStream in = new ByteArrayInputStream(xml.getBytes()); SAXBuilder saxb = new SAXBuilder(); Document doc = null; try { doc = saxb.build(in); } catch (JDOMException jDOMException) { System.out.println("JDOMException: " + jDOMException.getMessage()); } catch (IOException iOException) { System.out.println("IOExceptionL " + iOException.getMessage()); } String tagName = "sample"; XMLUtil instance = new XMLUtil(); String expResult = "sometest"; Element result = instance.getElement(doc, tagName); assertEquals(expResult, result.getText()); }
### Question: IncomingMessageXMLParserImpl implements IncomingMessageXMLParser { public String toSMSMessage(String xml) throws JDOMException, IOException, MotechParseException { String result = ""; InputStream in = new ByteArrayInputStream(xml.getBytes()); SAXBuilder saxb = new SAXBuilder(); Document doc = null; doc = saxb.build(in); Element root = doc.getRootElement(); Element formTypeElement = getXmlUtil().getElement(doc, formTypeTagName); String formType = formTypeElement == null ? null : formTypeElement.getText(); if (formType == null || "".equals(formType.trim())) { String error = "Empty or No form type defined in xml with root element: " + root.getName() + " and id: " + root.getAttributeValue("id"); log.error(error); throw new MotechParseException(error); } String formTypeFieldName = formTypeLookup.get(formType); if (formTypeFieldName == null || formTypeFieldName.trim().equals("")) { String error = "Could not find a valid (non-null-or-white-space) form type field name associated with form type: " + formType; log.error(error); throw new MotechParseException(error); } Element formNameElement = xmlUtil.getElement(doc, formNameTagName); if (formNameElement == null) { throw new MotechParseException("No element (representing the Form Name) found by name " + formNameTagName); } result += formTypeFieldName + getSeparator() + formNameElement.getText(); List children = root.getChildren(); for (Object o : children) { Element child = (Element) o; if (!(child.getName().equalsIgnoreCase(formTypeTagName) || child.getName().equalsIgnoreCase(formNameTagName))) { result += getDelimiter() + child.getName() + getSeparator(); String text = child.getText(); Pattern p = Pattern.compile(oxdDateRegex); Matcher m = p.matcher(child.getText()); if (m.matches()) { try { SimpleDateFormat sdf = new SimpleDateFormat(oxdDateFormat); Date date = sdf.parse(child.getText()); sdf = new SimpleDateFormat(impDateFormat); text = sdf.format(date); } catch (ParseException ex) { log.error("Error changing date format", ex); } } result += text; } } return result; } ArrayList<String> parseXML(ArrayList<String> xmls); String toSMSMessage(String xml); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); IncomingMessageParser getMessageParser(); void setMessageParser(IncomingMessageParser messageParser); String getSeparator(); void setSeparator(String separator); String getDelimiter(); void setDelimiter(String delimiter); String getFormTypeTagName(); void setFormTypeTagName(String formTypeTagName); Map<String, String> getFormTypeLookup(); void setFormTypeLookup(Map<String, String> formTypeLookup); XMLUtil getXmlUtil(); void setXmlUtil(XMLUtil xmlUtil); String getFormNameTagName(); void setFormNameTagName(String formNameTagName); void setOxdDateFormat(String oxdDateFormat); void setOxdDateRegex(String oxdDateRegex); void setImpDateFormat(String impDateFormat); }### Answer: @Test public void testToSMSMessage() throws Exception{ System.out.println("toSMSMessage"); String xml = "<?xml version='1.0' encoding='UTF-8' ?><patientreg description-template=\"${/patientreg/lastname}$ in ${/patientreg/continent}$\" id=\"1\" name=\"Patient Registration\" xmlns:xf=\"http: String expResult = "Type=patientreg\npatientid=123\ntitle=mrs\nfirstname=Test\nlastname=Test\nsex=female\nbirthdate=03/06/1990\nweight=40\nheight=20\npregnant=false\ncontinent=africa\ncountry=uganda\ndistrict=mbale"; String result = ((IncomingMessageXMLParserImpl)xmlParser).toSMSMessage(xml); assertEquals(result, expResult); }
### Question: RetryStatusActionImpl implements StatusAction { public void doAction(GatewayResponse response){ } void doAction(GatewayResponse response); }### Answer: @Test public void testDoAction() { }
### Question: OMIManagerImpl implements OMIManager, ApplicationContextAware { public OMIService createOMIService() { try{ return (OMIService)context.getBean("omiService"); } catch(Exception ex){ logger.fatal("OMIService creation failed", ex); throw new RuntimeException("Service creation failure: OMI service unavailable."); } } void setApplicationContext(ApplicationContext applicationContext); OMIService createOMIService(); MessageStoreManager createMessageStoreManager(); SMSMessageFormatter createMessageFormatter(); }### Answer: @Test public void testCreateOMIService() { System.out.println("createOMIService"); OMIService result = omiManager.createOMIService(); assertNotNull(result); }
### Question: MessageTemplateDAOImpl extends HibernateGenericDAOImpl<MessageTemplateImpl> implements MessageTemplateDAO<MessageTemplateImpl> { public MessageTemplate getTemplateByLangNotifMType(Language lang, NotificationType notif, MessageType type) { logger.debug("variables passed to getTemplateByLangNotifMType. language: " + lang + "And NotificationType: " + notif + "And MessageType: " + type); try { MessageTemplate template = (MessageTemplate) this.getSessionFactory().getCurrentSession().createCriteria(MessageTemplateImpl.class).add(Restrictions.eq("language", lang)).add(Restrictions.eq("notificationType", notif)).add(Restrictions.eq("messageType", type)).uniqueResult(); logger.debug(template); return template; } catch (NonUniqueResultException ne) { logger.error("Method getTemplateByLangNotifMType returned more than one MessageTemplate object", ne); return null; } catch (HibernateException he) { logger.error(" Persistence or JDBC Exception in Method getTemplateByLangNotifMType", he); return null; } catch (Exception ex) { logger.error("Exception in Method getTemplateByLangNotifMType", ex); return null; } } MessageTemplate getTemplateByLangNotifMType(Language lang, NotificationType notif, MessageType type); MessageTemplate getTemplateByLangNotifMType(Language lang, NotificationType notif, MessageType type, Language defaultLang); }### Answer: @Test public void testGetTemplateByLangNotifMType() { System.out.println("getTemplateByLangNotifMType"); mtDao.getSessionFactory().getCurrentSession().save(mt2); MessageTemplate result = mtDao.getTemplateByLangNotifMType(l1, nt2, type); Assert.assertNotNull(result); Assert.assertEquals(mt2, result); }
### Question: OMIManagerImpl implements OMIManager, ApplicationContextAware { public MessageStoreManager createMessageStoreManager() { try{ return (MessageStoreManager)context.getBean("storeManager"); } catch(Exception ex){ logger.error("MessageStoreManager creation failed", ex); return null; } } void setApplicationContext(ApplicationContext applicationContext); OMIService createOMIService(); MessageStoreManager createMessageStoreManager(); SMSMessageFormatter createMessageFormatter(); }### Answer: @Test public void testCreateMessageStoreManager() { System.out.println("createMessageStoreManager"); MessageStoreManager result = omiManager.createMessageStoreManager(); assertNotNull(result); }