Example usage for org.apache.commons.lang3.tuple Pair getKey

List of usage examples for org.apache.commons.lang3.tuple Pair getKey

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getKey.

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:com.epam.ngb.cli.manager.command.handler.http.FileRegistrationHandler.java

private RegistrationRequest createRegistrationRequest(Pair<String, String> file,
        BiologicalDataItemFormat format) {
    RegistrationRequest registration = new RegistrationRequest();
    registration.setName(fileName);//from   w w  w .  j a  va 2 s  . co  m
    registration.setPrettyName(prettyName);
    registration.setPath(file.getLeft());
    registration.setIndexPath(file.getRight());
    registration.setReferenceId(referenceId);
    registration.setType(BiologicalDataItemResourceType.getTypeFromPath(file.getKey()));

    if (file.getValue() != null) {
        registration.setIndexType(BiologicalDataItemResourceType.getTypeFromPath(file.getValue()));
    }

    if (format == BiologicalDataItemFormat.VCF || format == BiologicalDataItemFormat.GENE) {
        registration.setDoIndex(doIndex);
    }
    return registration;
}

From source file:com.microsoft.azure.storage.table.TableEncryptionPolicy.java

/**
 * Return an encrypted entity. This method is used for encrypting entity properties.
 *//*ww  w  .  jav  a 2s. c  o  m*/
Map<String, EntityProperty> encryptEntity(Map<String, EntityProperty> properties, String partitionKey,
        String rowKey, EncryptionResolver encryptionResolver) throws StorageException {
    Utility.assertNotNull("properties", properties);

    // The Key should be set on the policy for encryption. Otherwise, throw an error.
    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        Map<String, EntityProperty> encryptedProperties = new HashMap<String, EntityProperty>();
        HashSet<String> encryptionPropertyDetailsSet = new HashSet<String>();

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptionData.setContentEncryptionIV(myAes.getIV());

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
            if (encryptionResolver != null
                    && encryptionResolver.encryptionResolver(partitionKey, rowKey, kvp.getKey())) {
                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case
                // where a user adds a new property as follows - ent.Properties.Add("foo2", null);
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                kvp.getValue().setIsEncrypted(true);
            }

            // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is 
            // specified in the encryption resolver or both.
            if (kvp.getValue() != null && kvp.getValue().isEncrypted()) {
                // Throw if users try to encrypt non-string properties.
                if (kvp.getValue().getEdmType() != EdmType.STRING) {
                    throw new IllegalArgumentException(String
                            .format(SR.UNSUPPORTED_PROPERTY_TYPE_FOR_ENCRYPTION, kvp.getValue().getEdmType()));
                }

                byte[] columnIVFull = digest
                        .digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                                (partitionKey + rowKey + kvp.getKey()).getBytes(Constants.UTF8_CHARSET)));

                byte[] columnIV = new byte[16];
                System.arraycopy(columnIVFull, 0, columnIV, 0, 16);
                myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(columnIV));

                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO
                // case when the property value is null.
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                byte[] src = kvp.getValue().getValueAsString().getBytes(Constants.UTF8_CHARSET);
                byte[] dest = myAes.doFinal(src, 0, src.length);

                // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of 
                // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly 
                // even when the service does not return the type for JSON no-metadata.
                encryptedProperties.put(kvp.getKey(), new EntityProperty(dest));
                encryptionPropertyDetailsSet.add(kvp.getKey());
            } else {
                encryptedProperties.put(kvp.getKey(), kvp.getValue());
            }

            // Encrypt the property details set and add it to entity properties.
            byte[] metadataIVFull = digest.digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                    (partitionKey + rowKey + Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS)
                            .getBytes(Constants.UTF8_CHARSET)));

            byte[] metadataIV = new byte[16];
            System.arraycopy(metadataIVFull, 0, metadataIV, 0, 16);
            myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(metadataIV));

            byte[] src = Arrays.toString(encryptionPropertyDetailsSet.toArray())
                    .getBytes(Constants.UTF8_CHARSET);
            byte[] dest = myAes.doFinal(src, 0, src.length);
            encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS,
                    new EntityProperty(dest));
        }

        encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS,
                new EntityProperty(encryptionData.serialize()));

        return encryptedProperties;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testNoPublicCategoryAvailable() {
    LocalDateTime start = LocalDateTime.now().minusHours(1);
    LocalDateTime end = LocalDateTime.now().plusHours(1);

    List<TicketCategoryModification> categories = Arrays.asList(
            new TicketCategoryModification(null, "default", 2,
                    new DateTimeModification(start.toLocalDate(), start.toLocalTime()),
                    new DateTimeModification(end.toLocalDate(), end.toLocalTime()), DESCRIPTION, BigDecimal.TEN,
                    false, "", true, null, null, null, null, null),
            new TicketCategoryModification(null, "default2", 10,
                    new DateTimeModification(start.toLocalDate(), start.toLocalTime()),
                    new DateTimeModification(end.toLocalDate(), end.toLocalTime()), DESCRIPTION, BigDecimal.TEN,
                    true, "", true, null, null, null, null, null));

    configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_WAITING_QUEUE, "true");
    Pair<Event, String> eventAndUsername = initEvent(categories, organizationRepository, userManager,
            eventManager, eventRepository);
    Event event = eventAndUsername.getKey();
    List<TicketCategory> ticketCategories = ticketCategoryRepository.findByEventId(event.getId());
    TicketCategory first = ticketCategories.stream().filter(tc -> !tc.isAccessRestricted()).findFirst()
            .orElseThrow(IllegalStateException::new);
    reserveTickets(event, first, 2);//from   ww w. ja v a2  s .c o m
    assertTrue(
            waitingQueueManager.subscribe(event, customerJohnDoe(event), "john@doe.com", null, Locale.ENGLISH));
    assertTrue(waitingQueueManager.subscribe(event, new CustomerName("John Doe 2", "John", "Doe 2", event),
            "john@doe2.com", null, Locale.ENGLISH));

    ZoneId zoneId = event.getZoneId();
    Result<TicketCategory> ticketCategoryResult = eventManager.updateCategory(first.getId(), event,
            new TicketCategoryModification(first.getId(), first.getName(), 3,
                    fromZonedDateTime(first.getInception(zoneId)),
                    fromZonedDateTime(first.getExpiration(zoneId)), Collections.emptyMap(), first.getPrice(),
                    false, "", true, null, null, null, null, null),
            eventAndUsername.getValue());
    assertTrue(ticketCategoryResult.isSuccess());
    assertEquals(1, ticketRepository.countReleasedTicketInCategory(event.getId(), first.getId()).intValue());
    //now we should have an extra available ticket
    List<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> subscriptions = waitingQueueManager
            .distributeSeats(event).collect(Collectors.toList());
    assertEquals(1, subscriptions.size());
}

From source file:eu.openminted.registry.service.generate.WorkflowOutputMetadataGenerate.java

protected PersonInfo generatePersonInfo(String userId, boolean addOMTDPersonId)
        throws JsonParseException, JsonMappingException, IOException {
    PersonInfo personInfo = new PersonInfo();

    // Retrieve user information from aai service
    int coId = aaiUserInfoRetriever.getCoId(userId);
    Pair<String, String> userNames = aaiUserInfoRetriever.getSurnameGivenName(coId);
    String surname = userNames.getKey();
    String givenName = userNames.getValue();
    String email = aaiUserInfoRetriever.getEmail(coId);

    // User's name
    personInfo.setSurname(surname);//from ww w. j av  a2 s  . c  o m
    personInfo.setGivenName(givenName);

    if (addOMTDPersonId) {
        // Identifiers
        List<PersonIdentifier> personIdentifiers = new ArrayList<>();
        PersonIdentifier personID = new PersonIdentifier();
        personID.setValue(userId);
        personID.setPersonIdentifierSchemeName(PersonIdentifierSchemeNameEnum.OTHER);
        personIdentifiers.add(personID);
        personInfo.setPersonIdentifiers(personIdentifiers);
    }

    // User's communication info
    CommunicationInfo communicationInfo = new CommunicationInfo();
    List<String> emails = new ArrayList<>();
    emails.add(email);
    communicationInfo.setEmails(emails);
    personInfo.setCommunicationInfo(communicationInfo);
    logger.info("Person info as retrieved from aai :: " + mapper.writeValueAsString(personInfo));
    return personInfo;

}

From source file:com.spotify.heroic.metric.bigtable.BigtableBackend.java

private <T extends Metric> AsyncFuture<WriteMetric> writeBatch(final String columnFamily, final Series series,
        final BigtableDataClient client, final List<T> batch, final Function<T, ByteString> serializer)
        throws IOException {
    // common case for consumers
    if (batch.size() == 1) {
        return writeOne(columnFamily, series, client, batch.get(0), serializer).onFinished(written::mark);
    }/*from w  ww .j  av  a  2s.co m*/

    final List<Pair<RowKey, Mutations>> saved = new ArrayList<>();
    final Map<RowKey, Mutations.Builder> building = new HashMap<>();

    for (final T d : batch) {
        final long timestamp = d.getTimestamp();
        final long base = base(timestamp);
        final long offset = offset(timestamp);

        final RowKey rowKey = new RowKey(series, base);

        Mutations.Builder builder = building.get(rowKey);

        final ByteString offsetBytes = serializeOffset(offset);
        final ByteString valueBytes = serializer.apply(d);

        if (builder == null) {
            builder = Mutations.builder();
            building.put(rowKey, builder);
        }

        builder.setCell(columnFamily, offsetBytes, valueBytes);

        if (builder.size() >= MAX_BATCH_SIZE) {
            saved.add(Pair.of(rowKey, builder.build()));
            building.put(rowKey, Mutations.builder());
        }
    }

    final ImmutableList.Builder<AsyncFuture<WriteMetric>> writes = ImmutableList.builder();

    final RequestTimer<WriteMetric> timer = WriteMetric.timer();

    for (final Pair<RowKey, Mutations> e : saved) {
        final ByteString rowKeyBytes = serialize(e.getKey(), rowKeySerializer);
        writes.add(client.mutateRow(table, rowKeyBytes, e.getValue()).directTransform(result -> timer.end()));
    }

    for (final Map.Entry<RowKey, Mutations.Builder> e : building.entrySet()) {
        final ByteString rowKeyBytes = serialize(e.getKey(), rowKeySerializer);
        writes.add(client.mutateRow(table, rowKeyBytes, e.getValue().build())
                .directTransform(result -> timer.end()));
    }

    return async.collect(writes.build(), WriteMetric.reduce());
}

From source file:com.astamuse.asta4d.web.test.dispatch.RequestDispatcherTest.java

@Test(dataProvider = "data")
public void execute(String method, String url, int status, ContentProvider contentProvider) throws Exception {
    WebApplicationContext context = (WebApplicationContext) Context.getCurrentThreadContext();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    HttpSession session = mock(HttpSession.class);

    when(request.getParameterNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getCookies()).thenReturn(new Cookie[0]);
    when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getSession(true)).thenReturn(session);

    when(request.getRequestURI()).thenReturn(url);
    when(request.getContextPath()).thenReturn("");
    when(request.getMethod()).thenReturn(method);

    final ByteArrayOutputStream responseBos = new ByteArrayOutputStream();
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override/*from w w  w .j a v  a2 s. c  o m*/
        public void write(int b) throws IOException {
            responseBos.write(b);
        }
    });

    HandyRuleSet ruleSet = new HandyRuleSet();
    initTestRules(ruleSet);

    if (url.equals("/index-rewrite")) {
        context.setAccessURI("/index");
    }

    dispatcher.dispatchAndProcess(ruleSet.getArrangedRuleList());

    // verify status at first then when contentProvider is null, we do not
    // need to do more verification
    if (status != 0) {
        verify(response).setStatus(status);
    }

    if (contentProvider == null) {
        return;
    }

    // prepare expected results
    HttpServletResponse expectedResponse = mock(HttpServletResponse.class);

    final ByteArrayOutputStream expectedBos = new ByteArrayOutputStream();
    when(expectedResponse.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            expectedBos.write(b);
        }
    });

    final List<Pair<String, String>> expectedHeaderList = new LinkedList<>();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            expectedHeaderList.add(Pair.of((String) args[0], (String) args[1]));
            return null;
        }
    }).when(expectedResponse).addHeader(anyString(), anyString());

    UrlMappingRule currentRule = context.getCurrentRule();
    contentProvider.produce(currentRule, expectedResponse);

    // verify extra contents like headers and output stream

    for (Pair<String, String> pair : expectedHeaderList) {
        verify(response).addHeader(pair.getKey(), pair.getValue());
    }

    Assert.assertEquals(new String(responseBos.toByteArray()), new String(expectedBos.toByteArray()));

}

From source file:com.bluepowermod.part.tube.TubeLogic.java

public boolean injectStack(TubeStack stack, ForgeDirection from, boolean simulate) {

    if (tube.getWorld() != null && tube.getWorld().isRemote)
        throw new IllegalArgumentException("[Pneumatic Tube] You can't inject items from the client side!");
    Pair<ForgeDirection, TileEntity> heading = getHeadingForItem(stack, simulate);
    if (heading != null && heading.getKey() != from.getOpposite()) {
        if (!simulate) {
            tubeStacks.add(stack);/*from www  . j  a  v  a 2  s. co m*/
            tube.sendUpdatePacket();
        }
        return true;
    } else {
        return false;
    }
}

From source file:com.streamsets.pipeline.stage.processor.hbase.HBaseLookupProcessor.java

private void updateRecord(Record record, HBaseLookupParameterConfig parameter, Pair<String, HBaseColumn> key,
        Optional<String> value) throws JSONException {
    // If the value does not exists in HBase, no updates on record
    if (value == null || !value.isPresent()) {
        LOG.debug("No value found on Record '{}' with key:'{}', column:'{}', timestamp:'{}'", record,
                key.getKey(),
                Bytes.toString(key.getValue().getCf()) + ":" + Bytes.toString(key.getValue().getQualifier()),
                key.getValue().getTimestamp());
        return;//ww  w  .ja v a2 s  .  c  om
    }

    // if the Column Expression is empty, return the row data ( columnName + value )
    if (parameter.columnExpr.isEmpty()) {
        JSONObject json = new JSONObject(value.get());
        Iterator<String> iter = json.keys();
        Map<String, Field> columnMap = new HashMap<>();
        while (iter.hasNext()) {
            String columnName = iter.next();
            String columnValue = json.get(columnName).toString();
            columnMap.put(columnName, Field.create(columnValue));
        }
        record.set(parameter.outputFieldPath, Field.create(columnMap));
    } else {
        record.set(parameter.outputFieldPath, Field.create(value.get()));
    }
}

From source file:io.pravega.controller.store.stream.AbstractStreamMetadataStore.java

protected AbstractStreamMetadataStore(HostIndex hostIndex) {
    cache = CacheBuilder.newBuilder().maximumSize(10000).refreshAfterWrite(10, TimeUnit.MINUTES)
            .expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<Pair<String, String>, Stream>() {
                @Override/*w ww  .  ja  v a  2s  .c  o  m*/
                @ParametersAreNonnullByDefault
                public Stream load(Pair<String, String> input) {
                    try {
                        return newStream(input.getKey(), input.getValue());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

    scopeCache = CacheBuilder.newBuilder().maximumSize(1000).refreshAfterWrite(10, TimeUnit.MINUTES)
            .expireAfterWrite(10, TimeUnit.MINUTES).build(new CacheLoader<String, Scope>() {
                @Override
                @ParametersAreNonnullByDefault
                public Scope load(String scopeName) {
                    try {
                        return newScope(scopeName);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });

    this.hostIndex = hostIndex;
}

From source file:alfio.controller.ReservationFlowIntegrationTest.java

@Before
public void ensureConfiguration() {

    IntegrationTestUtil.ensureMinimalConfiguration(configurationRepository);
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
            new DateTimeModification(LocalDate.now().plusDays(1), LocalTime.now()), DESCRIPTION, BigDecimal.TEN,
            false, "", false, null, null, null, null, null));
    Pair<Event, String> eventAndUser = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//from  w w w .  j a va 2  s .  c  o  m

    event = eventAndUser.getKey();
    user = eventAndUser.getValue() + "_owner";

    //
    TemplateManager templateManager = Mockito.mock(TemplateManager.class);
    reservationApiController = new ReservationApiController(eventRepository, ticketHelper, templateManager,
            i18nManager, euVatChecker, ticketReservationRepository, ticketReservationManager);
}