I want to convert ItemCollection into my java pojo object .I want currently doing so by following way .What is the best way to do so?
QuerySpec spec = new QuerySpec()
.withKeyConditionExpression("txn_id = :txnId")
.withFilterExpression("rrn = :rrn")
.withValueMap(new ValueMap()
.withString(":txnId", txnId)
.withString(":rrn", rrn))
.withConsistentRead(true);
ItemCollection<QueryOutcome> items = table.query(spec);
here i got ItemCollection .Now i will be converting it to my java pojo :-
Iterator<Item> iter = items.iterator();
while (iter.hasNext()) {
String txn = iter.next().toJSON();
Gson gson = new Gson();
Test t = gson.fromJson(txn, Test.class);
return t;
}
Is there a way to convert dynamodb fetch value( ItemCollection) to java pojo directly like we do in mysql ?Why i will always get json then covert to pojo .We don't do so in other DB like mysql or oracle DB .
Text.java
public class Test implements Serializable {
#DynamoDBAttribute(attributeName = "txn_id")
#JsonProperty("txn_id")
#DynamoDBHashKey
private String txnId;
private String umn;
private String note;
#DynamoDBAttribute(attributeName = "rrn")
private String rrn;
#DynamoDBAttribute(attributeName = "expire_on")
private Date expireOn;
#DynamoDBAttribute(attributeName = "expire_after")
private Integer expireAfter;
#DynamoDBAttribute(attributeName = "created_on")
#DynamoDBAutoGeneratedTimestamp(strategy= DynamoDBAutoGenerateStrategy.CREATE)
private Date createdOn;
}
Yes, take a look at DynamoDBMapper. Uses the same pojo annotations...
CatalogItem partitionKey = new CatalogItem();
partitionKey.setId(102);
DynamoDBQueryExpression<CatalogItem> queryExpression = new DynamoDBQueryExpression<CatalogItem>()
.withHashKeyValues(partitionKey);
List<CatalogItem> itemList = mapper.query(CatalogItem.class, queryExpression);
for (int i = 0; i < itemList.size(); i++) {
System.out.println(itemList.get(i).getTitle());
System.out.println(itemList.get(i).getBookAuthors());
}
Related
I want to convert this query
select lKey from KeyMapping where gKey in ['A#1','A#2','A#3'];
I have a List that contain A#1, A#2 and A#3
into Java code to extract records from DynamoDB using PartiQL
#Autowired
private AmazonDynamoDB client;
List<String> paramList = new ArrayList<>(); //List of Parameters
paramList.add("A#1");
paramList.add("A#2");
paramList.add("A#3");
ExecuteStatementRequest request = new ExecuteStatementRequest();
String[] placeholders = new String[paramList.size()];
Arrays.fill(placeholders, "?");
String commalist = Arrays.stream(placeholders).collect(Collectors.joining(","));
request.setStatement("select * from "+appConfigs.getBoclipsTableName()+" where id in ("+commalist+")");
List<AttributeValue> parameters = new ArrayList<>();
for(String videoId: videoIds){
parameters.add(new AttributeValue(videoId));
}
System.out.println(client.executeStatement(request).toString());
I try to follow the article Access Azure Storage in an ASP.NET Core application using Connected Services, under ASP.NET Core 1.1 in order to connect my web application to Azure Tables.
I created
public interface ITableRepositories
{
void CreateRecord(Record record);
List<Record> GetRecords();
Record GetRecord(string key, string partitionKey = "record");
}
But the problem is that under ASP.NET Core and Microsoft.WindowsAzure.Storage nuget I have no acces to the Syncronous methods.
So, by eg this code of the OperationService class:
public class TableClientOperationsService : ITableRepositories
{
CloudStorageAccount storageAccount;
CloudTableClient tableClient;
IConfigurationRoot configs;
public TableClientOperationsService(IConfigurationRoot c) {
this.configs = c;
var connStr = this.configs.GetSection("MicrosoftAzureStorage:[...]");
storageAccount = CloudStorageAccount.Parse(connStr.Value);
tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("Book");
table.CreateIfNotExists();
}
I am forced to do the Async variant of the connector:
public class TableClientOperationsService: ITableRepositories
{
CloudStorageAccount storageAccount;
CloudTableClient tableClient;
public TableClientOperationsService(IOptions<AppSecrets> optionsAccessor) {
string connectionString = optionsAccessor.Value.MyProjectTablesConnectionString;
storageAccount = CloudStorageAccount.Parse(connectionString);
tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("Record");
// ??? How to use the async method in constructor?
var created = await table.CreateIfNotExistsAsync();
}
}
So what should be the Async approach for this? Should I create a static constructor instead?
PS.
Also the CreateRecord "async" operation
from
public void CreateBook(Book bk)
{
Random rnd = new Random();
bk.BookId = rnd.Next(100);
bk.RowKey = bk.BookId.ToString();
bk.PartitionKey = bk.Publisher;
CloudTable table = tableClient.GetTableReference("Book");
TableOperation insertOperation = TableOperation.Insert(bk);
table.Execute(insertOperation);
}
should be transformed in (?)
public void CreateRecord(Record record)
{
// var rowKey = (DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks).ToString("d19");
TableOperation insertOperation = TableOperation.Insert(record);
this.RecordTable.ExecuteAsync(insertOperation).Wait();
}
Or rather in
public Task<TableResult> CreateRecord(Record record)
{
TableOperation insertOperation = TableOperation.Insert(record);
return this.RecordTable.ExecuteAsync(insertOperation);
}
Finally I did it like
public async Task<bool> CreateRecord(Record record)
{
TableOperation insertOperation = TableOperation.Insert(record);
await this.RecordTable.ExecuteAsync(insertOperation);
return true;
}
also the
public Record GetRecord(string key, string partitionKey = "record")
{
Record myRecord = null;
TableOperation operation = TableOperation.Retrieve<Record>(partitionKey, key);
// ?
myRecord = recordTable.ExecuteAsync(operation).Result as Record;
}
The easy solution would be to just Wait() the async methods:
public class TableClientOperationsService: ITableRepositories
{
CloudStorageAccount storageAccount;
CloudTableClient tableClient;
public TableClientOperationsService(IOptions<AppSecrets> optionsAccessor)
{
string connectionString = optionsAccessor.Value.MyProjectTablesConnectionString;
storageAccount = CloudStorageAccount.Parse(connectionString);
tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("Record");
table.CreateIfNotExistsAsync().Wait();
}
}
If you need the result of the async method, try Result:
var created = table.CreateIfNotExistsAsync().Result;
Personally I'm not a big fan of constructors with (too) much functionality in them. Especially if it's something that (relatively) might take a while like connecting to a StorageAccount. You could implement an Initalize() method that could be async. Or you could implement a lazy property that only creates the CloudTable (and everything needed to get there) the first time the property is used. This also enables you to re-use the CloudTable during the lifetime of your class.
This would look something like this:
private CloudTable _table;
private CloudTable Table
{
get
{
if (_table == null)
{
var storageAccount = CloudStorageAccount.Parse(connectionString);
var tableClient = storageAccount.CreateCloudTableClient();
_table = tableClient.GetTableReference("Record");
_table.CreateIfNotExistsAsync().Wait();
}
return _table;
}
}
Does anyone know what has replaced AmazonDynamoDBClient?
Couldn't find anything in the documentation
Package - com.amazonaws.services.dynamodbv2
AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient();
As per the API doc, the builder class (e.g. AmazonDynamoDBClientBuilder) should be used to create the instance.
Sample code using the builder class:-
I have create the client for DynamoDB local.
DynamoDB dynamoDB = new DynamoDB(AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(new EndpointConfiguration("http://localhost:8000", "us-east-1")).build());
Table table = dynamoDB.getTable("Movies");
Scan using DynamoDB table class:-
private static void findProductsForPriceLessThanZero() {
Table table = dynamoDB.getTable(tableName);
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":pr", 100);
ItemCollection<ScanOutcome> items = table.scan(
"Price < :pr", //FilterExpression
"Id, Title, ProductCategory, Price", //ProjectionExpression
null, //ExpressionAttributeNames - not used in this example
expressionAttributeValues);
System.out.println("Scan of " + tableName + " for items with a price less than 100.");
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
}
I am using spring-boot, the way I am working with Dynamo is injecting an AWSCredentialsProvider and using the variables which are in my environment in this way:
#Bean
public AmazonDynamoDB amazonDynamoDB(AWSCredentialsProvider awsCredentialsProvider) {
AmazonDynamoDB amazonDynamoDB
= AmazonDynamoDBClientBuilder.standard()
.withCredentials(awsCredentialsProvider).build();
return amazonDynamoDB;
}
#Bean
public AWSCredentialsProvider awsCredentialsProvider() {
return new EnvironmentVariableCredentialsProvider();
}
The full example is available here: https://github.com/ioet/bpm-skills-api
This is the code for the TableView:
TableView<KontaktPerson> tableKontaktPerson = new TableView<>();
TableColumn KontaktPersonFornavn = new TableColumn("Fornavn");
KontaktPersonFornavn.setCellValueFactory(new PropertyValueFactory<KontaktPerson, String>("fornavn"));
TableColumn KontaktPersonEtternavn = new TableColumn("Etternavn");
KontaktPersonEtternavn.setCellValueFactory(new PropertyValueFactory<KontaktPerson, String>("etternavn"));
TableColumn KontaktPersonNr = new TableColumn("Medlemsnummer");
KontaktPersonNr.setCellValueFactory(new PropertyValueFactory<KontaktPerson, Integer>("medlemsNr"));
tableKontaktPerson.getColumns().addAll(KontaktPersonFornavn,KontaktPersonEtternavn,KontaktPersonNr);
tableKontaktPerson.getSelectionModel().cellSelectionEnabledProperty();
tableKontaktPerson.setPrefSize(800, 300);
i wish to display the "fornavn","etternavn" and "medlemsNr" of that Object
Here is the "KontaktPerson" Class:
public class KontaktPerson extends Bruker implements Serializable {
private String fornavn, etternavn, telefon, epost;
private static int nestenr = 1000;
private int medlemsNr;
public KontaktPerson(String br, String pas, String fn, String en, String tlf, String ep) { // Tar in oppgitte Stirng verdier
super(br,pas);
fornavn = fn;
etternavn = en;
telefon = tlf;
epost = ep;
medlemsNr = ++nestenr;
}
}
For some reason i cant seem to get the "fornavn" and "etternavn" out, i just get the medlemsNr...
Am facing an issue with Alfresco and honestly am not expert with this type of technology:
the idea is to add an xml file under a folder
the code is like that:
//with the static values are:
public static final String SUSPENDRE_DESUSPENDRE_CONTENT_NAME = "suspendreDesuspendre";
private static final String SUSPENDRE_DESUSPENDRE_CONTENT_TYPE = "text/xml";
private static final String SUSPENDRE_DESUSPENDRE_CONTENT_ENCODING = "UTF-8";
private static final ContentFormat SUSPENDRE_DESUSPENDRE_CONTENT_FORMAT = new ContentFormat(SUSPENDRE_DESUSPENDRE_CONTENT_TYPE,SUSPENDRE_DESUSPENDRE_CONTENT_ENCODING);
private static final byte[] SUSPENDRE_DESUSPENDRE_CONTENT_INITIAL_BYTES = "<?xml //version=\"1.0\" encoding=\"UTF-8\"?><suspendreDesuspendre></suspendreDesuspendre>".getBytes();
#Override
public void createOrUpdateHisSuspendre(ContractBean contractbean,SuspendreDesuspendreEntree suspendreDesuspendreEntree) throws Exception
{
String parentUuid=contractbean.getUuid();
contractDAO.createAlfrescoContent(parentUuid, SUSPENDRE_DESUSPENDRE_CONTENT_NAME, SUSPENDRE_DESUSPENDRE_CONTENT_INITIAL_BYTES, SUSPENDRE_DESUSPENDRE_CONTENT_FORMAT);
}
public Reference createAlfrescoContent(String folderUuid, String contentName,byte[] contentBytes,ContentFormat contentFormat)throws RepositoryFault, RemoteException {
ParentReference parentReference = new ParentReference(new Store(Constants.WORKSPACE_STORE, "SpacesStore"), folderUuid, null, Constants.ASSOC_CONTAINS, "{" + Constants.NAMESPACE_CONTENT_MODEL + "}" + contentName);
NamedValue[] properties = new NamedValue[]{Utils.createNamedValue(Constants.PROP_NAME, contentName)};
CMLCreate create = new CMLCreate("1", parentReference, null, null, null,
Constants.TYPE_CONTENT, properties);
CML cml = new CML();
cml.setCreate(new CMLCreate[]{create});
UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
Reference newContentNode = result[0].getDestination();
Content content = WebServiceFactory.getContentService().write(newContentNode, Constants.PROP_CONTENT, contentBytes, contentFormat);
return content.getNode();
}
the error is:
The association source type is incorrect:
Source Node: workspace://SpacesStore/d4ffbff4-6bd6-4945-948e-2c16c1990cb9
Association: Association[ class=ClassDef[name={http://www.alfresco.org/model/content/1.0}folder], name={http://www.alfresco.org/model/content/1.0}contains, target class={http://www.alfresco.org/model/system/1.0}base, source role=null, target role=null]
Required Source Type: {http://www.alfresco.org/model/content/1.0}folder
Actual Source Type: {com.genia.cnas.alfresco.model}contratDefenseur