target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void shouldGetPartitionAddress() { assertThat(NamingUtils.getPartitionAddress("testAddress", 0)).isEqualTo("testAddress-0"); }
public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldGetNameForPartition() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getNameForPartition(0)).isEqualTo(getPartitionAddress(name, 0)); }
@Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } }
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getNameForPartition(int i) { return getPartitionAddress(name, i); } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }
@Test public void shouldGetName() { String name = "test-name"; ArtemisConsumerDestination destination = new ArtemisConsumerDestination(name); assertThat(destination.getName()).isEqualTo(name); }
@Override public String getName() { return name; }
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } }
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); }
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); }
ArtemisConsumerDestination implements ConsumerDestination { @Override public String getName() { return name; } ArtemisConsumerDestination(String name); @Override String getName(); @Override String toString(); }
@Test public void shouldCreateAddress() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).start(); verify(mockClientSession).createAddress(address, MULTICAST, true); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); }
public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldCreateAddressWithCredentials() throws Exception { given(mockServerLocator.isPreAcknowledge()).willReturn(true); given(mockServerLocator.getAckBatchSize()).willReturn(1); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, "user", "pass"); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession("user", "pass", true, false, false, true, 1); verify(mockClientSession).start(); verify(mockClientSession).createAddress(address, MULTICAST, true); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); }
public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldNotCreateAddressIfOneExists() throws Exception { given(mockAddressQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createAddress(address.toString(), artemisCommonProperties); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).start(); verify(mockClientSession).stop(); verify(mockClientSession, times(0)).createAddress(any(), any(RoutingType.class), anyBoolean()); verify(mockClientSession, times(0)).queueQuery(any(SimpleString.class)); verify(mockClientSession, times(0)).createMessage(anyBoolean()); }
public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldFailToCreateAddress() throws Exception { given(mockServerLocator.createSessionFactory()).willThrow(new RuntimeException("test")); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createAddress(address.toString(), artemisCommonProperties); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format("Failed to create address '%s'", address); assertThat(e.getMessage()).contains(message); } }
public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createAddress(String name, ArtemisCommonProperties properties) { logger.debug("Creating address '{}'", name); SimpleString nameString = SimpleString.toSimpleString(name); try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { session.start(); if (!session.addressQuery(nameString).isExists()) { session.createAddress(nameString, RoutingType.MULTICAST, true); if (properties.isModifyAddressSettings()) { configureAddress(session, name, properties); } } else { logger.debug("Address '{}' already exists, ignoring", name); } session.stop(); } catch (Exception e) { throw new ProvisioningException(String.format("Failed to create address '%s'", name), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldCreateQueue() throws Exception { ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession).createSharedQueue(address, MULTICAST, queue, true); }
public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldCreateQueueWithCredentials() throws Exception { given(mockServerLocator.isPreAcknowledge()).willReturn(true); given(mockServerLocator.getAckBatchSize()).willReturn(1); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, "user", "pass"); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession("user", "pass", true, false, false, true, 1); verify(mockClientSession).createSharedQueue(address, MULTICAST, queue, true); }
public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldNotCreateQueueIfOneAlreadyExists() throws Exception { given(mockQueueQuery.getAddress()).willReturn(address); given(mockQueueQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); manager.createQueue(address.toString(), queue.toString()); verify(mockServerLocator).createSessionFactory(); verify(mockClientSessionFactory).createSession(); verify(mockClientSession, times(0)).createSharedQueue(any(), any(RoutingType.class), any(), anyBoolean()); }
public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldFailToCreateQueue() throws Exception { given(mockServerLocator.createSessionFactory()).willThrow(new RuntimeException("test")); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createQueue(address.toString(), queue.toString()); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format("Failed to create queue '%s' with address '%s'", queue, address); assertThat(e.getMessage()).contains(message); } }
public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetPartitionAddress() { NamingUtils.getPartitionAddress(null, 0); }
public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
NamingUtils { public static String getPartitionAddress(String address, int partition) { Objects.requireNonNull(address); return String.format("%s-%d", address, partition); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldFailToCreateQueueIfOneAlreadyExistsUnderAnotherAddress() { SimpleString anotherAddress = toSimpleString("another-address-name"); given(mockQueueQuery.getAddress()).willReturn(anotherAddress); given(mockQueueQuery.isExists()).willReturn(true); ArtemisBrokerManager manager = new ArtemisBrokerManager(mockServerLocator, null, null); try { manager.createQueue(address.toString(), queue.toString()); fail("Provisioning exception was expected"); } catch (ProvisioningException e) { String message = String.format( "Failed to create queue '%s' with address '%s'. Queue already exists under another address '%s'", queue, address, anotherAddress); assertThat(e.getMessage()).contains(message); } }
public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
ArtemisBrokerManager { public void createQueue(String address, String name) { try (ClientSessionFactory sessionFactory = serverLocator.createSessionFactory(); ClientSession session = getClientSession(sessionFactory)) { createQueueInternal(session, address, name); } catch (ProvisioningException e) { throw e; } catch (Exception e) { throw new ProvisioningException( String.format("Failed to create queue '%s' with address '%s'", name, address), e); } } ArtemisBrokerManager(ServerLocator serverLocator, String username, String password); void createAddress(String name, ArtemisCommonProperties properties); void createQueue(String address, String name); }
@Test public void shouldProvisionUnpartitionedProducer() { ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisProducerProperties); verify(mockArtemisBrokerManager, times(0)).createQueue(anyString(), anyString()); }
@Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionUnpartitionedProducerWithRequiredGroups() { given(mockProducerProperties.getRequiredGroups()).willReturn(groups); ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createQueue(address, getQueueName(address, groups[0])); verify(mockArtemisBrokerManager).createQueue(address, getQueueName(address, groups[1])); }
@Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionPartitionedProducer() { String partitionedAddress0 = String.format("%s-0", address); String partitionedAddress1 = String.format("%s-1", address); given(mockProducerProperties.isPartitioned()).willReturn(true); given(mockProducerProperties.getPartitionCount()).willReturn(2); ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getNameForPartition(0)).isEqualTo(partitionedAddress0); assertThat(destination.getNameForPartition(1)).isEqualTo(partitionedAddress1); verify(mockArtemisBrokerManager).createAddress(partitionedAddress0, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createAddress(partitionedAddress1, mockArtemisProducerProperties); verify(mockArtemisBrokerManager, times(0)).createQueue(anyString(), anyString()); }
@Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionPartitionedProducerWithRequiredGroups() { String partitionedAddress0 = String.format("%s-0", address); String partitionedAddress1 = String.format("%s-1", address); given(mockProducerProperties.getRequiredGroups()).willReturn(groups); given(mockProducerProperties.isPartitioned()).willReturn(true); given(mockProducerProperties.getPartitionCount()).willReturn(2); ProducerDestination destination = provider.provisionProducerDestination(address, mockProducerProperties); assertThat(destination).isInstanceOf(ArtemisProducerDestination.class); assertThat(destination.getNameForPartition(0)).isEqualTo(partitionedAddress0); assertThat(destination.getNameForPartition(1)).isEqualTo(partitionedAddress1); verify(mockArtemisBrokerManager).createAddress(partitionedAddress0, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createAddress(partitionedAddress1, mockArtemisProducerProperties); verify(mockArtemisBrokerManager).createQueue(partitionedAddress0, getQueueName(partitionedAddress0, groups[0])); verify(mockArtemisBrokerManager).createQueue(partitionedAddress0, getQueueName(partitionedAddress0, groups[1])); verify(mockArtemisBrokerManager).createQueue(partitionedAddress1, getQueueName(partitionedAddress1, groups[0])); verify(mockArtemisBrokerManager).createQueue(partitionedAddress1, getQueueName(partitionedAddress1, groups[1])); }
@Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties) throws ProvisioningException { if (properties.isPartitioned()) { return provisionPartitionedProducerDestination(address, properties); } return provisionUnpartitionedProducerDestination(address, properties); } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionUnpartitionedConsumer() { ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(address); verify(mockArtemisBrokerManager).createAddress(address, mockArtemisConsumerProperties); }
@Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldProvisionPartitionedConsumer() { given(mockConsumerProperties.isPartitioned()).willReturn(true); given(mockConsumerProperties.getInstanceIndex()).willReturn(0); ConsumerDestination destination = provider.provisionConsumerDestination(address, null, mockConsumerProperties); String partitionedAddress = String.format("%s-0", address); assertThat(destination).isInstanceOf(ArtemisConsumerDestination.class); assertThat(destination.getName()).isEqualTo(partitionedAddress); verify(mockArtemisBrokerManager).createAddress(partitionedAddress, mockArtemisConsumerProperties); }
@Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
ArtemisProvisioningProvider implements ProvisioningProvider< ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>> { @Override public ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) throws ProvisioningException { ArtemisConsumerDestination destination; if (properties.isPartitioned()) { logger.debug("Provisioning partitioned consumer destination with address '{}' and instance index '{}'", address, properties.getInstanceIndex()); destination = new ArtemisConsumerDestination(getPartitionAddress(address, properties.getInstanceIndex())); } else { logger.debug("Provisioning unpartitioned consumer destination with address '{}'", address); destination = new ArtemisConsumerDestination(address); } artemisBrokerManager.createAddress(destination.getName(), properties.getExtension()); return destination; } ArtemisProvisioningProvider(ArtemisBrokerManager artemisBrokerManager); @Override ProducerDestination provisionProducerDestination(String address, ExtendedProducerProperties<ArtemisProducerProperties> properties); @Override ConsumerDestination provisionConsumerDestination(String address, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties); }
@Test public void shouldGetListenerContainer() { ListenerContainerFactory factory = new ListenerContainerFactory(mockConnectionFactory); AbstractMessageListenerContainer container = factory.getListenerContainer("testTopic", "testSubscription"); assertThat(container.getConnectionFactory()).isEqualTo(mockConnectionFactory); assertThat(container.getDestinationName()).isEqualTo("testTopic"); assertThat(container.isPubSubDomain()).isTrue(); assertThat(container.getSubscriptionName()).isEqualTo("testSubscription"); assertThat(container.isSessionTransacted()).isTrue(); assertThat(container.isSubscriptionDurable()).isTrue(); assertThat(container.isSubscriptionShared()).isTrue(); }
public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; }
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } }
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } ListenerContainerFactory(ConnectionFactory connectionFactory); }
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } ListenerContainerFactory(ConnectionFactory connectionFactory); AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName); }
ListenerContainerFactory { public AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName) { DefaultMessageListenerContainer listenerContainer = new DefaultMessageListenerContainer(); listenerContainer.setConnectionFactory(connectionFactory); listenerContainer.setPubSubDomain(true); listenerContainer.setDestinationName(topic); listenerContainer.setSubscriptionName(subscriptionName); listenerContainer.setSessionTransacted(true); listenerContainer.setSubscriptionDurable(true); listenerContainer.setSubscriptionShared(true); return listenerContainer; } ListenerContainerFactory(ConnectionFactory connectionFactory); AbstractMessageListenerContainer getListenerContainer(String topic, String subscriptionName); }
@Test public void shouldGetQueueName() { assertThat(NamingUtils.getQueueName("testAddress", "testGroup")).isEqualTo("testAddress-testGroup"); }
public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullAddressToGetQueueName() { NamingUtils.getQueueName(null, "testGroup"); }
public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test(expected = NullPointerException.class) public void shouldNotAcceptNullGroupToGetQueueName() { NamingUtils.getQueueName("testAddress", null); }
public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
NamingUtils { public static String getQueueName(String address, String group) { Objects.requireNonNull(address); Objects.requireNonNull(group); return String.format("%s-%s", address, group); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldGetAnonymousQueueName() { assertThat(NamingUtils.getAnonymousGroupName()).hasSize(32) .startsWith("anonymous-"); }
public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); }
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); } }
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); } }
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
NamingUtils { public static String getAnonymousGroupName() { UUID uuid = UUID.randomUUID(); ByteBuffer buffer = ByteBuffer.wrap(new byte[16]); buffer.putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); return "anonymous-" + Base64Utils.encodeToUrlSafeString(buffer.array()) .replaceAll("=", ""); } static String getPartitionAddress(String address, int partition); static String getQueueName(String address, String group); static String getAnonymousGroupName(); }
@Test public void shouldCreateProducerMessageHandler() { MessageHandler handler = binder.createProducerMessageHandler(null, null, null); assertThat(handler).isInstanceOf(JmsSendingMessageHandler.class); }
@Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties<ArtemisProducerProperties> properties, MessageChannel errorChannel) { logger.debug("Creating producer message handler for '" + destination + "'"); JmsSendingMessageHandler handler = Jms.outboundAdapter(connectionFactory) .destination(message -> getMessageDestination(message, destination)) .configureJmsTemplate(templateSpec -> templateSpec.pubSubDomain(true)) .get(); handler.setApplicationContext(getApplicationContext()); handler.setBeanFactory(getBeanFactory()); return handler; } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
@Test public void shouldCreateRegularConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(1); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties); assertThat(producer).isInstanceOf(JmsMessageDrivenEndpoint.class); JmsMessageDrivenEndpoint endpoint = (JmsMessageDrivenEndpoint) producer; assertThat(endpoint.getListener()).isNotInstanceOf(RetryableChannelPublishingJmsMessageListener.class); }
@Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
@Test public void shouldCreateRetryableConsumerEndpoint() { given(mockConsumerProperties.getMaxAttempts()).willReturn(2); ArtemisConsumerDestination destination = new ArtemisConsumerDestination("test-destination"); MessageProducer producer = binder.createConsumerEndpoint(destination, "test-group", mockConsumerProperties); assertThat(producer).isInstanceOf(JmsMessageDrivenEndpoint.class); ChannelPublishingJmsMessageListener listener = ((JmsMessageDrivenEndpoint) producer).getListener(); assertThat(listener).isInstanceOf(RetryableChannelPublishingJmsMessageListener.class); assertThat(listener.getComponentType()).isEqualTo("jms:message-driven-channel-adapter"); }
@Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
ArtemisMessageChannelBinder extends AbstractMessageChannelBinder<ExtendedConsumerProperties<ArtemisConsumerProperties>, ExtendedProducerProperties<ArtemisProducerProperties>, ArtemisProvisioningProvider> implements ExtendedPropertiesBinder<MessageChannel, ArtemisConsumerProperties, ArtemisProducerProperties> { @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, ExtendedConsumerProperties<ArtemisConsumerProperties> properties) { logger.debug("Creating consumer endpoint for '{" + destination + "}' with a group '{" + group + "}'"); if (!StringUtils.hasText(group)) { group = getAnonymousGroupName(); } String subscriptionName = getQueueName(destination.getName(), group); ListenerContainerFactory listenerContainerFactory = new ListenerContainerFactory(connectionFactory); AbstractMessageListenerContainer listenerContainer = listenerContainerFactory .getListenerContainer(destination.getName(), subscriptionName); if (properties.getMaxAttempts() == 1) { return Jms.messageDrivenChannelAdapter(listenerContainer).get(); } RetryTemplate retryTemplate = buildRetryTemplate(properties); ErrorInfrastructure errorInfrastructure = registerErrorInfrastructure(destination, group, properties); RetryableChannelPublishingJmsMessageListener listener = new RetryableChannelPublishingJmsMessageListener(retryTemplate, errorInfrastructure.getRecoverer()); listener.setExpectReply(false); return new JmsMessageDrivenEndpoint(listenerContainer, listener); } ArtemisMessageChannelBinder(ArtemisProvisioningProvider provisioningProvider, ConnectionFactory connectionFactory, ArtemisExtendedBindingProperties bindingProperties); @Override ArtemisConsumerProperties getExtendedConsumerProperties(String channelName); @Override ArtemisProducerProperties getExtendedProducerProperties(String channelName); @Override String getDefaultsPrefix(); @Override Class<? extends BinderSpecificPropertiesProvider> getExtendedPropertiesEntryClass(); }
@Test public void shouldGetName() { String name = "test-name"; ArtemisProducerDestination destination = new ArtemisProducerDestination(name); assertThat(destination.getName()).isEqualTo(name); }
@Override public String getName() { return name; }
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } }
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }
ArtemisProducerDestination implements ProducerDestination { @Override public String getName() { return name; } ArtemisProducerDestination(String name); @Override String getName(); @Override String getNameForPartition(int i); @Override String toString(); }
@Test public void readLabelsFromFile1() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-gold1.txt")); }
public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test public void readLabelsFromFile2() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-gold2.txt")); }
public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong1() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong1.txt")); }
public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong2() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong2.txt")); }
public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test(expected = IllegalArgumentException.class) public void readLabelsFromFileWrong3() throws Exception { Scorer.readLabelsFromFile(getFileFromResources("test-wrong3.txt")); }
public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
Scorer { public static Map<String, Integer> readLabelsFromFile(File file) throws IOException { FileInputStream inputStream = new FileInputStream(file); List<String> lines = IOUtils.readLines(inputStream, UTF8); IOUtils.closeQuietly(inputStream); Map<String, Integer> result = new TreeMap<>(); for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); if (!line.trim().isEmpty() && !line.trim().startsWith("#")) { String[] split = line.split("\\s+"); if (split.length != 2) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected two whitespace-delimited entries but got '" + line + "' (file " + file.getAbsolutePath() + ")"); } String id = split[0].trim(); int value; try { value = Integer.valueOf(split[1]); } catch (NumberFormatException e) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected an integer but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } if (!(value == 0 || value == 1)) { throw new IllegalArgumentException("Error on line " + (i + 1) + ", expected 0 or 1 but got '" + split[1] + "' (file " + file.getAbsolutePath() + ")"); } result.put(id, value); } } return result; } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test public void computeAccuracy() throws Exception { Map<String, Integer> gold = Scorer .readLabelsFromFile(getFileFromResources("test-gold1.txt")); Map<String, Integer> predictions1 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions1.txt")); assertEquals(0.6, Scorer.computeAccuracy(gold, predictions1), 0.01); Map<String, Integer> predictions2 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions2.txt")); assertEquals(1.0, Scorer.computeAccuracy(gold, predictions2), 0.01); Map<String, Integer> predictions3 = Scorer .readLabelsFromFile(getFileFromResources("test-predictions3.txt")); assertEquals(0.0, Scorer.computeAccuracy(gold, predictions3), 0.01); }
public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); }
Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); } }
Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); } }
Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
Scorer { public static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions) throws IllegalArgumentException { if (gold == null) { throw new IllegalArgumentException("Parameter 'gold' is null"); } if (predictions == null) { throw new IllegalArgumentException("Parameter 'predictions' is null"); } if (gold.isEmpty()) { throw new IllegalArgumentException("Parameter 'gold' is an empty map"); } if (predictions.isEmpty()) { throw new IllegalArgumentException("Parameter 'predictions' is an empty map"); } if (!(gold.keySet().containsAll(predictions.keySet()) && predictions.keySet() .containsAll(gold.keySet()))) { throw new IllegalArgumentException( "Gold set and predictions contain different instance IDs"); } Set<String> correctPredictions = new TreeSet<>(); Set<String> wrongPredictions = new TreeSet<>(); for (String id : gold.keySet()) { int goldLabel = gold.get(id); int predictedLabel = predictions.get(id); if (goldLabel == predictedLabel) { correctPredictions.add(id); } else { wrongPredictions.add(id); } } return ((double) correctPredictions.size()) / ((double) correctPredictions.size() + wrongPredictions.size()); } static Map<String, Integer> readLabelsFromFile(File file); static double computeAccuracy(Map<String, Integer> gold, Map<String, Integer> predictions); static void main(String[] args); }
@Test public void getDOI_inInput_shouldWork() { String input = "{\"reference-count\":176,\"publisher\":\"IOP Publishing\",\"issue\":\"4\",\"content-domain\":{\"domain\":[],\"crossmark-restriction\":false},\"short-container-title\":[\"Russ. Chem. Rev.\"],\"published-print\":{\"date-parts\":[[1998,4,30]]},\"DOI\":\"10.1070/rc1998v067n04abeh000372\",\"type\":\"journal-article\",\"created\":{\"date-parts\":[[2002,8,24]],\"date-time\":\"2002-08-24T21:29:52Z\",\"timestamp\":{\"$numberLong\":\"1030224592000\"}},\"page\":\"279-293\",\"source\":\"Crossref\",\"is-referenced-by-count\":24,\"title\":[\"Haloalkenes activated by geminal groups in reactions with N-nucleophiles\"],\"prefix\":\"10.1070\",\"volume\":\"67\",\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"Rulev\",\"sequence\":\"first\",\"affiliation\":[]}],\"member\":\"266\",\"published-online\":{\"date-parts\":[[2007,10,17]]},\"container-title\":[\"Russian Chemical Reviews\"],\"deposited\":{\"date-parts\":[[2017,11,23]],\"date-time\":\"2017-11-23T03:38:45Z\",\"timestamp\":{\"$numberLong\":\"1511408325000\"}},\"score\":1,\"issued\":{\"date-parts\":[[1998,4,30]]},\"references-count\":176,\"journal-issue\":{\"published-print\":{\"date-parts\":[[1998,4,30]]},\"issue\":\"4\"},\"URL\":\"http: String doi = "10.1070/rc1998v067n04abeh000372"; String output = target.fetchDOI(input); assertThat(output, is(doi)); }
public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); String retrieveByArticleMetadata(String title, String firstAuthor, Boolean postValidate); void retrieveByArticleMetadataAsync(String title, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, String atitle, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage, String firstAuthor); void retrieveByJournalMetadataAsync(String title, String volume, String firstPage, String firstAuthor, Consumer<MatchingDocument> callback); String retrieveByDoi(String doi, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmid(String pmid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmc(String pmc, Boolean postValidate, String firstAuthor, String atitle); String retrieveByIstexid(String istexid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPii(String pii, Boolean postValidate, String firstAuthor, String atitle); PmidData retrievePMidsByDoi(String doi); PmidData retrievePMidsByPmid(String pmid); PmidData retrievePMidsByPmc(String pmc); IstexData retrieveIstexIdsByDoi(String doi); IstexData retrieveIstexIdsByIstexId(String istexId); String retrieveOAUrlByDoi(String doi); Pair<String,String> retrieveOaIstexUrlByDoi(String doi); String retrieveOAUrlByPmid(String pmid); Pair<String,String> retrieveOaIstexUrlByPmid(String pmid); String retrieveOAUrlByPmc(String pmc); Pair<String,String> retrieveOaIstexUrlByPmc(String pmc); String retrieveOAUrlByPii(String pii); Pair<String,String> retrieveOaIstexUrlByPii(String pii); String retrieveByBiblio(String biblio); void retrieveByBiblioAsync(String biblio, Boolean postValidate, String firstAuthor, String title, Boolean parseReference, Consumer<MatchingDocument> callback); void retrieveByBiblioAsync(String biblio, Consumer<MatchingDocument> callback); String fetchDOI(String input); void setMetadataMatching(MetadataMatching metadataMatching); void setOaDoiLookup(OALookup oaDoiLookup); void setIstexLookup(IstexIdsLookup istexLookup); void setMetadataLookup(MetadataLookup metadataLookup); void setPmidLookup(PMIdsLookup pmidLookup); void setGrobidClient(GrobidClient grobidClient); }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); String retrieveByArticleMetadata(String title, String firstAuthor, Boolean postValidate); void retrieveByArticleMetadataAsync(String title, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, String atitle, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage, String firstAuthor); void retrieveByJournalMetadataAsync(String title, String volume, String firstPage, String firstAuthor, Consumer<MatchingDocument> callback); String retrieveByDoi(String doi, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmid(String pmid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmc(String pmc, Boolean postValidate, String firstAuthor, String atitle); String retrieveByIstexid(String istexid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPii(String pii, Boolean postValidate, String firstAuthor, String atitle); PmidData retrievePMidsByDoi(String doi); PmidData retrievePMidsByPmid(String pmid); PmidData retrievePMidsByPmc(String pmc); IstexData retrieveIstexIdsByDoi(String doi); IstexData retrieveIstexIdsByIstexId(String istexId); String retrieveOAUrlByDoi(String doi); Pair<String,String> retrieveOaIstexUrlByDoi(String doi); String retrieveOAUrlByPmid(String pmid); Pair<String,String> retrieveOaIstexUrlByPmid(String pmid); String retrieveOAUrlByPmc(String pmc); Pair<String,String> retrieveOaIstexUrlByPmc(String pmc); String retrieveOAUrlByPii(String pii); Pair<String,String> retrieveOaIstexUrlByPii(String pii); String retrieveByBiblio(String biblio); void retrieveByBiblioAsync(String biblio, Boolean postValidate, String firstAuthor, String title, Boolean parseReference, Consumer<MatchingDocument> callback); void retrieveByBiblioAsync(String biblio, Consumer<MatchingDocument> callback); String fetchDOI(String input); void setMetadataMatching(MetadataMatching metadataMatching); void setOaDoiLookup(OALookup oaDoiLookup); void setIstexLookup(IstexIdsLookup istexLookup); void setMetadataLookup(MetadataLookup metadataLookup); void setPmidLookup(PMIdsLookup pmidLookup); void setGrobidClient(GrobidClient grobidClient); static Pattern DOIPattern; }
@Test public void getByQuery_DOIexists_WithPostvalidation_shouldReturnJSONFromTitleFirstAuthor() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "12312312313\"],\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"" + firstAuthor + "\",\"sequence\":\"first\",\"affiliation\":[]}]}"; final MatchingDocument response = new MatchingDocument(myDOI, jsonOutput); expect(mockMetadataLookup.retrieveByMetadata(myDOI)).andReturn(new MatchingDocument()); mockMetadataMatching.retrieveByMetadataAsync(eq(atitle), eq(firstAuthor), anyObject()); replay(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); target.getByQuery(myDOI, null, null, null, null, firstAuthor, atitle, postValidate, null, null, null, null, null, mockedAsyncResponse); verify(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); }
protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
@Test public void getDOI_notInInput_shouldReturnNull() { String input = "{\"reference-count\":176,\"publisher\":\"IOP Publishing\",\"issue\":\"4\",\"content-domain\":{\"domain\":[],\"crossmark-restriction\":false},\"short-container-title\":[\"Russ. Chem. Rev.\"],\"published-print\":{\"date-parts\":[[1998,4,30]]},\"type\":\"journal-article\",\"created\":{\"date-parts\":[[2002,8,24]],\"date-time\":\"2002-08-24T21:29:52Z\",\"timestamp\":{\"$numberLong\":\"1030224592000\"}},\"page\":\"279-293\",\"source\":\"Crossref\",\"is-referenced-by-count\":24,\"title\":[\"Haloalkenes activated by geminal groups in reactions with N-nucleophiles\"],\"prefix\":\"10.1070\",\"volume\":\"67\",\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"Rulev\",\"sequence\":\"first\",\"affiliation\":[]}],\"member\":\"266\",\"published-online\":{\"date-parts\":[[2007,10,17]]},\"container-title\":[\"Russian Chemical Reviews\"],\"deposited\":{\"date-parts\":[[2017,11,23]],\"date-time\":\"2017-11-23T03:38:45Z\",\"timestamp\":{\"$numberLong\":\"1511408325000\"}},\"score\":1,\"issued\":{\"date-parts\":[[1998,4,30]]},\"references-count\":176,\"journal-issue\":{\"published-print\":{\"date-parts\":[[1998,4,30]]},\"issue\":\"4\"},\"URL\":\"http: String output = target.fetchDOI(input); assertThat(output, is(nullValue())); }
public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); String retrieveByArticleMetadata(String title, String firstAuthor, Boolean postValidate); void retrieveByArticleMetadataAsync(String title, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, String atitle, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage, String firstAuthor); void retrieveByJournalMetadataAsync(String title, String volume, String firstPage, String firstAuthor, Consumer<MatchingDocument> callback); String retrieveByDoi(String doi, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmid(String pmid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmc(String pmc, Boolean postValidate, String firstAuthor, String atitle); String retrieveByIstexid(String istexid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPii(String pii, Boolean postValidate, String firstAuthor, String atitle); PmidData retrievePMidsByDoi(String doi); PmidData retrievePMidsByPmid(String pmid); PmidData retrievePMidsByPmc(String pmc); IstexData retrieveIstexIdsByDoi(String doi); IstexData retrieveIstexIdsByIstexId(String istexId); String retrieveOAUrlByDoi(String doi); Pair<String,String> retrieveOaIstexUrlByDoi(String doi); String retrieveOAUrlByPmid(String pmid); Pair<String,String> retrieveOaIstexUrlByPmid(String pmid); String retrieveOAUrlByPmc(String pmc); Pair<String,String> retrieveOaIstexUrlByPmc(String pmc); String retrieveOAUrlByPii(String pii); Pair<String,String> retrieveOaIstexUrlByPii(String pii); String retrieveByBiblio(String biblio); void retrieveByBiblioAsync(String biblio, Boolean postValidate, String firstAuthor, String title, Boolean parseReference, Consumer<MatchingDocument> callback); void retrieveByBiblioAsync(String biblio, Consumer<MatchingDocument> callback); String fetchDOI(String input); void setMetadataMatching(MetadataMatching metadataMatching); void setOaDoiLookup(OALookup oaDoiLookup); void setIstexLookup(IstexIdsLookup istexLookup); void setMetadataLookup(MetadataLookup metadataLookup); void setPmidLookup(PMIdsLookup pmidLookup); void setGrobidClient(GrobidClient grobidClient); }
LookupEngine { public String fetchDOI(String input) { Matcher doiMatcher = DOIPattern.matcher(input); while (doiMatcher.find()) { if (doiMatcher.groupCount() == 1) { return doiMatcher.group(1); } } return null; } LookupEngine(); LookupEngine(StorageEnvFactory storageFactory); String retrieveByArticleMetadata(String title, String firstAuthor, Boolean postValidate); void retrieveByArticleMetadataAsync(String title, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, String atitle, String firstAuthor, Boolean postValidate, Consumer<MatchingDocument> callback); void retrieveByJournalMetadataAsync(String jtitle, String volume, String firstPage, Consumer<MatchingDocument> callback); String retrieveByJournalMetadata(String title, String volume, String firstPage, String firstAuthor); void retrieveByJournalMetadataAsync(String title, String volume, String firstPage, String firstAuthor, Consumer<MatchingDocument> callback); String retrieveByDoi(String doi, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmid(String pmid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPmc(String pmc, Boolean postValidate, String firstAuthor, String atitle); String retrieveByIstexid(String istexid, Boolean postValidate, String firstAuthor, String atitle); String retrieveByPii(String pii, Boolean postValidate, String firstAuthor, String atitle); PmidData retrievePMidsByDoi(String doi); PmidData retrievePMidsByPmid(String pmid); PmidData retrievePMidsByPmc(String pmc); IstexData retrieveIstexIdsByDoi(String doi); IstexData retrieveIstexIdsByIstexId(String istexId); String retrieveOAUrlByDoi(String doi); Pair<String,String> retrieveOaIstexUrlByDoi(String doi); String retrieveOAUrlByPmid(String pmid); Pair<String,String> retrieveOaIstexUrlByPmid(String pmid); String retrieveOAUrlByPmc(String pmc); Pair<String,String> retrieveOaIstexUrlByPmc(String pmc); String retrieveOAUrlByPii(String pii); Pair<String,String> retrieveOaIstexUrlByPii(String pii); String retrieveByBiblio(String biblio); void retrieveByBiblioAsync(String biblio, Boolean postValidate, String firstAuthor, String title, Boolean parseReference, Consumer<MatchingDocument> callback); void retrieveByBiblioAsync(String biblio, Consumer<MatchingDocument> callback); String fetchDOI(String input); void setMetadataMatching(MetadataMatching metadataMatching); void setOaDoiLookup(OALookup oaDoiLookup); void setIstexLookup(IstexIdsLookup istexLookup); void setMetadataLookup(MetadataLookup metadataLookup); void setPmidLookup(PMIdsLookup pmidLookup); void setGrobidClient(GrobidClient grobidClient); static Pattern DOIPattern; }
@Test public void testParsingPublication_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); }
public GrobidResponse getResponse() { return response; }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
@Test public void testParsingPublication2_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-2.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getFirstAuthorMonograph(), is("Gupta")); }
public GrobidResponse getResponse() { return response; }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
@Test public void testParsingPublication3_shouldWork() throws Exception { InputStream inputStream = this.getClass().getResourceAsStream("/sample.grobid-3.xml"); XMLStreamReader2 reader = (XMLStreamReader2) inputFactory.createXMLStreamReader(inputStream); StaxUtils.traverse(reader, target); GrobidResponseStaxHandler.GrobidResponse structures = target.getResponse(); assertThat(structures.getAtitle(), is("This si the end of the world")); assertThat(structures.getFirstAuthor(), is("Foppiano")); }
public GrobidResponse getResponse() { return response; }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
GrobidResponseStaxHandler implements StaxParserContentHandler { public GrobidResponse getResponse() { return response; } @Override void onStartDocument(XMLStreamReader2 reader); @Override void onEndDocument(XMLStreamReader2 reader); @Override void onStartElement(XMLStreamReader2 reader); @Override void onEndElement(XMLStreamReader2 reader); @Override void onCharacter(XMLStreamReader2 reader); GrobidResponse getResponse(); }
@Test public void test() throws Exception { IstexData metadata = target.fromJson("{\"corpusName\":\"bmj\",\"istexId\":\"052DFBD14E0015CA914E28A0A561675D36FFA2CC\",\"ark\":[\"ark:/67375/NVC-W015BZV5-Q\"],\"doi\":[\"10.1136/sti.53.1.56\"],\"pmid\":[\"557360\"],\"pii\":[\"123\"]}"); assertThat(metadata, is(not(nullValue()))); assertThat(metadata.getCorpusName(), is("bmj")); assertThat(metadata.getIstexId(), is("052DFBD14E0015CA914E28A0A561675D36FFA2CC")); assertThat(metadata.getDoi(), hasSize(1)); assertThat(metadata.getDoi().get(0), is("10.1136/sti.53.1.56")); assertThat(metadata.getArk(), hasSize(1)); assertThat(metadata.getArk().get(0), is("ark:/67375/NVC-W015BZV5-Q")); assertThat(metadata.getPmid(), hasSize(1)); assertThat(metadata.getPmid().get(0), is("557360")); assertThat(metadata.getPii(), hasSize(1)); assertThat(metadata.getPii().get(0), is("123")); }
public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; }
IstexIdsReader { public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; } }
IstexIdsReader { public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; } }
IstexIdsReader { public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }
IstexIdsReader { public IstexData fromJson(String inputLine) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); return mapper.readValue(inputLine, IstexData.class); } catch (JsonGenerationException | JsonMappingException e) { LOGGER.error("The input line cannot be processed\n " + inputLine + "\n ", e); } catch (IOException e) { LOGGER.error("Some serious error when deserialize the JSON object: \n" + inputLine, e); } return null; } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }
@Test public void test3() throws Exception { target.load( new GZIPInputStream(this.getClass().getResourceAsStream("/sample-istex-ids.json.gz")), unpaidWallMetadata -> System.out.println(unpaidWallMetadata.getDoi() )); }
public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } }
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } }
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } }
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }
IstexIdsReader { public void load(String input, Consumer<IstexData> closure) { try (Stream<String> stream = Files.lines(Paths.get(input))) { stream.forEach(line -> closure.accept(fromJson(line))); } catch (IOException e) { LOGGER.error("Some serious error when processing the input Istex ID file.", e); } } void load(String input, Consumer<IstexData> closure); void load(InputStream input, Consumer<IstexData> closure); IstexData fromJson(String inputLine); }
@Test public void test() throws Exception { PmidData metadata = target.fromCSV("9999996,,\"https: assertThat(metadata, is(not(nullValue()))); assertThat(metadata.getDoi(), is ("10.1103/physrevb.44.3678")); assertThat(metadata.getPmid(), is ("9999996")); assertThat(metadata.getPmcid(), is ("")); }
public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; }
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } }
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } }
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } void load(String input, Consumer<PmidData> closure); void load(InputStream input, Consumer<PmidData> closure); PmidData fromCSV(String inputLine); }
PmidReader { public PmidData fromCSV(String inputLine) { final String[] split = StringUtils.splitPreserveAllTokens(inputLine, ","); if (split.length > 0 && split.length <= 3) { return new PmidData(split[0], split[1], replaceAll(split[2], "\"", "")); } return null; } void load(String input, Consumer<PmidData> closure); void load(InputStream input, Consumer<PmidData> closure); PmidData fromCSV(String inputLine); }
@Test public void getByQuery_DOIexists_passingPostValidation_shouldReturnJSONBody() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "\"],\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"" + firstAuthor + "\",\"sequence\":\"first\",\"affiliation\":[]}]}"; final MatchingDocument response = new MatchingDocument(myDOI, jsonOutput); expect(mockMetadataLookup.retrieveByMetadata(myDOI)).andReturn(response); expect(mockIstexLookup.retrieveByDoi(myDOI)).andReturn(null); expect(mockPmidsLookup.retrieveIdsByDoi(myDOI)).andReturn(null); expect(mockOALookup.retrieveOaLinkByDoi(myDOI)).andReturn(null); expect(mockedAsyncResponse.resume(response.getJsonObject())).andReturn(true); replay(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); target.getByQuery(myDOI, null, null, null, null, firstAuthor, atitle, postValidate, null, null, null, null, null, mockedAsyncResponse); verify(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); }
protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
@Test public void getByQuery_DOIexists_NotPassingPostValidation_shouldReturnJSONFromTitleFirstAuthor() { final String myDOI = "myDOI"; final boolean postValidate = true; final String atitle = "atitle"; final String firstAuthor = "firstAuthor"; final String jsonOutput = "{\"DOI\":\"" + myDOI + "\",\"title\":[\"" + atitle + "12312312313\"],\"author\":[{\"given\":\"Alexander Yu\",\"family\":\"" + firstAuthor + "\",\"sequence\":\"first\",\"affiliation\":[]}]}"; final MatchingDocument response = new MatchingDocument(myDOI, jsonOutput); expect(mockMetadataLookup.retrieveByMetadata(myDOI)).andReturn(response); mockMetadataMatching.retrieveByMetadataAsync(eq(atitle), eq(firstAuthor), anyObject()); replay(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); target.getByQuery(myDOI, null, null, null, null, firstAuthor, atitle, postValidate, null, null, null, null, null, mockedAsyncResponse); verify(mockMetadataLookup, mockedAsyncResponse, mockPmidsLookup, mockOALookup, mockIstexLookup, mockMetadataMatching); }
protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
LookupController { protected void getByQuery( String doi, String pmid, String pmc, String pii, String istexid, String firstAuthor, String atitle, final Boolean postValidate, String jtitle, String volume, String firstPage, String biblio, final Boolean parseReference, AsyncResponse asyncResponse ) { boolean areParametersEnoughToLookup = false; StringBuilder messagesSb = new StringBuilder(); if (isNotBlank(doi)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByDoi(doi, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { messagesSb.append(e.getMessage()); LOGGER.warn("DOI did not matched, move to additional metadata"); } } if (isNotBlank(pmid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmid(pmid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMID did not matched, move to additional metadata"); } } if (isNotBlank(pmc)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPmc(pmc, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PMC ID did not matched, move to additional metadata"); } } if (isNotBlank(pii)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByPii(pii, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("PII ID did not matched, move to additional metadata"); } } if (isNotBlank(istexid)) { areParametersEnoughToLookup = true; try { final String response = lookupEngine.retrieveByIstexid(istexid, postValidate, firstAuthor, atitle); if (isNotBlank(response)) { asyncResponse.resume(response); return; } } catch (NotFoundException e) { LOGGER.warn("ISTEX ID did not matched, move to additional metadata"); } } if (isNotBlank(atitle) && isNotBlank(firstAuthor)) { LOGGER.debug("Match with metadata"); lookupEngine.retrieveByArticleMetadataAsync(atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { LOGGER.debug("Error with title/first author, trying to match with journal infos (no first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal title, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, MatchingDocumentBiblio -> { if (MatchingDocumentBiblio.isException()) { asyncResponse.resume(MatchingDocumentBiblio.getException()); } else { asyncResponse.resume(MatchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with journal infos (with first author)"); if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocumentJournal -> { if (matchingDocumentJournal.isException()) { LOGGER.debug("Error with journal info, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocumentJournal.getFinalJsonObject()); } }); return; } LOGGER.debug("Error with title/first author, trying to match with biblio string"); if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(firstAuthor) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title and first page"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(jtitle) && isNotBlank(volume) && isNotBlank(firstPage)) { LOGGER.debug("Match with journal title without first author"); lookupEngine.retrieveByJournalMetadataAsync(jtitle, volume, firstPage, atitle, firstAuthor, postValidate, matchingDocument -> { if (matchingDocument.isException()) { if (isNotBlank(biblio)) { lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } else { asyncResponse.resume(matchingDocument.getException()); } } else { asyncResponse.resume(matchingDocument.getFinalJsonObject()); } }); return; } if (isNotBlank(biblio)) { LOGGER.debug("Match with biblio string"); lookupEngine.retrieveByBiblioAsync(biblio, postValidate, firstAuthor, atitle, parseReference, matchingDocumentBiblio -> { if (matchingDocumentBiblio.isException()) { asyncResponse.resume(matchingDocumentBiblio.getException()); } else { asyncResponse.resume(matchingDocumentBiblio.getFinalJsonObject()); } }); return; } if (areParametersEnoughToLookup) { throw new ServiceException(404, messagesSb.toString()); } else { throw new ServiceException(400, "The supplied parameters were not sufficient to select the query"); } } protected LookupController(); @Inject LookupController(LookupConfiguration configuration, StorageEnvFactory storageEnvFactory); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/") void getByQueryAsync( @QueryParam("doi") String doi, @QueryParam("pmid") String pmid, @QueryParam("pmc") String pmc, @QueryParam("pii") String pii, @QueryParam("istexid") String istexid, @QueryParam("firstAuthor") String firstAuthor, @QueryParam("atitle") String atitle, @QueryParam("postValidate") Boolean postValidate, @QueryParam("jtitle") String jtitle, @QueryParam("volume") String volume, @QueryParam("firstPage") String firstPage, @QueryParam("biblio") String biblio, @QueryParam("parseReference") Boolean parseReference, @Suspended final AsyncResponse asyncResponse); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/doi/{doi}") String getByDoi(@PathParam("doi") String doi); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmid/{pmid}") String getByPmid(@PathParam("pmid") String pmid); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pii/{pii}") String getByPii(@PathParam("pii") String pii); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/pmc/{pmc}") String getByPmc(@PathParam("pmc") String pmc); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/istexid/{istexid}") String getByIstexid(@PathParam("istexid") String istexid); @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/") void getByBiblioStringWithPost(String biblio, @Suspended final AsyncResponse asyncResponse); }
@Test public void whenListFiltered_returnSavedList() { List<SupplyLocation> locations = new ArrayList<>(); locations.add(generateSupplyLocations(4, 4, "504")); when(service.saveSupplyLocationsZipContains504(inputLocations)).thenReturn(locations); assertThat(controller.uploadFitleredLocations(inputLocations)).size().isEqualTo(1); assertThat(controller.uploadFitleredLocations(inputLocations).get(0).getZip()).isEqualTo("504"); }
public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); }
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } }
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository, SupplyLocationService service); }
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository, SupplyLocationService service); @RequestMapping(value = "/bulk/supplyLocations", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void upload(@RequestBody List<SupplyLocation> locations); @RequestMapping(value = "/purge", method = RequestMethod.POST) void purge(); List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations); }
SupplyLocationBulkUploadController { public List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations) { return this.service.saveSupplyLocationsZipContains504(locations); } @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository); @Autowired SupplyLocationBulkUploadController(SupplyLocationRepository repository, SupplyLocationService service); @RequestMapping(value = "/bulk/supplyLocations", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) void upload(@RequestBody List<SupplyLocation> locations); @RequestMapping(value = "/purge", method = RequestMethod.POST) void purge(); List<SupplyLocation> uploadFitleredLocations(List<SupplyLocation> locations); }
@Test public void disallowsNullKeyAndNullValue() { assertFalse(generator.okToAdd(null, null)); }
@Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void choosingFromEmptyCollection() { thrown.expect(IllegalArgumentException.class); Items.choose(emptyList(), random); }
@SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { @SuppressWarnings("unchecked") public static <T> T choose(Collection<T> items, SourceOfRandomness random) { int size = items.size(); if (size == 0) { throw new IllegalArgumentException( "Collection is empty, can't pick an element from it"); } if (items instanceof RandomAccess && items instanceof List<?>) { List<T> list = (List<T>) items; return size == 1 ? list.get(0) : list.get(random.nextInt(size)); } if (size == 1) { return items.iterator().next(); } Object[] array = items.toArray(new Object[0]); return (T) array[random.nextInt(array.length)]; } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void choosingWeightedFromEmptyCollection() { thrown.expect(AssertionError.class); thrown.expectMessage("sample = 0, range = 0"); Items.chooseWeighted(emptyList(), random); }
public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
Items { public static <T> T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random) { if (items.size() == 1) return items.iterator().next().item; int range = items.stream().mapToInt(i -> i.weight).sum(); int sample = random.nextInt(range); int threshold = 0; for (Weighted<T> each : items) { threshold += each.weight; if (sample < threshold) return each.item; } throw new AssertionError( String.format("sample = %d, range = %d", sample, range)); } private Items(); @SuppressWarnings("unchecked") static T choose(Collection<T> items, SourceOfRandomness random); static T chooseWeighted( Collection<Weighted<T>> items, SourceOfRandomness random); }
@Test public void rejectsNegativeRemovalCount() { thrown.expect(IllegalArgumentException.class); Lists.removeFrom(newArrayList("abc"), -1); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void removalsOfZeroElementsFromAList() { List<Integer> target = newArrayList(1, 2, 3); assertEquals(singletonList(target), Lists.removeFrom(target, 0)); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void removalsFromAnEmptyList() { assertEquals(emptyList(), Lists.removeFrom(emptyList(), 1)); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void singleRemovalsFromASingletonList() { assertEquals(singletonList(emptyList()), Lists.removeFrom(singletonList('a'), 1)); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void singleRemovalsFromADoubletonList() { assertEquals( newHashSet(singletonList('a'), singletonList('b')), newHashSet(Lists.removeFrom(newArrayList('a', 'b'), 1))); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void doubleRemovalsFromADoubletonList() { assertEquals(singletonList(emptyList()), Lists.removeFrom(newArrayList('a', 'b'), 2)); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void tooManyRemovalsFromADoubletonList() { assertEquals(emptyList(), Lists.removeFrom(newArrayList('a', 'b'), 3)); }
public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> removeFrom(List<T> target, int howMany) { if (howMany < 0) throw new IllegalArgumentException("Can't remove " + howMany + " elements from a list"); if (howMany == 0) return singletonList(target); if (howMany > target.size()) return emptyList(); List<T> left = target.subList(0, howMany); List<T> right = target.subList(howMany, target.size()); if (right.isEmpty()) return singletonList(emptyList()); List<List<T>> removals = new ArrayList<>(); removals.add(right); removals.addAll(removeFrom(right, howMany) .stream() .map(r -> { List<T> items = new ArrayList<>(left); items.addAll(r); return items; }) .collect(toList())); return removals; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void shrinksOfEmptyList() { assertEquals(emptyList(), Lists.shrinksOfOneItem(random, emptyList(), null)); }
public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void rejectsNonFunctionalInterface() { thrown.expect(IllegalArgumentException.class); thrown.expectMessage(Cloneable.class + " is not a functional interface"); makeLambda(Cloneable.class, new AnInt(), status); }
public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
@Test public void shrinksOfNonEmptyList() { List<List<Integer>> shrinks = Lists.shrinksOfOneItem( random, newArrayList(1, 2, 3), (r, i) -> { assumeThat(r, sameInstance(random)); return newArrayList(4, 5); }); assertEquals( newArrayList( newArrayList(4, 2, 3), newArrayList(5, 2, 3), newArrayList(1, 4, 3), newArrayList(1, 5, 3), newArrayList(1, 2, 4), newArrayList(1, 2, 5) ), shrinks); }
public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
Lists { public static <T> List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink) { if (target.isEmpty()) return new ArrayList<>(); T head = target.get(0); List<T> tail = target.subList(1, target.size()); List<List<T>> shrinks = new ArrayList<>(); shrinks.addAll( shrink.shrink(random, head) .stream() .map(i -> { List<T> items = new ArrayList<>(); items.add(i); items.addAll(tail); return items; }) .collect(toList())); shrinks.addAll( shrinksOfOneItem(random, tail, shrink) .stream() .map(s -> { List<T> items = new ArrayList<>(); items.add(head); items.addAll(s); return items; }) .collect(toList())); return shrinks; } private Lists(); static List<List<T>> removeFrom(List<T> target, int howMany); static List<List<T>> shrinksOfOneItem( SourceOfRandomness random, List<T> target, Shrink<T> shrink); static boolean isDistinct(List<T> target); }
@Test public void invokingDefaultMethodOnFunctionalInterface() { System.out.println(System.getProperty("java.version")); @SuppressWarnings("unchecked") Predicate<Integer> another = makeLambda(Predicate.class, returnValueGenerator, status); boolean firstResult = predicate.test(4); boolean secondResult = another.test(4); assertEquals(firstResult || secondResult, predicate.or(another).test(4)); }
public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
Lambdas { public static <T, U> T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status) { if (singleAbstractMethodOf(lambdaType) == null) { throw new IllegalArgumentException( lambdaType + " is not a functional interface type"); } return lambdaType.cast( newProxyInstance( lambdaType.getClassLoader(), new Class<?>[] { lambdaType }, new LambdaInvocationHandler<>( lambdaType, returnValueGenerator, status.attempts()))); } private Lambdas(); static T makeLambda( Class<T> lambdaType, Generator<U> returnValueGenerator, GenerationStatus status); }
@Test public void stringifying() { assertEquals("[1 = 2]", new Pair<>(1, 2).toString()); }
@Override public String toString() { return String.format("[%s = %s]", first, second); }
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } }
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); }
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); }
Pair { @Override public String toString() { return String.format("[%s = %s]", first, second); } Pair(F first, S second); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); final F first; final S second; }
@Test public void halvingBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(5), BigInteger.valueOf(7), BigInteger.valueOf(8), BigInteger.valueOf(9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN, BigInteger.ZERO))); }
public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(5), BigDecimal.valueOf(8), BigDecimal.valueOf(9), BigDecimal.TEN), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN, BigDecimal.ZERO))); }
public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingNegativeBigIntegers() { assertEquals( newArrayList( BigInteger.valueOf(-5), BigInteger.valueOf(-7), BigInteger.valueOf(-8), BigInteger.valueOf(-9)), newArrayList(Sequences.halvingIntegral(BigInteger.TEN.negate(), BigInteger.ZERO))); }
public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingNegativeBigDecimals() { assertEquals( newArrayList( BigDecimal.valueOf(-5), BigDecimal.valueOf(-8), BigDecimal.valueOf(-9), BigDecimal.TEN.negate()), newArrayList(Sequences.halvingDecimal(BigDecimal.TEN.negate(), BigDecimal.ZERO))); }
public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void halvingInts() { assertEquals( newArrayList(27, 13, 6, 3, 1), newArrayList(Sequences.halving(27))); }
public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void callingNextOutOfSequenceOnHalvingBigIntegers() { Iterator<BigInteger> i = Sequences.halvingIntegral(BigInteger.ZERO, BigInteger.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start) { return () -> new BigIntegerHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void callingNextOutOfSequenceOnHalvingBigDecimals() { Iterator<BigDecimal> i = Sequences.halvingDecimal(BigDecimal.ZERO, BigDecimal.ZERO).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start) { return () -> new BigDecimalHalvingIterator(start, max); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void disallowsNullKey() { assertFalse(generator.okToAdd(null, new Object())); }
@Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void callingNextOutOfSequenceOnHalvingInts() { Iterator<Integer> i = Sequences.halving(0).iterator(); i.next(); thrown.expect(NoSuchElementException.class); i.next(); }
public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
Sequences { public static Iterable<Integer> halving(int start) { return () -> new IntegerHalvingIterator(start); } private Sequences(); static Iterable<BigInteger> halvingIntegral( BigInteger max, BigInteger start); static Iterable<BigDecimal> halvingDecimal( BigDecimal max, BigDecimal start); static Iterable<Integer> halving(int start); }
@Test public void capabilityOfShrinkingNonEnum() { assertFalse(generator.canShrink(new Object())); }
@Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
@Test public void capabilityOfShrinkingEnumOfDesiredType() { assertTrue(generator.canShrink(ElementType.METHOD)); }
@Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
@Test public void capabilityOfShrinkingEnumOfOtherType() { assertFalse(generator.canShrink(RetentionPolicy.SOURCE)); }
@Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
EnumGenerator extends Generator<Enum> { @Override public boolean canShrink(Object larger) { return enumType.isInstance(larger); } EnumGenerator(Class<?> enumType); @Override Enum<?> generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); }
@Test public void capabilityOfShrinkingDependsOnComponents() { when(first.canShrink(9)).thenReturn(true); when(second.canShrink(9)).thenReturn(false); when(third.canShrink(9)).thenReturn(true); assertTrue(composite.canShrink(9)); }
@Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void capabilityOfShrinkingFalseIfNoComponentsCanShrinkAValue() { when(first.canShrink(8)).thenReturn(false); when(second.canShrink(8)).thenReturn(false); when(third.canShrink(8)).thenReturn(false); assertFalse(composite.canShrink(8)); }
@Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
CompositeGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return composed.stream() .map(w -> w.item) .anyMatch(g -> g.canShrink(larger)); } CompositeGenerator(List<Weighted<Generator<?>>> composed); @Override Object generate(SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); Generator<?> composed(int index); int numberOfComposedGenerators(); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); @Override void configure(AnnotatedElement element); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void capabilityOfShrinkingNonArray() { assertFalse(intArrayGenerator.canShrink(3)); }
@Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
@Test public void capabilityOfShrinkingArrayOfIdenticalComponentType() { assertTrue(intArrayGenerator.canShrink(new int[0])); }
@Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
@Test public void capabilityOfShrinkingArrayOfEquivalentWrapperComponentType() { assertFalse(intArrayGenerator.canShrink(new Integer[0])); }
@Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
ArrayGenerator extends Generator<Object> { @Override public boolean canShrink(Object larger) { return larger.getClass().getComponentType() == componentType; } ArrayGenerator(Class<?> componentType, Generator<?> component); void configure(Size size); void configure(Distinct distinct); @Override Object generate( SourceOfRandomness random, GenerationStatus status); @Override boolean canShrink(Object larger); @Override List<Object> doShrink(SourceOfRandomness random, Object larger); @Override void provide(Generators provided); @Override BigDecimal magnitude(Object value); @Override void configure(AnnotatedType annotatedType); }
@Test public void leastMagnitudeUnbounded() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, null, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void disallowsNullValue() { assertFalse(generator.okToAdd(new Object(), null)); }
@Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void leastMagnitudeNegativeMinOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-3, null, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudePositiveMinOnly() { assertEquals(Integer.valueOf(4), Comparables.leastMagnitude(4, null, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudeNegativeMaxOnly() { assertEquals(Integer.valueOf(-2), Comparables.leastMagnitude(null, -2, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudePositiveMaxOnly() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(null, 5, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudeBothLessThanZero() { assertEquals(Integer.valueOf(-1), Comparables.leastMagnitude(-4, -1, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudeBothGreaterThanZero() { assertEquals(Integer.valueOf(5), Comparables.leastMagnitude(5, 7, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void leastMagnitudeStraddlingZero() { assertEquals(Integer.valueOf(0), Comparables.leastMagnitude(-2, 4, 0)); }
public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
Comparables { public static <T extends Comparable<? super T>> T leastMagnitude( T min, T max, T zero) { if (min == null && max == null) return zero; if (min == null) return max.compareTo(zero) <= 0 ? max : zero; if (max == null) return min.compareTo(zero) >= 0 ? min : zero; if (min.compareTo(zero) > 0) return min; if (max.compareTo(zero) < 0) return max; return zero; } private Comparables(); static Predicate<T> inRange( T min, T max); static T leastMagnitude( T min, T max, T zero); }
@Test public void negativeProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(-ulp(0), random); }
int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void zeroProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(0, random); }
int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void greaterThanOneProbability() { thrown.expect(IllegalArgumentException.class); distro.sample(1 + ulp(1), random); }
int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void allowsKeyAndValueWhenNeitherIsNull() { assertTrue(generator.okToAdd(new Object(), new Object())); }
@Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
HashtableGenerator extends MapGenerator<Hashtable> { @Override protected boolean okToAdd(Object key, Object value) { return key != null && value != null; } HashtableGenerator(); @Override void addComponentGenerators(List<Generator<?>> newComponents); }
@Test public void sampleWithCertainProbability() { assertEquals(0, distro.sample(1, random)); }
int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void sampleWithNonCertainProbability() { when(random.nextDouble()).thenReturn(0.88); assertEquals(10, distro.sample(0.2, random)); }
int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { int sample(double p, SourceOfRandomness random) { ensureProbability(p); if (p == 1) return 0; double uniform = random.nextDouble(); return (int) ceil(log(1 - uniform) / log(1 - p)); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void negativeMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(-ulp(0)); }
double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void zeroMeanProbability() { thrown.expect(IllegalArgumentException.class); distro.probabilityOfMean(0); }
double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void nonZeroMeanProbability() { assertEquals(1 / 6D, distro.probabilityOfMean(6), 0); }
double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { double probabilityOfMean(double mean) { if (mean <= 0) throw new IllegalArgumentException("Need a positive mean, got " + mean); return 1 / mean; } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void sampleWithMean() { when(random.nextDouble()).thenReturn(0.76); assertEquals(8, distro.sampleWithMean(6, random)); }
public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); }
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } }
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } }
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); }
GeometricDistribution { public int sampleWithMean(double mean, SourceOfRandomness random) { return sample(probabilityOfMean(mean), random); } int sampleWithMean(double mean, SourceOfRandomness random); }
@Test public void findingConstructorQuietly() { Constructor<Integer> ctor = findConstructor(Integer.class, int.class); assertEquals(int.class, ctor.getParameterTypes()[0]); }
public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingConstructorQuietlyWhenNoSuchConstructor() { thrown.expect(ReflectionException.class); thrown.expectMessage(NoSuchMethodException.class.getName()); assertNull(findConstructor(Integer.class, Object.class)); }
public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes) { try { return type.getConstructor(parameterTypes); } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
@Test public void findingDeclaredConstructorQuietly() { Constructor<Integer> ctor = findDeclaredConstructor(Integer.class, int.class); assertEquals(int.class, ctor.getParameterTypes()[0]); }
public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }
Reflection { public static <T> Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes) { try { Constructor<T> ctor = type.getDeclaredConstructor(parameterTypes); ctor.setAccessible(true); return ctor; } catch (Exception ex) { throw reflectionException(ex); } } private Reflection(); static Class<?> maybeWrap(Class<?> clazz); static Constructor<T> findConstructor( Class<T> type, Class<?>... parameterTypes); static Constructor<T> findDeclaredConstructor( Class<T> type, Class<?>... parameterTypes); @SuppressWarnings("unchecked") static Constructor<T> singleAccessibleConstructor( Class<T> type); static T instantiate(Class<T> clazz); static T instantiate(Constructor<T> ctor, Object... args); static Set<Type<?>> supertypes(Type<?> bottom); static Object defaultValueOf( Class<? extends Annotation> annotationType, String attribute); static List<Annotation> allAnnotations(AnnotatedElement e); static List<T> allAnnotationsByType( AnnotatedElement e, Class<T> type); static Method findMethod( Class<?> target, String methodName, Class<?>... argTypes); static Object invoke(Method method, Object target, Object... args); static Field findField(Class<?> type, String fieldName); static List<Field> allDeclaredFieldsOf(Class<?> type); static void setField( Field field, Object target, Object value, boolean suppressProtection); static boolean jdk9OrBetter(); static Method singleAbstractMethodOf(Class<?> rawClass); static boolean isMarkerInterface(Class<?> clazz); static RuntimeException reflectionException(Exception ex); static List<AnnotatedType> annotatedComponentTypes( AnnotatedType annotatedType); }