private Map<String, AttributeValueUpdate> createAttributes(Entry entry) { Map<String, AttributeValueUpdate> attributes = new HashMap<>(); attributes.put(SCHEMA_VERSION_FIELD_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue().withN(SCHEMA_VERSION))); attributes.put(OPTIMISTIC_LOCK_FIELD_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue().withS(sha(entry)))); for (Map.Entry<Integer, String> e : attributeMappings.entrySet()) { Object value = getValue(entry, e.getValue()); if (value != null) { attributes.put(e.getKey().toString(), new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(getAttribute(value))); } } return attributes; }
@Test public void createsOnlyThreeOpenLogs() throws Exception { final User user = new DyUser(new Dynamo(), "yegor256"); final Script script = user.script("test5"); final AttributeValueUpdate upd = new AttributeValueUpdate().withValue( new AttributeValue().withN( Long.toString(System.currentTimeMillis()) ) ).withAction(AttributeAction.PUT); // @checkstyle MagicNumber (1 line) for (int idx = 0; idx < 3; ++idx) { final Item item = script.open().iterator().next(); item.put("finish", upd); } MatcherAssert.assertThat( script.open(), Matchers.emptyIterable() ); }
public static void updateItem(AmazonDynamoDBClient client, String tableName, String id, String val) { java.util.Map<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put("Id", new AttributeValue().withN(id)); Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>(); AttributeValueUpdate update = new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue().withS(val)); attributeUpdates.put("attribute-2", update); UpdateItemRequest updateItemRequest = new UpdateItemRequest() .withTableName(tableName) .withKey(key) .withAttributeUpdates(attributeUpdates); client.updateItem(updateItemRequest); }
/** * Do nothing to an attribute if update value for it is null. */ public Map<String, AttributeValueUpdate> genUpdateItemsWithEmptyAttributeKept(String GSIHashKeyName, AttributeValue GSIHashKeyUpdateValue, String GSIRangeKeyName, AttributeValue GSIRangeKeyUpdateValue) { Map<String, AttributeValueUpdate> updateItems = new HashMap<String, AttributeValueUpdate>(); boolean updateFound = false; if (GSIHashKeyName != null && GSIHashKeyUpdateValue != null) { updateItems.put(GSIHashKeyName, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(GSIHashKeyUpdateValue)); updateFound = true; } if (GSIRangeKeyName != null && GSIRangeKeyUpdateValue != null) { updateItems.put(GSIRangeKeyName, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(GSIRangeKeyUpdateValue)); updateFound = true; } if(updateFound) { violationUpdateRequests++; } return updateItems; }
@Test public void test_updateItem_WithAllParameters() throws Exception { createTable(); putItem(TEST_ATTRIBUTE, TEST_ATTRIBUTE_VALUE); String UPDATE_ATTRIBUTE_VALUE = "UpdateAttributeValue1"; Map<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(TEST_ATTRIBUTE, new AttributeValue() .withS(TEST_ATTRIBUTE_VALUE)); Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<String, AttributeValueUpdate>(); attributeUpdates.put(TEST_ATTRIBUTE, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withS(UPDATE_ATTRIBUTE_VALUE))); String returnValues = ""; UpdateItemResult result = dynamoDb.updateItem(TEST_TABLE_NAME, key, attributeUpdates, returnValues); Double units = result.getConsumedCapacity().getCapacityUnits(); GetItemResult getItemResult = getItem(TEST_ATTRIBUTE, UPDATE_ATTRIBUTE_VALUE); String updatedValue = getItemResult.getItem().get(TEST_ATTRIBUTE).getS(); assertThat(units.doubleValue(), equalTo(1.0)); assertThat(updatedValue, equalTo(UPDATE_ATTRIBUTE_VALUE)); }
/** * Move or rename entity to other folder * * @param entity * - current entity want to move or rename * @param newParent * - parent of entity * @param newEntityName * - new name of entity * @param isRenamingAction * - TRUE is renaming file, otherwise FALSE * @return TRUE/FALSE */ @Override public boolean updateEntityByUniqueId(String tableName, Entity entity, Folder newParent, String newEntityName, boolean isRenamingAction) { HashMap<String, AttributeValue> primaryKey = new HashMap<String, AttributeValue>(); primaryKey.put(AttributeKey.UUID, new AttributeValue().withS(entity.getId().toString())); Map<String, AttributeValueUpdate> updateItems = new HashMap<String, AttributeValueUpdate>(); updateItems.put(AttributeKey.ENTITY_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT).withValue(new AttributeValue().withS(newEntityName))); updateItems.put(AttributeKey.MODIFIED_DATE, new AttributeValueUpdate() .withAction(AttributeAction.PUT).withValue(new AttributeValue().withS(DateUtils.dateToString(new Date())))); if (!isRenamingAction) { updateItems.put(AttributeKey.PARENT_UUID, new AttributeValueUpdate() .withAction(AttributeAction.PUT).withValue(new AttributeValue() .withS(newParent.getId().toString()))); } UpdateItemResult updateStatus = dynamoDBService.updateItem(tableName, primaryKey, updateItems); if (updateStatus != null) { return true; } return false; }
private void updateRow(String key, String appid, Map<String, AttributeValue> row) { if (StringUtils.isBlank(key) || StringUtils.isBlank(appid) || row == null || row.isEmpty()) { return; } Map<String, AttributeValueUpdate> rou = new HashMap<>(); try { for (Entry<String, AttributeValue> attr : row.entrySet()) { rou.put(attr.getKey(), new AttributeValueUpdate(attr.getValue(), AttributeAction.PUT)); } UpdateItemRequest updateItemRequest = new UpdateItemRequest(getTableNameForAppid(appid), Collections.singletonMap(Config._KEY, new AttributeValue(getKeyForAppid(key, appid))), rou); client().updateItem(updateItemRequest); } catch (Exception e) { logger.error("Could not update row in DB - appid={}, key={}", appid, key, e); } }
/** * MkRegion can store and read items. * @throws Exception If some problem inside */ @Test public void storesAndReadsSingleAttribute() throws Exception { final String table = "ideas"; final String key = "number"; final String attr = "total"; final Region region = new MkRegion( new H2Data().with(table, new String[] {key}, attr) ); final Table tbl = region.table(table); tbl.put( new Attributes() .with(key, "32443") .with(attr, "0") ); final Item item = tbl.frame().iterator().next(); item.put( attr, new AttributeValueUpdate().withValue( new AttributeValue().withN("2") ).withAction(AttributeAction.PUT) ); MatcherAssert.assertThat(item.get(attr).getN(), Matchers.equalTo("2")); }
@Override public void update(final String bash) throws IOException { this.item().put( "bash", new AttributeValueUpdate() .withValue(new AttributeValue().withS(bash)) .withAction(AttributeAction.PUT) ); }
@Override public void flush() throws IOException { this.item().put( "hour", new AttributeValueUpdate().withValue( new AttributeValue().withN("0") ).withAction(AttributeAction.PUT) ); }
@Override public void track(final long seconds) throws IOException { if (seconds > TimeUnit.MINUTES.toSeconds(2L)) { final Item item = this.item(); item.put( "used", new AttributeValueUpdate().withValue( new AttributeValue().withN(Long.toString(seconds)) ).withAction(AttributeAction.ADD) ); if (this.overdue() && item.has("stripe_customer")) { this.rebill(); } } }
@Override public void pay(final long cents, final String token, final String email) throws IOException { final String customer; try { customer = Customer.create( new StickyMap<String, Object>( new MapEntry<>("email", email), new MapEntry<>("source", token) ), new RequestOptions.RequestOptionsBuilder().setApiKey( Manifests.read("ThreeCopies-StripeSecret") ).build() ).getId(); } catch (final APIException | APIConnectionException | AuthenticationException | CardException | InvalidRequestException ex) { throw new IOException(ex); } this.item().put( new AttributeUpdates() .with( "stripe_cents", new AttributeValueUpdate().withValue( new AttributeValue().withN(Long.toString(cents)) ).withAction(AttributeAction.PUT) ) .with( "stripe_customer", new AttributeValueUpdate().withValue( new AttributeValue().withS(customer) ).withAction(AttributeAction.PUT) ) ); this.rebill(); }
/** * Charge him again. * @throws IOException If fails */ private void rebill() throws IOException { final Item item = this.item(); final Long cents = Long.parseLong(item.get("stripe_cents").getN()); final String customer = item.get("stripe_customer").getS(); try { Charge.create( new StickyMap<String, Object>( new MapEntry<>("amount", cents), new MapEntry<>("currency", "usd"), new MapEntry<>( "description", String.format("ThreeCopies: %s", this.name) ), new MapEntry<>("customer", customer) ), new RequestOptions.RequestOptionsBuilder().setApiKey( Manifests.read("ThreeCopies-StripeSecret") ).build() ); } catch (final APIException | APIConnectionException | AuthenticationException | CardException | InvalidRequestException ex) { throw new IOException(ex); } this.item().put( "paid", new AttributeValueUpdate().withValue( new AttributeValue().withN( Long.toString(cents * TimeUnit.HOURS.toSeconds(1L)) ) ).withAction(AttributeAction.ADD) ); }
/** * Make an update. * @param action The action * @return The update */ public AttributeValueUpdate update(final AttributeAction action) { return new AttributeValueUpdate() .withAction(action) .withValue( new AttributeValue().withN( Long.toString(this.longValue()) ) ); }
/** * Save XML. * @param xml The XML to save * @throws IOException If fails */ private void save(final String xml) throws IOException { this.item.put( "usage", new AttributeValueUpdate() .withValue(new AttributeValue().withS(xml)) .withAction(AttributeAction.PUT) ); }
/** * Save total. * @param total Total usage * @throws IOException If fails */ private void save(final long total) throws IOException { this.item.put( "total", new AttributeValueUpdate() .withValue(new AttributeValue().withN(Long.toString(total))) .withAction(AttributeAction.PUT) ); }
@Override public void status(final String text) throws IOException { this.item.put( "status", new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue().withS(text)) ); }
@Override public void vote(final int points) throws IOException { this.item.put( "rank", new AttributeValueUpdate() .withAction(AttributeAction.ADD) .withValue(new AttributeValue().withN(Integer.toString(points))) ); }
@Test public void execute() { Map<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put("1", new AttributeValue("Key_1")); exchange.getIn().setHeader(DdbConstants.KEY, key); Map<String, AttributeValueUpdate> attributeMap = new HashMap<String, AttributeValueUpdate>(); AttributeValueUpdate attributeValue = new AttributeValueUpdate( new AttributeValue("new value"), AttributeAction.ADD); attributeMap.put("name", attributeValue); exchange.getIn().setHeader(DdbConstants.UPDATE_VALUES, attributeMap); Map<String, ExpectedAttributeValue> expectedAttributeValueMap = new HashMap<String, ExpectedAttributeValue>(); expectedAttributeValueMap .put("name", new ExpectedAttributeValue(new AttributeValue("expected value"))); exchange.getIn().setHeader(DdbConstants.UPDATE_CONDITION, expectedAttributeValueMap); exchange.getIn().setHeader(DdbConstants.RETURN_VALUES, "ALL_OLD"); command.execute(); assertEquals("DOMAIN1", ddbClient.updateItemRequest.getTableName()); assertEquals(attributeMap, ddbClient.updateItemRequest.getAttributeUpdates()); assertEquals(key, ddbClient.updateItemRequest.getKey()); assertEquals(expectedAttributeValueMap, ddbClient.updateItemRequest.getExpected()); assertEquals("ALL_OLD", ddbClient.updateItemRequest.getReturnValues()); assertEquals(new AttributeValue("attrValue"), exchange.getIn().getHeader(DdbConstants.ATTRIBUTES, Map.class).get( "attrName")); }
public SingleUpdateBuilder put(final StaticBuffer column, final StaticBuffer value) { updates.put(encodeKeyBuffer(column), new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(encodeValue(value))); return this; }
/** * Delete the attribute if update value for it is null. */ public Map<String, AttributeValueUpdate> genUpdateItemsWithEmptyAttributeDeleted(String GSIHashKeyName, AttributeValue GSIHashKeyUpdateValue, String GSIRangeKeyName, AttributeValue GSIRangeKeyUpdateValue) { Map<String, AttributeValueUpdate> updateItems = new HashMap<String, AttributeValueUpdate>(); boolean updateFound = false; if (GSIHashKeyName != null) { if (GSIHashKeyUpdateValue == null) { updateItems.put(GSIHashKeyName, new AttributeValueUpdate().withAction(AttributeAction.DELETE)); updateFound = true; } else { updateItems.put(GSIHashKeyName, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(GSIHashKeyUpdateValue)); updateFound = true; } } if (GSIRangeKeyName != null) { if (GSIRangeKeyUpdateValue == null) { updateItems.put(GSIRangeKeyName, new AttributeValueUpdate().withAction(AttributeAction.DELETE)); updateFound = true; } else { updateItems.put(GSIRangeKeyName, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(GSIRangeKeyUpdateValue)); updateFound = true; } } if(updateFound) { violationUpdateRequests++; } return updateItems; }
/** * Update the Inventory table with the state of an Aggregator. * * @param streamName The Kinesis Stream being aggregated. * @param applicationName The application name running the aggregator. * @param workerId The worker ID which encapsulates an instance of an * Aggregator. * @param lastLowSeq The lowest sequence number observed in all records * which were flushed prior to this update. * @param lastHighSeq The highest sequence number for all records flushed in * this update. * @param lastWriteTime The write time of the data to Dynamo DB. * @param status The {@link STATE} of the Aggregator. * @throws Exception */ public void update(final String streamName, final String applicationName, final String namespace, final String shardId, final String lastLowSeq, final String lastHighSeq, final long lastWriteTime, final STATE status) throws Exception { // create the last write time value final String lastUpdateDateLabel = StreamAggregator.dateFormatter.format(new Date( lastWriteTime)); // generate the item update Map<String, AttributeValueUpdate> inventoryUpdate = new HashMap<String, AttributeValueUpdate>() { { put(InventoryModel.LAST_WRITE_TIME, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue( new AttributeValue().withS(lastUpdateDateLabel))); if (lastLowSeq != null) put(InventoryModel.LAST_LOW_SEQ, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue( new AttributeValue().withS(lastLowSeq))); if (lastHighSeq != null) put(InventoryModel.LAST_HIGH_SEQ, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue( new AttributeValue().withS(lastHighSeq))); if (status != null) put(InventoryModel.STATUS, new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue( new AttributeValue().withS(status.name()))); } }; DynamoUtils.updateWithRetries( dynamoClient, new UpdateItemRequest().withTableName(InventoryModel.TABLE_NAME).withKey( getKey(streamName, applicationName, namespace, shardId)).withAttributeUpdates( inventoryUpdate)); }
private void updateRowColumnUpdates(String storeName, Map<String, AttributeValue> key, List<DColumn> colList) { Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<>(); for (DColumn col : colList) { AttributeValue attrValue = mapColumnValue(storeName, col); attributeUpdates.put(col.getName(), new AttributeValueUpdate(attrValue, AttributeAction.PUT)); } m_service.updateRow(storeName, key, attributeUpdates); }
private void updateRowColumnDeletes(String storeName, Map<String, AttributeValue> key, List<String> colNames) { Map<String, AttributeValueUpdate> attributeUpdates = new HashMap<>(); for (String colName : colNames) { attributeUpdates.put(colName, new AttributeValueUpdate().withAction(AttributeAction.DELETE)); } m_service.updateRow(storeName, key, attributeUpdates); }
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { String refreshToken = null; if (token.getRefreshToken() != null) { refreshToken = token.getRefreshToken().getValue(); } // the JdbcTokenStore removes the existing token for this token_id [if it exists] // We'll avoid doing so for now, unless a compelling reason to do otherwise presents itself // if (readAccessToken(token.getValue()) != null) { // removeAccessToken(token.getValue()); // } Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>(); updates.put(schema.getAccessColumnToken(), new AttributeValueUpdate(new AttributeValue().withB(serializeAccessToken(token)), AttributeAction.PUT)); DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnAuthenticationId(), authenticationKeyGenerator.extractKey(authentication)); if (authentication.isClientOnly() || authentication.getName() == null || authentication.getName().length() == 0) { DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnUserName(), schema.getAccessNullUserToken()); updates.put(schema.getAccessColumnIsNullUser(), new AttributeValueUpdate(new AttributeValue().withN(schema.getAccessIsNullUserTrueToken()), AttributeAction.PUT)); } else { DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnUserName(), authentication.getName()); DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnIsNullUser(), null); } DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnClientId(), authentication.getOAuth2Request().getClientId()); updates.put(schema.getAccessColumnAuthentication(), new AttributeValueUpdate(new AttributeValue().withB(serializeAuthentication(authentication)), AttributeAction.PUT)); DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnRefreshToken(), extractTokenKey(refreshToken)); dynamoDBTemplate.update(schema.getAccessTableName(), // Collections.singletonMap(schema.getAccessColumnTokenId(), new AttributeValue(extractTokenKey(token.getValue()))), // updates); }
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) { Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>(); updates.put(schema.getRefreshColumnToken(), new AttributeValueUpdate(new AttributeValue().withB(serializeRefreshToken(refreshToken)), AttributeAction.PUT)); updates.put(schema.getRefreshColumnAuthentication(), new AttributeValueUpdate(new AttributeValue().withB(serializeAuthentication(authentication)), AttributeAction.PUT)); dynamoDBTemplate.update(schema.getRefreshTableName(), // Collections.singletonMap(schema.getRefreshColumnTokenId(), new AttributeValue(extractTokenKey(refreshToken.getValue()))), // updates); }
public static void nullSafeUpdateS(Map<String, AttributeValueUpdate> updates, String column, String value) { if (value == null || value.length() == 0) { updates.put(column, new AttributeValueUpdate().withAction(AttributeAction.DELETE)); } else { updates.put(column, new AttributeValueUpdate(new AttributeValue(value), AttributeAction.PUT)); } }
/** * With this attribute. * @param name Attribute name * @param value The value * @return AttributeUpdates * @since 0.14.3 */ public AttributeUpdates with(final String name, final AttributeValue value) { return this.with( name, new AttributeValueUpdate(value, AttributeAction.PUT) ); }
/** * AttributesUpdates can tell if it contains a value. */ @Test public void containsValue() { final String value = "attrv"; final AttributeUpdates attr = new AttributeUpdates() .with("attrkey", value).with("otherkey", "othervalue"); MatcherAssert.assertThat( attr.containsValue( new AttributeValueUpdate( new AttributeValue(value), AttributeAction.PUT ) ), Matchers.is(Boolean.TRUE) ); }
private void updatePoint(JSONObject requestObject, PrintWriter out) throws IOException, JSONException { GeoPoint geoPoint = new GeoPoint(requestObject.getDouble("lat"), requestObject.getDouble("lng")); AttributeValue rangeKeyAttributeValue = new AttributeValue().withS(requestObject.getString("rangeKey")); String schoolName = requestObject.getString("schoolName"); AttributeValueUpdate schoolNameValueUpdate = null; String memo = requestObject.getString("memo"); AttributeValueUpdate memoValueUpdate = null; if (schoolName == null || schoolName.equalsIgnoreCase("")) { schoolNameValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.DELETE); } else { AttributeValue schoolNameAttributeValue = new AttributeValue().withS(schoolName); schoolNameValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue( schoolNameAttributeValue); } if (memo == null || memo.equalsIgnoreCase("")) { memoValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.DELETE); } else { AttributeValue memoAttributeValue = new AttributeValue().withS(memo); memoValueUpdate = new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(memoAttributeValue); } UpdatePointRequest updatePointRequest = new UpdatePointRequest(geoPoint, rangeKeyAttributeValue); updatePointRequest.getUpdateItemRequest().addAttributeUpdatesEntry("schoolName", schoolNameValueUpdate); updatePointRequest.getUpdateItemRequest().addAttributeUpdatesEntry("memo", memoValueUpdate); UpdatePointResult updatePointResult = geoDataManager.updatePoint(updatePointRequest); printUpdatePointResult(updatePointResult, out); }
private UpdateItemRequest constructUpdateItemRequest(RawSecretEntry rawSecretEntry, boolean expectExists, Optional<RawSecretEntry> expectedRawSecretEntry) { // Create item key. Map<String, AttributeValue> key = new HashMap<>(); key.put(KEY_ATTRIBUTE_NAME.toString(), new AttributeValue().withS(rawSecretEntry.secretIdentifier.name)); key.put(VERSION_ATTRIBUTE_NAME.toString(), new AttributeValue().withN(String.valueOf(rawSecretEntry.version))); // Create item attributes. Map<String, AttributeValueUpdate> attributes = new HashMap<>(); attributes.put(SCHEMA_VERSION_FIELD_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withN(SCHEMA_VERSION))); attributes.put(NOT_BEFORE_ATTRIBUTE_NAME.toString(), new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withN(FormattedTimestamp.epoch(rawSecretEntry.notBefore.get()).toString()))); attributes.put(STATE_ATTRIBUTE_NAME.toString(), new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withN(Byte.toString(rawSecretEntry.state.asByte())))); attributes.put(VALUE_ATTRIBUTE_NAME.toString(), new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withS(Encoder.base64encode(rawSecretEntry.encryptedPayload)))); attributes.put(OPTIMISTIC_LOCKING_ATTRIBUTE_NAME, new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue(new AttributeValue() .withS(Encoder.base64encode(rawSecretEntry.sha1OfEncryptionPayload())))); // Create the expected conditions map. Map<String, ExpectedAttributeValue> expected = new HashMap<>(); if (expectExists) { expected.put(KEY_ATTRIBUTE_NAME.toString(), new ExpectedAttributeValue(true).withValue( new AttributeValue(rawSecretEntry.secretIdentifier.name))); expected.put(OPTIMISTIC_LOCKING_ATTRIBUTE_NAME, new ExpectedAttributeValue(true).withValue( new AttributeValue(Encoder.sha1(expectedRawSecretEntry.get().encryptedPayload)))); } else { expected.put(KEY_ATTRIBUTE_NAME.toString(), new ExpectedAttributeValue(false)); } return new UpdateItemRequest(tableName, key, attributes).withExpected(expected); }
/** * The date/time is expired? * @param item The item * @param period Either hour, day or week * @return Collection of items or empty * @throws IOException If fails */ private Collection<Item> required(final Item item, final String period) throws IOException { final Collection<Item> created = new LinkedList<>(); if (!item.has(period) || DyScript.expired(item.get(period).getN(), period)) { final long start = System.currentTimeMillis(); item.put( new AttributeUpdates() .with( period, new AttributeValueUpdate().withValue( new AttributeValue().withN(Long.toString(start)) ).withAction(AttributeAction.PUT) ) ); created.add( this.region.table("logs").put( new Attributes() .with("group", new AttributeValue().withS(this.group())) .with( "start", new AttributeValue().withN(Long.toString(start)) ) .with("login", new AttributeValue().withS(this.login)) .with("period", new AttributeValue().withS(period)) .with("exit", new AttributeValue().withN("0")) .with( "finish", new AttributeValue().withN( Long.toString(Long.MAX_VALUE) ) ) .with( "ttl", new AttributeValue().withN( Long.toString( // @checkstyle MagicNumber (2 lines) System.currentTimeMillis() / 1000L + TimeUnit.DAYS.toSeconds(14L) ) ) ) .with( "ocket", new AttributeValue().withS( String.format( "%s_%s-%s-%tF-%4$tH-%4$tM", this.login, this.name, period, new Date() ) ) ) ) ); } return created; }
/** * Start a Docker container. * @param script The script * @param log The log * @throws IOException If fails */ private void start(final Script script, final Item log) throws IOException { this.upload("start.sh"); final XML xml = new XMLDocument( new Xembler(script.toXembly()).xmlQuietly() ); final String login = xml.xpath("/script/login/text()").get(0); final String period = log.get("period").getS(); final String container = log.get("ocket").getS(); this.shell.exec( String.join( " && ", String.format("mkdir -p %s/%s", Routine.DIR, container), String.format("cat > %s/%s/script.sh", Routine.DIR, container) ), new InputOf( xml.xpath("/script/bash/text()").get(0).replace("\r\n", "\n") ).stream(), new DeadOutputStream(), new DeadOutputStream() ); this.shell.exec( String.format( "%s/start.sh %s %s &", Routine.DIR, container, period ), new DeadInputStream(), new DeadOutputStream(), new DeadOutputStream() ); log.put( new AttributeUpdates() .with( "container", new AttributeValueUpdate() .withValue(new AttributeValue().withS(container)) .withAction(AttributeAction.PUT) ) ); Logger.info(this, "Started %s for %s", container, login); }
/** * Finish already running Docker container. * @param script The script * @param log The log * @throws IOException If fails */ private void finish(final Script script, final Item log) throws IOException { this.upload("finish.sh"); final String container = log.get("container").getS(); final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); this.shell.exec( String.join( " && ", String.format("cd %s", Routine.DIR), String.format("./finish.sh %s", container) ), new DeadInputStream(), stdout, new DeadOutputStream() ); final String[] parts = new String( stdout.toByteArray(), StandardCharsets.UTF_8 ).split("\n", 2); if (parts.length > 1) { new Ocket.Text( this.bucket.ocket(log.get("ocket").getS()) ).write(parts[1]); final int exit = Integer.parseInt(parts[0].trim()); log.put( new AttributeUpdates() .with( "finish", new AttributeValueUpdate().withValue( new AttributeValue().withN( Long.toString(System.currentTimeMillis()) ) ).withAction(AttributeAction.PUT) ) .with( "exit", new AttributeValueUpdate().withValue( new AttributeValue().withN(Integer.toString(exit)) ).withAction(AttributeAction.PUT) ) ); script.track( (System.currentTimeMillis() - Long.parseLong(log.get("start").getN())) / TimeUnit.SECONDS.toMillis(1L) ); Logger.info( this, "Finished %s with %s and %d log bytes", container, exit, parts[1].length() ); } }
/** * Add one metric. * @param metric XML with metric * @throws IOException If fails */ private void add(final XML metric) throws IOException { final Item item; final Iterator<Item> items = this.table.frame() .through( new QueryValve() .withLimit(1) .withSelect(Select.ALL_ATTRIBUTES) ) .where("metric", metric.xpath("@name").get(0)) .where("version", new Version().value()) .iterator(); if (items.hasNext()) { item = items.next(); } else { item = this.table.put( new Attributes() .with("metric", metric.xpath("@name").get(0)) .with("version", new Version().value()) .with("artifact", "?") .with("champions", 0L) // @checkstyle MagicNumber (2 lines) .with("mean", new DyNum(0.5d).longValue()) .with("sigma", new DyNum(0.1d).longValue()) ); } final double mean = Double.parseDouble( metric.xpath("mean/text()").get(0) ); final double sigma = Double.parseDouble( metric.xpath("sigma/text()").get(0) ); final boolean reverse = Boolean.parseBoolean( metric.xpath("reverse/text()").get(0) ); final double mbefore = new DyNum(item, "mean").doubleValue(); final double sbefore = new DyNum(item, "sigma").doubleValue(); // @checkstyle BooleanExpressionComplexityCheck (1 line) if (sigma < sbefore || mean < mbefore && reverse || mean > mbefore && !reverse) { item.put( new AttributeUpdates() .with("artifact", metric.xpath("/index/@artifact").get(0)) .with( "champions", new AttributeValueUpdate() .withValue(new AttributeValue().withN("1")) .withAction(AttributeAction.ADD) ) .with("mean", new DyNum(mean).update()) .with("sigma", new DyNum(sigma).update()) ); } }
@Override public void post(final String title, final String text) throws IOException { final Iterator<Item> items = this.items(title); if (items.hasNext()) { final Item item = items.next(); item.put( new AttributeUpdates() .with( "rank", new AttributeValueUpdate() .withValue(new AttributeValue().withN("1")) .withAction(AttributeAction.ADD) ) .with( "text", new AttributeValueUpdate() .withAction(AttributeAction.PUT) .withValue( new AttributeValue().withS( DyEvents.concat( item.get("text").getS(), text ) ) ) ) ); Logger.info( this, "Event updated for %s: \"%s\"", this.urn, title ); } else { final int rank; if (title.startsWith("io.wring.agents.")) { rank = -Tv.THOUSAND; } else { rank = 1; } this.table().put( new Attributes() .with("urn", this.urn) .with("title", title) .with("text", text) .with("rank", rank) .with("time", System.currentTimeMillis()) ); Logger.info( this, "Event created for %s: \"%s\"", this.urn, title ); } }
public static AttributeValueUpdate attrValueUpdateOf(Object value, AttributeAction action) { return new AttributeValueUpdate(attrValueOf(value), action); }
private SingleUpdateBuilder delete(final StaticBuffer column) { updates.put(encodeKeyBuffer(column), new AttributeValueUpdate() .withAction(AttributeAction.DELETE)); return this; }
private DynamoSummaryUpdateMethod(AttributeAction a) { this.action = a; }