How to check if key exists or not using json-path library? - rest-assured

I'm using Json Path library and I want to check if key exists or not and based on that I'll do some actions. Hence I wrote following code -
for(int i = 0; i < keyValues.length; i++) {
List<String> invalidKeys = new ArrayList<>();
if(Objects.isNull(jsonPath.getString(key))) {
invalidKeys.add(key);
continue;
}else {
value = keyValues[i].split("=")[1];
}
}
My intention to get keys which are not present in json but with this code, if key has value as null that is also treated non-existing key. Is there any way I can modify above code to get only keys which are not present in json?

You can use your jsonPath to build a JSONObject:
JSONObject jsonObject = new JSONObject(jsonPath.prettify());
Then you can use this jsonObject to check if the key exists:
for(int i = 0; i < keyValues.length; i++) {
List<String> invalidKeys = new ArrayList<>();
if(!jsonObject.has(key)) {
invalidKeys.add(key);
continue;
}else {
value = keyValues[i].split("=")[1];
}
}

Related

am working on updating a single attribute in the User Model which is the balance attribute,

how I can update a single value for an already existing row in the db by only having a parameters that I want to add it to this attribute
here is my code for a trivial way but didnt work
public bool BuyBook(int BookId, int UserId, int BookPrice){
using (var ctx = new OnlineBooksEntities())
{
User updatedCustomer = (from c in ctx.Users
where c.UserId == UserId
select c).FirstOrDefault();
updatedCustomer.Balance = BookPrice;
ctx.SaveChanges();
}
this.DeleteBook(BookId);
return true;
}
Add an sql query to the method solves the update aim
public bool BuyBook(int BookId, int UserId, int BookPrice)
{
try
{
using (var ctx = new OnlineBooksEntities())
{
User user = ctx.Users.Where(x => x.UserId == UserId).FirstOrDefault();
BookPrice = (int)user.Balance + BookPrice;
int noOfRowUpdated =
ctx.Database.ExecuteSqlCommand("Update Users set Balance = "+BookPrice+ " where UserId ="+UserId);
}
Updating basically means changing an existing row's value. Since you mentioned EF, you can do this by retrieving the object, changing its value, and saving it back. Thus you can do something like this:
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookPrice == bookPrice);
if (result != null)
{
result.SomeValue = "Your new value here";
db.SaveChanges();
}
}

In .NET MVC - how do we get back a parameter map of key/name values

I want to port this Spring MVC to .NET MVC. This Spring MVC can handle any submissions because I am a map:
#RequestMapping(value = "/invokeFormStrSubmit.do", method = RequestMethod.POST)
ModelAndView addCustomer2(HttpServletRequest request, HttpServletResponse response) {
java.util.Map<java.lang.String,java.lang.String[]> formData = request.getParameterMap();
This works nicely in Spring MVC.
How do we do this same in .NET MVC? I can read the parameters when I know the form fields.
Thank you for your help...
Request.Params is a NameValue collection of everything submitted in the form. See here:
HttpRequest.Params
You can use NameValueCollection -
a collection of associated String keys and String values that can be accessed either with the key or with the index.
public System.Collections.Specialized.NameValueCollection Params { get; }
See below how to loop through the Params property for a page and how to display each key/value pair.
string paramInfo = "";
NameValueCollection pColl = Request.Params;
for(int i = 0; i <= pColl.Count - 1; i++)
{
paramInfo += "Key: " + pColl.GetKey(i);
string[] pValues = pColl.GetValues(i);
for(int j = 0; j <= pValues.Length - 1; j++)
{
paramInfo += "Value:" + pValues[j];
}
HTTPRequest.Params is not defined for HTTPRequest that is part of Microsoft.AspNetCore.Http namespace.
My objective was to build a COntroller that can handle form fields from an unknown form. It could be a JQuery Mobile Form with different fields. Since there are different fields - we cannot use a model.
I got this working with HTTPRequest.Form:
public IActionResult HandleSubmission()
{
// NameValueCollection coll;
try
{
var address = HttpContext.Connection.RemoteIpAddress;
var userAgent = Request.Headers["User-Agent"].FirstOrDefault();
IFormCollection userdata = Request.Form;
int myCount = userdata.Count;
foreach (var item in userdata.Keys)
{
String yy = "5";
String uu= item.ToString();
Microsoft.Extensions.Primitives.StringValues ttt;
userdata.TryGetValue(uu, out ttt);
}
}
catch (Exception w)
{
Console.Write(w.StackTrace);
}

enumerate resource-bundles defined in faces-config.xml

I am using a mojarra-specific code for this:
public static Map<String, ResourceBundle> getBundleMap()
{
Locale locale = Faces.getLocale();
ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();
Map<String, ApplicationResourceBundle> resourceBundles = associate.getResourceBundles();
Map<String, ResourceBundle> map = new HashMap<>(resourceBundles.size());
for(Entry<String, ApplicationResourceBundle> entry : resourceBundles.entrySet())
{
String name = entry.getKey();
ResourceBundle bundle = entry.getValue().getResourceBundle(locale);
map.put(name, bundle);
}
return map;
}
I'd like to have an implementation-agnostic way to get this map.
Should I parse every faces-config.xml defined in application and libs? Isn't this reinventing the wheel?
A Map<String, String>, where key = /faces-config/application/resource-bundle/var and value = /faces-config/application/resource-bundle/base-name would be sufficient.
Thanks.
I'd like to have an implementation-agnostic way to get this map.
Understandable.
Should I parse every faces-config.xml defined in application and libs?
Yes. This functionality isn't available in JSF API.
Isn't this reinventing the wheel?
Yes, definitely. You could however try to get it into OmniFaces, which has already a similar utility class for /WEB-INF/web.xml and all /META-INF/web-fragment.xml, the WebXml.
A Map<String, String>, where key = /faces-config/application/resource-bundle/var and value = /faces-config/application/resource-bundle/base-name would be sufficient.
Here's a kickoff example using JAXP (cough):
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(false);
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.appendChild(document.createElement("all-faces-configs"));
List<URL> facesConfigURLs = new ArrayList<>();
facesConfigURLs.add(FacesContext.getCurrentInstance().getExternalContext().getResource("/WEB-INF/faces-config.xml"));
facesConfigURLs.addAll(Collections.list(Thread.currentThread().getContextClassLoader().getResources("META-INF/faces-config.xml")));
for (URL facesConfigURL : facesConfigURLs) {
URLConnection connection = facesConfigURL.openConnection();
connection.setUseCaches(false);
try (InputStream input = connection.getInputStream()) {
NodeList children = builder.parse(input).getDocumentElement().getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
document.getDocumentElement().appendChild(document.importNode(children.item(i), true));
}
}
}
Map<String, String> resourceBundles = new HashMap<>();
Element allFacesConfigs = document.getDocumentElement();
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList resourceBundleNodes = (NodeList) xpath.compile("application/resource-bundle").evaluate(allFacesConfigs, XPathConstants.NODESET);
for (int i = 0; i < resourceBundleNodes.getLength(); i++) {
Node resourceBundleNode = resourceBundleNodes.item(i);
String var = xpath.compile("var").evaluate(resourceBundleNode).trim();
String baseName = xpath.compile("base-name").evaluate(resourceBundleNode).trim();
resourceBundles.put(var, baseName);
}

smartgwt listgrid.getRecordList() not give me updated data

I'm on my smartgwt project having issue in listgrid.
my listgrid having data come from server side, and user allow to edit any record from that grid.
searchGrid.setAutoFetchData(true);
searchGrid.setDataSource(searchDS);
searchGrid.setAlwaysShowEditors(true);
When I try to edit any cell in grid and try to loop through all record from grid, it doesn't give me latest updated cell which I edited.
I use below code for fetching all records from my listgrid.
private String getGridDetails() {
RecordList records = searchGrid.getRecordList();
Document doc = XMLParser.createDocument();
Element rootElement = doc.createElement("ROOT");
doc.appendChild(rootElement);
for (int i = 0; i < records.getLength(); i++) {
Record rec = records.get(i);
Element row = doc.createElement("ROW");
for (String str : rec.getAttributes()) {
String propertyVal = rec.getAttributeAsString(str);
if (propertyVal != null
&& propertyVal.equalsIgnoreCase("") != true) {
Element columnElement = doc
.createElement(str.toUpperCase());
columnElement.appendChild(doc.createTextNode(propertyVal));
row.appendChild(columnElement);
}
}
rootElement.appendChild(row);
}
return doc.toString();
}
If you want to get every edited and unedited record, you may loop one by one:
public Record[] getData(ListGrid grid)
{
RecordList data = new RecordList();
for (int i = 0; i < grid.getTotalRows(); i++)
data.add(grid.getEditedRecord(i));
return data.duplicate();
}
But if you just want to retrieve the edited records, try the following snippet:
public static Record[] dameDatosLocalesEditedRows(ListGrid grid)
{
RecordList data = new RecordList();
int[] edited = grid.getAllEditRows();
for (int i = 0; i < edited.length; i++)
data.add(grid.getEditedRecord(edited[i]));
return data.duplicate();
}

Reflection + Entity Framework to update data in MVC app

I've got a complex form on a page that is bound to a POCO representing a rather complex entity. One of the requirements is that, on blur, I update the database.
I'm currently passing the property (as key), value, and CampaignId via ajax. The key might look something like: Campaign.FanSettings.SocialSharing.FacebookLinkText.
I am using the code below, and getting "close". My final propertyToSet is the FacebookLinkText is not being set, because my object source is of type Entities.Campaign, while my object value is simply a string. I understand these need to be the same type, but I don't understand how to do that. Two questions:
How do I modify the code below to be able to execute the propertyToSet.SetValue method
Since I'm casting this to an object, I don't see how this would actually update my entity, so when I call SaveChanges it updates appropriately. What am I missing?
Thanks!
Code:
public void UpdateCampaign(int id, string key, string value)
{
using (var context = new BetaEntities())
{
var camp = context.Campaigns.Where(e => e.Id == id).Single();
SetProperty(camp, key,value);
}
}
public void SetProperty(object source, string property, object value)
{
string[] bits = property.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
{
PropertyInfo prop = source.GetType().GetProperty(bits[i]);
source = prop.GetValue(source, null);
}
PropertyInfo propertyToSet = null;
if (source is IEnumerable)
{
foreach (object o in (source as IEnumerable))
{
propertyToSet = o.GetType().GetProperty(bits[bits.Length - 1]);
break;
}
}
else
{
propertyToSet = source.GetType().GetProperty(bits[bits.Length - 1]);
}
propertyToSet.SetValue(source, value, null);
}
Solved.
public void UpdateCampaign(int id, string key, string value)
{
using (var context = new BetaEntities())
{
var camp = context.Campaigns.Where(e => e.Id == id).Single();
SetProperty(camp, key, value);
context.SaveChanges()
}
}
public void SetProperty(object source, string property, object value)
{
string[] bits = property.Split('.');
for (int i = 0; i < bits.Length - 1; i++)
{
PropertyInfo prop = source.GetType().GetProperty(bits[i]);
source = prop.GetValue(source, null);
}
PropertyInfo propertyToSet = null;
if (source is IEnumerable)
{
foreach (object o in (source as IEnumerable))
{
propertyToSet = o.GetType().GetProperty(bits[bits.Length - 1]);
propertyToSet.SetValue(o, value,null);
break;
}
}
else
{
propertyToSet = source.GetType().GetProperty(bits[bits.Length - 1]);
propertyToSet.SetValue(source, value, null);
}
}

Resources