method2testcases
stringlengths 118
3.08k
|
---|
### Question:
StatelessStreamReceiver implements StreamReceiver { @Override public StreamConnectionDetails setupStream(final InterledgerAddress receiverAddress) { Objects.requireNonNull(receiverAddress); return streamConnectionGenerator.generateConnectionDetails(serverSecretSupplier, receiverAddress); } StatelessStreamReceiver(
final ServerSecretSupplier serverSecretSupplier, final StreamConnectionGenerator streamConnectionGenerator,
final StreamEncryptionService streamEncryptionService, final CodecContext streamCodecContext
); @Override StreamConnectionDetails setupStream(final InterledgerAddress receiverAddress); @Override InterledgerResponsePacket receiveMoney(
final InterledgerPreparePacket preparePacket, final InterledgerAddress receiverAddress,
final Denomination denomination
); }### Answer:
@Test public void setupStream() { StreamConnectionGenerator streamConnectionGenerator = mock(StreamConnectionGenerator.class); this.streamReceiver = new StatelessStreamReceiver( serverSecretSupplier, streamConnectionGenerator, streamEncryptionService, StreamCodecContextFactory.oer() ); InterledgerAddress receiverAddress = InterledgerAddress.of("example.receiver"); streamReceiver.setupStream(receiverAddress); Mockito.verify(streamConnectionGenerator).generateConnectionDetails(Mockito.any(), eq(receiverAddress)); } |
### Question:
AsnInterledgerAddressPrefixCodec extends
AsnIA5StringBasedObjectCodec<InterledgerAddressPrefix> { @Override public InterledgerAddressPrefix decode() { return InterledgerAddressPrefix.of(getCharString()); } AsnInterledgerAddressPrefixCodec(); @Override InterledgerAddressPrefix decode(); @Override void encode(InterledgerAddressPrefix value); }### Answer:
@Test public void decode() { assertThat(codec.decode()).isEqualTo(InterledgerAddressPrefix.of(G)); } |
### Question:
AsnSequenceOfSequenceCodec extends AsnObjectCodecBase<L> { public AsnSequenceCodec<T> getCodecAt(final int index) { Objects.requireNonNull(codecs); final AsnSequenceCodec<T> subCodec; if (codecs.size() == 0 || codecs.size() <= index) { subCodec = subCodecSupplier.get(); codecs.add(index, subCodec); } else { subCodec = codecs.get(index); } return subCodec; } AsnSequenceOfSequenceCodec(
final Supplier<L> listConstructor, final Supplier<AsnSequenceCodec<T>> subCodecSupplier
); int size(); AsnSequenceCodec<T> getCodecAt(final int index); @Override L decode(); @Override void encode(final L values); }### Answer:
@Test public void getCodecAtNegativeIndex() { expectedException.expect(IndexOutOfBoundsException.class); codec.getCodecAt(-1); }
@Test public void getCodecAtWithRandomAccess() { expectedException.expect(IndexOutOfBoundsException.class); codec.getCodecAt(100); } |
### Question:
AsnSequenceOfSequenceCodec extends AsnObjectCodecBase<L> { @Override public void encode(final L values) { Objects.requireNonNull(values); this.codecs = new ArrayList<>(CODECS_ARRAY_INITIAL_CAPACITY); for (T value : values) { AsnSequenceCodec<T> codec = subCodecSupplier.get(); codec.encode(value); this.codecs.add(codec); } } AsnSequenceOfSequenceCodec(
final Supplier<L> listConstructor, final Supplier<AsnSequenceCodec<T>> subCodecSupplier
); int size(); AsnSequenceCodec<T> getCodecAt(final int index); @Override L decode(); @Override void encode(final L values); }### Answer:
@Test public void testEncodeWithNullCodecsList() { expectedException.expect(NullPointerException.class); codec.encode(null); } |
### Question:
AsnUintCodecUL extends AsnOctetStringBasedObjectCodec<UnsignedLong> { @Override public UnsignedLong decode() { try { return UnsignedLong.valueOf(new BigInteger(1, getBytes())); } catch (Exception e) { if (defaultValue.isPresent()) { logger.warn( "Variable Unsigned Integer was too big for VarUInt: {}. Returning UnsignedLong.Max", Base64.getEncoder().encodeToString(getBytes()) ); return defaultValue.get(); } else { throw e; } } } AsnUintCodecUL(); AsnUintCodecUL(final UnsignedLong defaultValue); @Override UnsignedLong decode(); @Override void encode(final UnsignedLong value); }### Answer:
@Test public void decode() { codec = new AsnUintCodecUL(); codec.setBytes(new byte[]{1}); assertThat(codec.decode()).isEqualTo(UnsignedLong.ONE); }
@Test public void decodeValueTooLarge() { codec = new AsnUintCodecUL(UnsignedLong.ONE); byte[] bytes = new BigInteger("18446744073709551616").toByteArray(); codec.setBytes(bytes); assertThat(codec.decode()).isEqualTo(UnsignedLong.ONE); } |
### Question:
AsnInterledgerAddressPrefixCodec extends
AsnIA5StringBasedObjectCodec<InterledgerAddressPrefix> { @Override public void encode(InterledgerAddressPrefix value) { setCharString(value.getValue()); } AsnInterledgerAddressPrefixCodec(); @Override InterledgerAddressPrefix decode(); @Override void encode(InterledgerAddressPrefix value); }### Answer:
@Test public void encode() { codec.encode(InterledgerAddressPrefix.of(G)); assertThat(codec.getCharString()).isEqualTo(G); } |
### Question:
AsnUintCodecUL extends AsnOctetStringBasedObjectCodec<UnsignedLong> { @Override public void encode(final UnsignedLong value) { byte[] bytes = value.bigIntegerValue().toByteArray(); if (bytes[0] == 0x00 && bytes.length > 1) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(bytes, 1, bytes.length - 1); setBytes(baos.toByteArray()); return; } setBytes(bytes); } AsnUintCodecUL(); AsnUintCodecUL(final UnsignedLong defaultValue); @Override UnsignedLong decode(); @Override void encode(final UnsignedLong value); }### Answer:
@Test public void encode() { codec = new AsnUintCodecUL(); codec.encode(UnsignedLong.ONE); assertThat(codec.getBytes()).isEqualTo(new byte[] {1}); } |
### Question:
AsnUintCodec extends AsnOctetStringBasedObjectCodec<BigInteger> { @Override public void encode(final BigInteger value) { if (value.compareTo(BigInteger.ZERO) < 0) { throw new IllegalArgumentException("value must be positive or zero"); } byte[] bytes = value.toByteArray(); if (bytes[0] == 0x00 && bytes.length > 1) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(bytes, 1, bytes.length - 1); setBytes(baos.toByteArray()); return; } setBytes(bytes); } AsnUintCodec(); @Override BigInteger decode(); @Override void encode(final BigInteger value); }### Answer:
@Test(expected = IllegalArgumentException.class) public void encodeNegative() { try { codec.encode(BigInteger.valueOf(-1L)); } catch (IllegalArgumentException e) { assertThat(e.getMessage()).isEqualTo("value must be positive or zero"); throw e; } }
@Test public void encode() { codec.encode(expectedUint); assertThat(codec.getBytes()).isEqualTo(this.expectedEncodedBytes); } |
### Question:
AsnUintCodec extends AsnOctetStringBasedObjectCodec<BigInteger> { @Override public BigInteger decode() { return new BigInteger(1, getBytes()); } AsnUintCodec(); @Override BigInteger decode(); @Override void encode(final BigInteger value); }### Answer:
@Test public void decode() { codec.setBytes(this.expectedEncodedBytes); assertThat(codec.decode()).isEqualTo(this.expectedUint); } |
### Question:
AsnSizeConstraint { public boolean isFixedSize() { return max != 0 && max == min; } AsnSizeConstraint(int fixedSize); AsnSizeConstraint(int min, int max); boolean isUnconstrained(); boolean isFixedSize(); int getMax(); int getMin(); @Override boolean equals(Object obj); @Override int hashCode(); static final AsnSizeConstraint UNCONSTRAINED; }### Answer:
@Test public void isFixedSize() { final AsnSizeConstraint constraint = new AsnSizeConstraint(1); assertThat(constraint.isUnconstrained()).isFalse(); assertThat(constraint.isFixedSize()).isTrue(); assertThat(constraint.getMin()).isEqualTo(1); assertThat(constraint.getMax()).isEqualTo(1); } |
### Question:
AsnSizeConstraint { @Override public int hashCode() { int result = min; result = 31 * result + max; return result; } AsnSizeConstraint(int fixedSize); AsnSizeConstraint(int min, int max); boolean isUnconstrained(); boolean isFixedSize(); int getMax(); int getMin(); @Override boolean equals(Object obj); @Override int hashCode(); static final AsnSizeConstraint UNCONSTRAINED; }### Answer:
@Test public void equalsHashCode() { assertThat(AsnSizeConstraint.UNCONSTRAINED).isEqualTo(AsnSizeConstraint.UNCONSTRAINED); assertThat(AsnSizeConstraint.UNCONSTRAINED).isNotEqualTo(new AsnSizeConstraint(1)); assertThat(AsnSizeConstraint.UNCONSTRAINED.hashCode()).isEqualTo(AsnSizeConstraint.UNCONSTRAINED.hashCode()); assertThat(AsnSizeConstraint.UNCONSTRAINED.hashCode()).isNotEqualTo(new AsnSizeConstraint(1).hashCode()); } |
### Question:
AsnInterledgerAddressCodec extends AsnIA5StringBasedObjectCodec<InterledgerAddress> { @Override public InterledgerAddress decode() { return Optional.ofNullable(getCharString()) .filter(charString -> !"".equals(charString)) .map(InterledgerAddress::of) .orElse(null); } AsnInterledgerAddressCodec(); @Override InterledgerAddress decode(); @Override void encode(InterledgerAddress value); }### Answer:
@Test public void decode() { assertThat(codec.decode()).isEqualTo(InterledgerAddress.of(G_FOO)); } |
### Question:
LinkException extends RuntimeException { public LinkId getLinkId() { return linkId; } LinkException(LinkId linkId); LinkException(String message, LinkId linkId); LinkException(String message, Throwable cause, LinkId linkId); LinkException(Throwable cause, LinkId linkId); LinkException(
String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, LinkId linkId
); LinkId getLinkId(); @Override String toString(); }### Answer:
@Test public void getLinkId() { assertThat(new LinkException(LinkId.of("foo")).getLinkId().value()).isEqualTo("foo"); } |
### Question:
LinkException extends RuntimeException { @Override public String toString() { String linkIdMessage = "LinkId=" + getLinkId(); String className = getClass().getName(); String message = getLocalizedMessage() == null ? linkIdMessage : getLocalizedMessage() + " " + linkIdMessage; return (className + ": " + message); } LinkException(LinkId linkId); LinkException(String message, LinkId linkId); LinkException(String message, Throwable cause, LinkId linkId); LinkException(Throwable cause, LinkId linkId); LinkException(
String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, LinkId linkId
); LinkId getLinkId(); @Override String toString(); }### Answer:
@Test public void testToStringWithNullMessage() { assertThat(new LinkException(LinkId.of("foo")).toString()) .isEqualTo("org.interledger.link.exceptions.LinkException: LinkId=LinkId(foo)"); }
@Test public void testToString() { assertThat(new LinkException("hello", LinkId.of("foo")).toString()) .isEqualTo("org.interledger.link.exceptions.LinkException: hello LinkId=LinkId(foo)"); } |
### Question:
PingLoopbackLink extends AbstractLink<LinkSettings> implements Link<LinkSettings> { @Override public void registerLinkHandler(LinkHandler ilpDataHandler) throws LinkHandlerAlreadyRegisteredException { throw new RuntimeException( "PingLoopback links never have incoming data, and thus should not have a registered DataHandler." ); } PingLoopbackLink(
final Supplier<InterledgerAddress> operatorAddressSupplier, final LinkSettings linkSettings
); @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 PING_PROTOCOL_FULFILLMENT; static final InterledgerCondition PING_PROTOCOL_CONDITION; }### Answer:
@Test(expected = RuntimeException.class) public void registerLinkHandler() { try { link.registerLinkHandler(incomingPreparePacket -> null); } catch (Exception e) { assertThat(e.getMessage()).isEqualTo( "PingLoopback links never have incoming data, and thus should not have a registered DataHandler."); throw e; } } |
### 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:
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 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:
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:
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:
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:
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:
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 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 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 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 { 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:
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:
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:
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:
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:
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:
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); } |
### Question:
OMIManagerImpl implements OMIManager, ApplicationContextAware { public SMSMessageFormatter createMessageFormatter() { try{ return (SMSMessageFormatter)context.getBean("messageFormatter"); } catch(Exception ex){ logger.error("SMSMessageFormatter creation failed", ex); return null; } } void setApplicationContext(ApplicationContext applicationContext); OMIService createOMIService(); MessageStoreManager createMessageStoreManager(); SMSMessageFormatter createMessageFormatter(); }### Answer:
@Test public void testCreateMessageFormatter() { System.out.println("createMessageFormatter"); SMSMessageFormatter result = omiManager.createMessageFormatter(); assertNotNull(result); } |
### Question:
MessageStoreManagerImpl implements MessageStoreManager, ApplicationContextAware { String fetchTemplate(MessageRequest messageData, Language defaultLang) { if (messageData.getNotificationType() == null) return ""; MessageTemplate template = coreManager.createMessageTemplateDAO().getTemplateByLangNotifMType(messageData.getLanguage(), messageData.getNotificationType(), messageData.getMessageType(), defaultLang); if (template == null) throw new MotechException("No such NotificationType found"); return template.getTemplate(); } GatewayRequest constructMessage(MessageRequest messageRequest, Language defaultLang); String parseTemplate(String template, Set<NameValuePair> templateParams); String formatPhoneNumber(String requesterPhone, MessageType type); CoreManager getCoreManager(); void setCoreManager(CoreManager coreManager); void setMaxConcat(int maxConcat); void setCharsPerSMS(int charsPerSMS); void setConcatAllowance(int concatAllowance); void setLocalNumberExpression(String localNumberExpression); void setDefaultCountryCode(String defaultCountryCode); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testFetchTemplate() { System.out.println("fetchTemplate"); mockTemplateDao = createMock(MessageTemplateDAO.class); MessageRequest message = new MessageRequestImpl(); Language defaultLang = new LanguageImpl(); message.setNotificationType(new NotificationTypeImpl()); expect( mockCore.createMessageTemplateDAO() ).andReturn(mockTemplateDao); expect( mockTemplateDao.getTemplateByLangNotifMType((Language)anyObject(), (NotificationType) anyObject(), (MessageType) anyObject(), (Language) anyObject()) ).andReturn(template); replay(mockCore, mockTemplateDao); String result = instance.fetchTemplate(message, defaultLang); assertEquals(result, "testing"); verify(mockCore, mockTemplateDao); } |
### Question:
LogStatusActionImpl implements StatusAction { public void doAction(GatewayResponse response){ LogType logType; String summary = "Status of message with id " + response.getRequestId() + " is: " + response.getMessageStatus().toString() + ". Response from gateway was: " + response.getResponseText(); if(response.getMessageStatus() == MStatus.DELIVERED){ logType = LogType.SUCCESS; } else if(response.getMessageStatus() == MStatus.SENT){ logType = LogType.SUCCESS; } else{ logType = LogType.FAILURE; } try{ getRegWs().log(logType, summary); } catch(Exception e){ logger.error("Error communicating with logging service", e); } } void doAction(GatewayResponse response); RegistrarService getRegWs(); void setRegWs(RegistrarService regWs); }### Answer:
@Test public void testDoAction(){ System.out.println("doAction"); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(mockGatewayRequestDetails); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayRequest(messageDetails); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.PENDING); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(15000000002l); mockService.log((LogType) anyObject(), (String) anyObject()); expectLastCall(); replay(mockService); instance.doAction(response); verify(mockService); } |
### Question:
IMPManagerImpl implements ApplicationContextAware, IMPManager { public IMPService createIMPService(){ return (IMPService)context.getBean("impService"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testCreateIMPService() { System.out.println("createIMPService"); IMPService result = impManager.createIMPService(); assertNotNull(result); } |
### Question:
ReportStatusActionImpl implements StatusAction { public void doAction(GatewayResponse response) { if (response.getRequestId() == null || response.getRequestId().isEmpty()) { return; } if (response.getRecipientNumber() == null || response.getRecipientNumber().isEmpty()) { return; } try { if (response.getMessageStatus() == MStatus.DELIVERED) { getRegWs().setMessageStatus(response.getRequestId(), true); } else if (response.getMessageStatus() == MStatus.FAILED) { getRegWs().setMessageStatus(response.getRequestId(), false); } } catch (Exception e) { logger.error("Error communicating with event engine", e); } } void doAction(GatewayResponse response); RegistrarService getRegWs(); void setRegWs(RegistrarService regWs); }### Answer:
@Test public void testDoAction(){ System.out.println("doAction"); GatewayRequestDetails grd = new GatewayRequestDetailsImpl(); grd.setId(17000000002l); GatewayRequest messageDetails = new GatewayRequestImpl(); messageDetails.setDateFrom(new Date()); messageDetails.setMessage("a message for testing"); messageDetails.setDateTo(new Date()); messageDetails.setRecipientsNumber("000000000000"); messageDetails.setGatewayRequestDetails(grd); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayRequest(messageDetails); response.setGatewayMessageId("werfet54y56g645v4e"); response.setMessageStatus(MStatus.DELIVERED); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(17000000003l); instance.doAction(response); } |
### Question:
StatusHandlerImpl implements StatusHandler { public void handleStatus(GatewayResponse response) { List<StatusAction> actions = actionRegister.get(response.getMessageStatus()); if (actions != null) { for (StatusAction action : actions) { action.doAction(response); } } } void handleStatus(GatewayResponse response); boolean registerStatusAction(MStatus status, StatusAction action); Map<MStatus, List<StatusAction>> getActionRegister(); void setActionRegister(Map<MStatus, List<StatusAction>> registry); }### Answer:
@Test public void testHandleStatus(){ System.out.println("handleStatus"); GatewayResponse response = new GatewayResponseImpl(); response.setGatewayMessageId("DoActionwerfet54y56g645v4e"); response.setMessageStatus(MStatus.DELIVERED); response.setRecipientNumber("000000000000"); response.setResponseText("Some gateway response message"); response.setId(18000000001l); List<StatusAction> actionList = new ArrayList<StatusAction>(); actionList.add(mockAction); expect( mockRegister.get((MStatus) anyObject()) ).andReturn(actionList); mockAction.doAction(response); expectLastCall(); replay(mockRegister, mockAction); instance.handleStatus(response); verify(mockRegister, mockAction); } |
### Question:
StatusHandlerImpl implements StatusHandler { public boolean registerStatusAction(MStatus status, StatusAction action) { return actionRegister.get(status).add(action); } void handleStatus(GatewayResponse response); boolean registerStatusAction(MStatus status, StatusAction action); Map<MStatus, List<StatusAction>> getActionRegister(); void setActionRegister(Map<MStatus, List<StatusAction>> registry); }### Answer:
@Test public void testregisterStatusAction(){ System.out.println("registerStatusAction"); List<StatusAction> actionList = new ArrayList<StatusAction>(); expect( mockRegister.get((MStatus)anyObject()) ).andReturn(actionList); replay(mockRegister); instance.registerStatusAction(MStatus.PENDING, mockAction); verify(mockRegister); } |
### Question:
IMPManagerImpl implements ApplicationContextAware, IMPManager { public IncomingMessageParser createIncomingMessageParser(){ return (IncomingMessageParser)context.getBean("imParser"); } IMPService createIMPService(); IncomingMessageParser createIncomingMessageParser(); IncomingMessageXMLParser createIncomingMessageXMLParser(); IncomingMessageFormValidator createIncomingMessageFormValidator(); CommandAction createCommandAction(); void setApplicationContext(ApplicationContext applicationContext); }### Answer:
@Test public void testCreateIncomingMessageParser() { System.out.println("createIncomingMessageParser"); IncomingMessageParser result = impManager.createIncomingMessageParser(); assertNotNull(result); } |
### Question:
ClickatellGatewayMessageHandlerImpl implements GatewayMessageHandler { public MStatus parseMessageStatus(String gatewayResponse) { logger.debug("Parsing message gateway status response"); String status; String[] responseParts = gatewayResponse.split(" "); if(responseParts.length == 2){ status = responseParts[1]; } else 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.RETRY; MStatus result = instance.parseMessageStatus(messageStatus); assertEquals(expResult, result); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.