Connecting dynamically to Cassandra using Spring Data Cassandra - cassandra

I need to connect dynamically to new Cassandra clusters without restarting the application. I'm using Spring Data Cassandra.
The following code does this, but since it's not done via beans and the IoC, it does not use the ExceptionTranslator implementation that translates Cassandra exceptions to exceptions in Spring’s portable DataAccessException hierarchy.
CqlSession session = CqlSession.builder()
.withKeyspace("composite")
.build();
template = new CassandraTemplate(session);
Is there a way to connect to Cassandra using Spring Data dynamically, by creating beans, in the middle of a running application so that we get the advantages of the standard exception translator? i.e. Not using annotations or XML which only work at startup.
Can you point me at some sample code?
I'm building a service and so what I really want are for these new beans to be part of the ApplicationContext. The above code I believe creates a separate context. The following creates these beans in the ApplicationContext.
var factory = context.getAutowireCapableBeanFactory();
var registry = (BeanDefinitionRegistry) factory;
var beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(Config.class);
registry.registerBeanDefinition("config", beanDef);
beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(CqlSessionFactoryBean.class);
beanDef.setParentName("config");
var properties = new MutablePropertyValues();
properties.add("contactPoints", contactPoints);
properties.add("keyspaceName", keyspaceName);
properties.add("localDatacenter", datacenter);
beanDef.setPropertyValues(properties);
registry.registerBeanDefinition("session", beanDef);
beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(CassandraMappingContext.class);
beanDef.setParentName("config");
properties = new MutablePropertyValues();
var session = factory.getBean("session");
properties.add("userTypeResolver", new SimpleUserTypeResolver((CqlSession) factory.getBean("session")));
beanDef.setPropertyValues(properties);
registry.registerBeanDefinition("mappingContext", beanDef);
beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(MappingCassandraConverter.class);
beanDef.setParentName("config");
var args = new ConstructorArgumentValues();
args.addGenericArgumentValue(factory.getBean("mappingContext"));
beanDef.setConstructorArgumentValues(args);
registry.registerBeanDefinition("converter", beanDef);
beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(SessionFactoryFactoryBean.class);
beanDef.setParentName("config");
properties = new MutablePropertyValues();
properties.add("session", factory.getBean("session"));
properties.add("converter", factory.getBean("converter"));
properties.add("schemaAction", SchemaAction.NONE);
beanDef.setPropertyValues(properties);
registry.registerBeanDefinition("sessionFactory", beanDef);
beanDef = new GenericBeanDefinition();
beanDef.setBeanClass(CassandraTemplate.class);
beanDef.setParentName("config");
args = new ConstructorArgumentValues();
args.addIndexedArgumentValue(0, factory.getBean("sessionFactory"));
args.addIndexedArgumentValue(1, factory.getBean("converter"));
beanDef.setConstructorArgumentValues(args);
registry.registerBeanDefinition("cassandraTemplate", beanDef);
template = (CassandraTemplate) factory.getBean("cassandraTemplate");

Related

Why aren't the Template tasks coming in when I create a project using a graph extension / C# code?

I have a customization where I'm creating projects in code using the ProjectEntry graph and
the PMProject DAC:
//create the project graph...
ProjectEntry projentry = PXGraph.CreateInstance<ProjectEntry>();
pmproj = new PMProject();
//Set the ProjectID:
pmproj.ContractCD = "000001"; //Project preferences is set to allow manually created project CDs...
//The template ID...
var tmplt = (PMProject)PXSelect<PMProject,
Where<PMProject.contractCD, Equal<Required<PMProject.contractCD>>>>.Select(Base, "00TEMPLATE01");
pmproj.TemplateID = tmplt.ContractID;
//The description....
pmproj.Description = "Test description";
//Now save the new project...
pmproj = projentry.Project.Insert(pmproj);
projentry.Persist();
It's not picking up the template tasks. Is there something else I need to do to get those tasks to come into the project?
There is a separate method that you need to trigger to populate settings from a project template.
DefaultFromTemplate(Project.Current, newTempleteID, DefaultFromTemplateSettings.Default);
It is executed automatically when you do that from UI, but if you do that from cod you need to do it manually.
Try this alternative approach to the sequence in which the values are entered in the Cache:
ProjectEntry projentry = PXGraph.CreateInstance<ProjectEntry>();
pmproj = new PMProject();
pmproj.ContractCD = "000001";
pmproj = projentry.Project.Insert(pmproj);
var tmplt = (PMProject)PXSelect<PMProject,
Where<PMProject.contractCD, Equal<Required<PMProject.contractCD>>>>.Select(Base, "00TEMPLATE01");
pmproj.TemplateID = tmplt.ContractID;
projentry.Project.Update(pmproj);
pmproj.Description = "Test description";
projentry.Project.Update(pmproj);
projentry.Actions.PressSave();

Insert data into cassandra using datastax driver

We are trying to insert data from CSV file into Cassandra using the DataStax driver for Java. What are the available methods to do so?
We are currently using running cqlsh to load from a CSV file.
The question is quite vague. Usually, you should be able to provide code, and give an example of something that isn't working quite right for you.
That being said, I just taught a class (this week) on this subject for our developers at work. So I can give you some quick examples.
First of all, you should have a separate class built to handle your Cassandra connection objects. I usually build it with a couple of constructors so that it can be called in a couple different ways. But each essentially calls a connect method, which looks something like this:
public void connect(String[] nodes, String user, String pwd, String dc) {
QueryOptions qo = new QueryOptions();
qo.setConsistencyLevel(ConsistencyLevel.LOCAL_ONE);
cluster = Cluster.builder()
.addContactPoints(nodes)
.withCredentials(user,pwd)
.withQueryOptions(qo)
.withLoadBalancingPolicy(
new TokenAwarePolicy(
DCAwareRoundRobinPolicy.builder()
.withLocalDc(dc)
.build()
)
)
.build();
session = cluster.connect();
With that in place, I also write a few simple methods to expose some functionality of the of the session object:
public ResultSet query(String strCQL) {
return session.execute(strCQL);
}
public PreparedStatement prepare(String strCQL) {
return session.prepare(strCQL);
}
public ResultSet query(BoundStatement bStatement) {
return session.execute(bStatement);
}
With those in-place, I can then call these methods from within a service layer. A simple INSERT (with preparing a statement and binding values to it) looks like this:
String[] nodes = {"10.6.8.2","10.6.6.4"};
CassandraConnection conn = new CassandraConnection(nodes, "aploetz", "flynnLives", "West-DC");
String userID = "Aaron";
String value = "whatever";
String strINSERT = "INSERT INTO stackoverflow.timestamptest "
+ "(userid, activetime, value) "
+ "VALUES (?,dateof(now()),?)";
PreparedStatement pIStatement = conn.prepare(strINSERT);
BoundStatement bIStatement = new BoundStatement(pIStatement);
bIStatement.bind(userID, value);
conn.query(bIStatement);
In addition, the DataStax Java Driver has a folder called "examples" in their Git repo. Here's a link to the "basic" examples, which I recommend reading further.

Spotfire Automation Xlsx DataWriter

I was wondering if anybody here attempted creating an Automation Service to Export a DataTable to Xlsx in Spotfire Automation Services? I have been trying to create one but I am having issues. If anybody has been able to do this can you please share your project?
THis is the code I have thus far but having issues with Accessing the DataSource and DataTable.
protected override TaskExecutionStatus ExecuteCore(TaskExecutionContext context)
{
DataRowReader dataRowReader;
///Create a DataWriter
DataWriter writer = context.Application.CreateDataWriter(DataWriterTypeIdentifiers.ExcelXlsDataWriter);
///<summary>
///Call the DataWriter Core from here or call a class that will do the relevant work
///<toDO>Need to find a way to access the current DataTable of the Open Analysis</toDo>
///</summary>
Document doc = context.Application.Document;
if(doc == null)
return new TaskExecutionStatus(false, "NoAnalysisLoaded");
DataManager data = doc.Context.GetService<DataManager>();
DataTable table = data.Tables.Add(doc.ActiveDataTableReference, dataSource);
string fileName = context.ExpandTags(this.filePath);
FileStream fs = File.OpenWrite(fileName);
//See how to properly impliment the writers
writer.Write(fs, table, new IndexSet(table.RowCount, true), table.Columns.Names);
fs.Close();
data.Tables.Remove(table);
return new TaskExecutionStatus(true);
}
To get the active data table reference you should use
DataTable mytable = Application.Document.ActiveDataTableReference;
and then you can use mytable further in the code.

Associate Multiple records to subgrid using plugin in Dynamics crm

I'm associating record to some other entity using AssociateRequest.My question is how to Associate multiple records to subgrid.could you plz anyone clarify me.
Entity en=(Entity)context.InputParameters["Target"];
AssociateRequest assreq = new AssociateRequest();
assreq.Target = new EntityReference(en.LogicalName,en.Id);
assreq.RelatedEntities = new EntityReferenceCollection();
assreq.RelatedEntities.Add(new EntityReference("contact", new Guid("72C8B80B-FEF1-E311-9345-D89D67642EB0")));
assreq.Relationship = new Relationship("contact_customer_accounts");
AssociateResponse assresponse = (AssociateResponse)service.Execute(assreq);
The AssociateRequest can only be used to create a relationship between two records. If you need to associate a record multiple times, you will have to repeat the procedure for every single relationship.
You can pack the AssociateRequest's into an ExecuteMultipleRequest and save some roundtrips to the server. Please, keep in mind: the requests that are in the ExecuteMultipleRequest do not participate in the same database transaction.
OrganizationRequestCollection associateRequestCollection = new OrganizationRequestCollection();
Entity en = (Entity)context.InputParameters["Target"];
you will have to create AssociateRequest for every single
relationship and add them int associateRequestCollection object like below
AssociateRequest assreq = new AssociateRequest();
assreq.Target = new EntityReference(en.LogicalName, en.Id);
assreq.RelatedEntities = new EntityReferenceCollection();
assreq.RelatedEntities.Add(new EntityReference("contact", new Guid("72C8B80B-FEF1-E311-9345-D89D67642EB0")));
assreq.Relationship = new Relationship("contact_customer_accounts");
associateRequestCollection.Add(assreq);
//Process the Create Multiple emails against Contact Ids;
ExecuteMultipleResponse emResponses = ExecuteCRMMultipleRequest(associateRequestCollection);
private ExecuteMultipleResponse ExecuteCrmMultipleRequest(OrganizationRequestCollection associateRequestCollection)
{
ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest
{
Requests = associateRequestCollection,
Settings = new ExecuteMultipleSettings
{
ContinueOnError = true,
ReturnResponses = true
}
};
return (ExecuteMultipleResponse)service.Execute(emRequest);
}

I dont have overload for EF savechanges, and no acceptallchanges available

I am very confused, i am trying in vain to queue up multiple inserts i have thousands of adds to do so i only want to really do the database once.
I am using .net 4 and entity framework 4 and also added reference to system.data.objects
but i still have no overload available for SaveChanges
here is my code:
using (TransactionScope scope = new TransactionScope())
{
using (myDbContext context = new myDbContext)
{
foreach (var p in model)
{
var tempProduct = new Products();
// set a loopable list of available products
IEnumerable<MerchantProductFeedMerchantProd> prod = p.prod;
foreach (var i in prod)
{
var prodText = i.text.FirstOrDefault();
var prodUri = i.uri.FirstOrDefault();
var prodPrice = i.price.FirstOrDefault();
FillTempProduct(feedId, i, tempProduct, supplierId, feedInfo, prodPrice, prodText,
prodUri);
context.Products.Add(tempProduct);
context.SaveChanges(false); // no overload
}
scope.Complete();
context.AcceptAllChanges(); //acceptallchanges not referenced ??
}
}
this is really battering my head now, so any help would be much appreciated.
thanks
Because you are using DbContext API and these methods are from ObjectContext API. DbContext API is simplified = it is only for simple requirements. If you have more complex requirements you must use ObjectContext API by converting your DbContext to ObjectContext instance:
var objectContext = ((IObjectContextAdapter)myDbContext).ObjectContext;

Resources