Serializing objects Codename One - codenameone

How do I serialize an object in order to make a customizable Parse initialization? Like:
//Simple text fields to get info
TextField url = new TextField();
TextField appid = new TextField();
TextField clientkey = new TextField();
then I put all in an object e.g:
Myclass object = new Myclass();
object.url = url.getText();
object.appid = appid.getText();
object.clientkey = clientkey.getText();
so I put it here, but before it needs to be serialized in order to keep its values after my app get restarted.
//After serialization
Parse.initialize(object.url, object.appid, object.clientkey);
In this way I can set my Parse initialization by my application instead.
I'd appreciate to see an example of serialization in this case.

When you store an object in parse it's saved locally so you don't need to serialize.
FYI Codename One supports the Externalizable interface to serialize objects in binary form. It also supports seamless externalization for object properties. The latter don't work with Parse AFAIK.

There's no support for serialization. You're on your own.

Related

Is there a way to populate an object instance using AutoFixture?

Here is a sample of what I'm trying to do
var foo = CreateFoo(); // I don't have access to the internals of CreateFoo
fixture.Populate(foo); // foo should now have random property values
Obviously, there is no Fixture.Populate method. But how should I solve this problem?
Thanks!
AutoFixture indeed doesn't provide API to fill writable properties of an existing object. However, you can use the following snippet to achieve the desired behavior:
var fixture = new Fixture();
var objectToFill = new TypeWithProperties();
new AutoPropertiesCommand().Execute(objectToFill, new SpecimenContext(fixture));
Assert.NotNull(objectToFill.Value);
If you need that often, you can create an extension method for the IFixture in your test project.

How to create a Solr collection that doesn't shuffle the createNodeSet hosts using the SolrJ API?

I'm trying to create a Solr collection on SolrCloud, and I want to pass in the hosts I want the collection to exist on in a certain order, and have Solr follow that order. Solr exposes this functionality in the API with the parameter createNodeSet.shuffle, but I can't explicitly set this parameter in a SolrAdminRequest.Create instance.
Does this functionality not exist within Solrj? Can I set the value with the setProperties() method even though it's a "param"?
I'm facing this problem too, and I notice that you had opened a PR on the GitHub. I've tried several ways to achieve this goal but finally I give up by shuffling the nodes myself, before passing them to the Create request.
In Kotlin:
val nodes = listOf("node1", "node2")
val createNodeSet = nodes.shuffled().joinToString(",")
In Java:
List<String> nodes = Arrays.asList("node1", "node2");
Collections.shuffle(nodes);
String createNodeSet = String.join(",", nodes);
As current Solr now has the constructor marked as protected, only accessible via a static builder, and as I didn't want to have a new class to worry about, I figured out the following way to set the needed parameter.
This method should be usable on many of the other builder created op objects.
Create req = CollectionAdminRequest //
.createCollection(newCollection, newConfigSet, NUM_SHARDS, NUM_REPLICAS);
final SolrParams reqParams = req.getParams();
if (reqParams instanceof ModifiableSolrParams) {
((ModifiableSolrParams) reqParams).set("createNodeSet.shuffle", "false");
}

Create Class object through class name in Salesforce

I am new to Salesforce and want to code one requirement, I have an api name in string variable through which I want to create an object of that class.
For Eg. Object name is Account which is stored in string variable.
String var = 'Account'
Now I want to create object of 'Account'. In java it is possible by Class.forName('Account') but similar approach is not working in Salesforce Apex.
Can anyone please help me out in this.
Have a look at Type class. The documentation for it isn't terribly intuitive, perhaps you'll benefit more from the article that introduced it: https://developer.salesforce.com/blogs/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html
I'm using this in managed package code which inserts Chatter posts (feed items) only if the org has Chatter enabled:
sObject fItem = (sObject)System.Type.forName('FeedItem').newInstance();
fItem.put('ParentId', UserInfo.getUserId());
fItem.put('Body', 'Bla bla bla');
insert fItem;
(If I'd hardcode the FeedItem class & insert it directly it'd mark my package as "requires Chatter to run").
Alternative would be to build a JSON representation of your object (String with not only the type but also some field values). You could have a look at https://salesforce.stackexchange.com/questions/171926/how-to-deserialize-json-to-sobject
At the very least now you know what keywords & examples to search for :)
Edit:
Based on your code snippet - try something like this:
String typeName = 'List<Account>';
String content = '[{"attributes":{"type":"Account"},"Name":"Some account"},{"attributes":{"type":"Account"},"Name":"Another account"}]';
Type t = Type.forName(typeName);
List<sObject> parsed = (List<sObject>) JSON.deserialize(content, t);
System.debug(parsed);
System.debug(parsed[1].get('Name'));
// And if you need to write code "if it's accounts then do something special with them":
if(t == List<Account>.class){
List<Account> accs = (List<Account>) parsed;
accs[1].BillingCountry = 'USA';
}

Getting Collection of particular Type with Hybris ModelService

Hiy!
I want all objects(rows in Test Type) with ModelService
So I could iterate through collection and update a Single row (object)'s attribute with new value
I see getModelService.create(TestModel.class) and getModelService.save()
but will they not create a new object/row rather than update a existing object?right
I don't want to create a new one rather selecting one of the existing matching my criteria and update one attribute of that
can somebody help with List<TestModel> testModels = getModelService.get(TestModel.class) will that return me all rows (collection) of Test Type/Table?
unfortunately I can't test it so need help
Actually I am in validateInterceptor ... and on the basis of this intercepted model changed attribute value I have to update another model attribute value...
thanks
ModelService.create(new TestModel.class) will create a single instance of the specified type and attach it to the modelservice's context.
But it will only be saved to the persistence store when you call modelService.save(newInstance)
ModelService.get() returns a model object but expects a Jalo object as input, (Jalo being the legacy persistence layer of hybris) so that won't work for you.
To retrieve objects you can either write your own queries using the FlexibleSearchService or you can have a look at the DefaultGenericDao which has a bunch of simple find() type of methods.
Typically you would inject the dao like e.g.:
private GenericDao<TestModel> dao;
[...]
public void myMethod()
{
List<TestModel> allTestModels = dao.find();
[...]
}
There are a lot more methods with which you can create WHERE type of statements to restrict your result.
Regarding ValidateInterceptor:
Have a look at the wiki page for the lifecycle of interceptors:
https://wiki.hybris.com/display/release5/Interceptors
It's not a good idea to modify 'all' objects of a type while being an interceptor of that type.
So if you're in an interceptor declared for the Test item type, then don't try to modify the items there.
If you happen to be in a different interceptor and want to modify items of a different type:
E.g. you have Type1 which has a list of Type2 objects in it and in the interceptor for Type1 you want to modify all Type2 objects.
For those scenarios you would have to add the instances of Type2 that you modify to the interceptor context so that those changes will be persisted.
That would be something like:
void onValidate(Test1 model, InterceptorContext ctx) throws InterceptorException
{
...
List<Type2> type2s = dao.find();
for (Type2 type2 : type2s)
{
// do something with it
// then make sure to persist that change
ctx.registerElementFor(type2, PersistenceOperation.SAVE);
[...]
}
}
First of all - i think it's not a good idea, to create/update models in any interceptor, especially in 'validation' one.
Regarding your question:
ModelService in most of the cases works with single model, and
designed for create/update/delete operations.
To retreive all models of certain type, you have to use FlexibleSearchService
Then to update each retrieved TestType model, you can use ModelService's save method.
A query to retreive all TestType models will look like:
SELECT PK FROM {TestType}
You could simply use the Flexible Search Service search by example method, and the model service to save them all. Here is an example using Groovy script, with all products :
import java.util.List
import de.hybris.platform.core.model.product.ProductModel
import de.hybris.platform.servicelayer.search.FlexibleSearchService
import de.hybris.platform.servicelayer.model.ModelService
FlexibleSearchService fsq = spring.getBean("flexibleSearchService")
ModelService ms = spring.getBean("modelService")
ProductModel prd = ms.create(ProductModel.class)
List<ProductModel> products = fsq.getModelsByExample(prd)
//Do Whatever you want with the objects in the List
ms.saveAll(products)

How, WCF Ria Services can make a customised entity, known at client-side?

I constructed my Entity Model. One of my business objects,let's call it Store has a spatial data type. Very quickly I figured out that spatial fields aren't mapped via EF4. However I struggled my way out, by editing the xml declarations defining a query like the following:
<EntitySet Name="Stores" EntityType="Eltrun.OnShelfAuditModel.Store.Stores">
<DefiningQuery>
SELECT [rowId], [storeName], [location].STAsText() as location FROM Stores
</DefiningQuery>
</EntitySet>
At this point I decided to customize my Store entity via a partial class like this, just to make the conversion and still keep the SQLGeography data stored, returning just a double[] at client (as I cannot return neither SqlGeography, neither Location (Bing datatype).
public partial class Store
{
public double[] StoreLocation
{
get
{
SqlGeography geoLocation = SqlGeography.
STPointFromText(new SqlChars(this.location.ToCharArray()), 4326);
return new double[]{
(double)geoLocation.Lat,
(double)geoLocation.Long};
}
}
}
How can I make aware the Store data type of my little customization, at client project?
Thank you!
Just add a setter to your property, and the RIA Services code generator and serializer should create the equivalent property on the client's version of the Store class.
Hope that helps...

Resources