Search in sources :

Example 6 with Table

use of com.amazonaws.services.dynamodbv2.document.Table in project openhab1-addons by openhab.

the class DynamoDBPersistenceService method store.

/**
     * {@inheritDoc}
     */
@Override
public void store(Item item, String alias) {
    if (item.getState() instanceof UnDefType) {
        logger.debug("Undefined item state received. Not storing item.");
        return;
    }
    if (!isProperlyConfigured) {
        logger.warn("Configuration for dynamodb not yet loaded or broken. Not storing item.");
        return;
    }
    if (!maybeConnectAndCheckConnection()) {
        logger.warn("DynamoDB not connected. Not storing item.");
        return;
    }
    String realName = item.getName();
    String name = (alias != null) ? alias : realName;
    Date time = new Date(System.currentTimeMillis());
    State state = item.getState();
    logger.trace("Tried to get item from item class {}, state is {}", item.getClass(), state.toString());
    DynamoDBItem<?> dynamoItem = AbstractDynamoDBItem.fromState(name, state, time);
    DynamoDBMapper mapper = getDBMapper(tableNameResolver.fromItem(dynamoItem));
    if (!createTable(mapper, dynamoItem.getClass())) {
        logger.warn("Table creation failed. Not storing item");
        return;
    }
    try {
        logger.debug("storing {} in dynamo. Serialized value {}. Original Item: {}", name, state, item);
        mapper.save(dynamoItem);
        logger.debug("Sucessfully stored item {}", item);
    } catch (AmazonClientException e) {
        logger.error("Error storing object to dynamo: {}", e.getMessage());
    }
}
Also used : UnDefType(org.openhab.core.types.UnDefType) State(org.openhab.core.types.State) AmazonClientException(com.amazonaws.AmazonClientException) DynamoDBMapper(com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper) Date(java.util.Date)

Example 7 with Table

use of com.amazonaws.services.dynamodbv2.document.Table in project gora by apache.

the class GoraDynamoDBCompiler method readMapping.

/**
   * Reads the schema file and converts it into a data structure to be used
   * @param pMapFile
   *          schema file to be mapped into a table
   * @return
   * @throws IOException
   */
@SuppressWarnings("unchecked")
private DynamoDBMapping readMapping(File pMapFile) throws IOException {
    DynamoDBMappingBuilder mappingBuilder = new DynamoDBMappingBuilder();
    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(pMapFile);
        if (doc == null || doc.getRootElement() == null)
            throw new GoraException("Unable to load " + MAPPING_FILE + ". Please check its existance!");
        Element root = doc.getRootElement();
        List<Element> tableElements = root.getChildren("table");
        boolean keys = false;
        for (Element tableElement : tableElements) {
            String tableName = tableElement.getAttributeValue("name");
            long readCapacUnits = Long.parseLong(tableElement.getAttributeValue("readcunit"));
            long writeCapacUnits = Long.parseLong(tableElement.getAttributeValue("writecunit"));
            this.packageName = tableElement.getAttributeValue("package");
            mappingBuilder.setProvisionedThroughput(tableName, readCapacUnits, writeCapacUnits);
            log.debug("Table properties have been set for name, package and provisioned throughput.");
            // Retrieving attributes
            List<Element> fieldElements = tableElement.getChildren("attribute");
            for (Element fieldElement : fieldElements) {
                String key = fieldElement.getAttributeValue("key");
                String attributeName = fieldElement.getAttributeValue("name");
                String attributeType = fieldElement.getAttributeValue("type");
                mappingBuilder.addAttribute(tableName, attributeName, attributeType);
                // Retrieving key's features
                if (key != null) {
                    mappingBuilder.setKeySchema(tableName, attributeName, key);
                    keys = true;
                }
            }
            log.debug("Attributes for table '{}' have been read.", tableName);
            if (!keys)
                log.warn("Keys for table '{}' have NOT been set.", tableName);
        }
    } catch (IOException ex) {
        log.error("Error while performing xml mapping.", ex.getMessage());
        throw new RuntimeException(ex);
    } catch (Exception ex) {
        log.error("An error occured whilst reading the xml mapping file!", ex.getMessage());
        throw new IOException(ex);
    }
    return mappingBuilder.build();
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) GoraException(org.apache.gora.util.GoraException) KeySchemaElement(com.amazonaws.services.dynamodbv2.model.KeySchemaElement) Element(org.jdom.Element) DynamoDBMappingBuilder(org.apache.gora.dynamodb.store.DynamoDBMapping.DynamoDBMappingBuilder) IOException(java.io.IOException) Document(org.jdom.Document) IOException(java.io.IOException) GoraException(org.apache.gora.util.GoraException)

Example 8 with Table

use of com.amazonaws.services.dynamodbv2.document.Table in project gora by apache.

the class DynamoDBStore method waitForTableToBeDeleted.

/**
   * Waits up to 6 minutes to confirm if a table has been deleted or not
   * 
   * @param pTableName
   */
private void waitForTableToBeDeleted(String pTableName) {
    LOG.debug("Waiting for " + pTableName + " to be deleted.");
    long startTime = System.currentTimeMillis();
    long endTime = startTime + WAIT_TIME;
    while (System.currentTimeMillis() < endTime) {
        try {
            Thread.sleep(SLEEP_DELETE_TIME);
        } catch (Exception e) {
        }
        try {
            DescribeTableRequest request = new DescribeTableRequest().withTableName(pTableName);
            TableDescription tableDescription = getDynamoDBClient().describeTable(request).getTable();
            String tableStatus = tableDescription.getTableStatus();
            LOG.debug(pTableName + " - current state: " + tableStatus);
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException") == true)
                return;
            LOG.error(ase.getMessage());
        }
    }
    LOG.debug(pTableName + " deleted.");
}
Also used : AmazonServiceException(com.amazonaws.AmazonServiceException) DescribeTableRequest(com.amazonaws.services.dynamodbv2.model.DescribeTableRequest) TableDescription(com.amazonaws.services.dynamodbv2.model.TableDescription) GoraException(org.apache.gora.util.GoraException) AmazonServiceException(com.amazonaws.AmazonServiceException) IOException(java.io.IOException) ResourceNotFoundException(com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException)

Example 9 with Table

use of com.amazonaws.services.dynamodbv2.document.Table in project gora by apache.

the class DynamoDBUtils method waitForTableToBecomeAvailable.

/**
   * Waits up to 6 minutes to confirm if a table has been created or not
   * 
   * @param awsClient
   * @param tableName
   */
public static void waitForTableToBecomeAvailable(AmazonDynamoDB awsClient, String tableName) {
    LOG.debug("Waiting for {} to become available", tableName);
    long startTime = System.currentTimeMillis();
    long endTime = startTime + WAIT_TIME;
    while (System.currentTimeMillis() < endTime) {
        try {
            Thread.sleep(SLEEP_TIME);
        } catch (Exception e) {
        }
        try {
            DescribeTableRequest request = new DescribeTableRequest().withTableName(tableName);
            TableDescription tableDescription = awsClient.describeTable(request).getTable();
            String tableStatus = tableDescription.getTableStatus();
            LOG.debug("{} - current state: {}", tableName, tableStatus);
            if (tableStatus.equals(TableStatus.ACTIVE.toString()))
                return;
        } catch (AmazonServiceException ase) {
            if (ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException") == false)
                throw ase;
        }
    }
    throw new RuntimeException("Table " + tableName + " never became active");
}
Also used : AmazonServiceException(com.amazonaws.AmazonServiceException) DescribeTableRequest(com.amazonaws.services.dynamodbv2.model.DescribeTableRequest) TableDescription(com.amazonaws.services.dynamodbv2.model.TableDescription) ResourceInUseException(com.amazonaws.services.dynamodbv2.model.ResourceInUseException) AmazonServiceException(com.amazonaws.AmazonServiceException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 10 with Table

use of com.amazonaws.services.dynamodbv2.document.Table in project gora by apache.

the class DynamoDBUtils method executeCreateTableRequest.

/**
   * Executes a create table request using the DynamoDB client and waits the
   * default time until it's been created.
   * 
   * @param awsClient
   * @param keySchema
   * @param tableName
   * @param proThrou
   */
public static void executeCreateTableRequest(AmazonDynamoDB awsClient, String tableName, ArrayList<KeySchemaElement> keySchema, Map<String, String> attrs, ProvisionedThroughput proThrou) {
    CreateTableRequest createTableRequest = buildCreateTableRequest(tableName, keySchema, proThrou, attrs);
    // use the client to perform the request
    try {
        awsClient.createTable(createTableRequest).getTableDescription();
        // wait for table to become active
        waitForTableToBecomeAvailable(awsClient, tableName);
    } catch (ResourceInUseException ex) {
        LOG.warn("Table '{}' already exists.", tableName);
    } finally {
        LOG.info("Table '{}' is available.", tableName);
    }
}
Also used : ResourceInUseException(com.amazonaws.services.dynamodbv2.model.ResourceInUseException) CreateTableRequest(com.amazonaws.services.dynamodbv2.model.CreateTableRequest)

Aggregations

AmazonServiceException (com.amazonaws.AmazonServiceException)16 AmazonDynamoDB (com.amazonaws.services.dynamodbv2.AmazonDynamoDB)12 ResourceNotFoundException (com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException)12 TableDescription (com.amazonaws.services.dynamodbv2.model.TableDescription)11 HashMap (java.util.HashMap)10 AttributeValue (com.amazonaws.services.dynamodbv2.model.AttributeValue)9 DescribeTableRequest (com.amazonaws.services.dynamodbv2.model.DescribeTableRequest)9 ProvisionedThroughput (com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput)9 CreateTableRequest (com.amazonaws.services.dynamodbv2.model.CreateTableRequest)8 KeySchemaElement (com.amazonaws.services.dynamodbv2.model.KeySchemaElement)8 ScanRequest (com.amazonaws.services.dynamodbv2.model.ScanRequest)8 ScanResult (com.amazonaws.services.dynamodbv2.model.ScanResult)7 AttributeDefinition (com.amazonaws.services.dynamodbv2.model.AttributeDefinition)6 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 DeleteTableRequest (com.amazonaws.services.dynamodbv2.model.DeleteTableRequest)5 GoraException (org.apache.gora.util.GoraException)4 AmazonClientException (com.amazonaws.AmazonClientException)3 DynamoDBMapper (com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper)2 Table (com.amazonaws.services.dynamodbv2.document.Table)2