MongoDB + Spring MVC - mongodb

I have working a project which is combination of Spring MVC and Mongodb .
The Database Structure
{
"id": " 12214 -1",
"eRA": " 12214 -1",
"agreementId": null,
"agreementNumber": null,
"deviceTimestamp": null,
"tag": null,
"curentLocation": null,
"gps": "NO",
"grps": "NO",
"logs": {},
"isRead": "1.0",
"rptTime": "15:00",
"salut": "Mr",
"guestName": "Ritesh Arora",
"guestCompShortName": "mmi",
"vehNum": "KL22E2448",
"chauffName": "baba",
"rptDate": "40-83-2.01 15:00",
"rladdr": null,
"rentalType": "Local Run",
"addressRL": "Okhla",
"status": "Received from Carpro"
}
Bean Class Structre
#Document
public class Agreement {
#Id
private String id;
private String eRA;
private AgreementId agreementId; // /Aggrement No
private String agreementNumber;
private String RLAddr; // // RL
private String Salut; // // Salut
private String GuestName; // //GuestName ;
private String GuestCompShortName; // / Company;
private String VehNum; // / vechileNumber
private String ChauffName; // / Driver
private String RentalType; // / RentalType
private String AddressRL; // / reportingAddress
private String RptDate; // / RptDate + RptTime reportingDateTime
private String RptTime; // / RptDate + RptTime reportingDateTime
private String deviceTimestamp; // ///
private String tag;
private String curentLocation;
#Field("Status")
private String Status; // // eRAStatus
private String gps;
private String type;
private String grps;
private Map<String, Map<String, Double>> logs;
private String isRead;
private String name;
public String getType() {
return this.getStatus();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public String getIsRead() {
return isRead;
}
public void setIsRead(String isRead) {
this.isRead = isRead;
}
public String geteRA() {
this.id = this.id.replace("{ \"AgreementNo\" :", "")
.replace(" \"SubNo\" : ", "").replace("}", "")
.replace(",", "-");
return this.id;
}
public void seteRA(String eRA) {
this.eRA = eRA;
}
public AgreementId getAgreementId() {
return agreementId;
}
public void setAgreementId(AgreementId agreementId) {
this.agreementId = agreementId;
}
public String getRLAddr() {
return RLAddr;
}
public void setRLAddr(String rLAddr) {
RLAddr = rLAddr;
}
public String getSalut() {
return Salut;
}
public void setSalut(String salut) {
Salut = salut;
}
public String getGuestName() {
return GuestName;
}
public void setGuestName(String guestName) {
GuestName = guestName;
}
public String getGuestCompShortName() {
return GuestCompShortName;
}
public void setGuestCompShortName(String guestCompShortName) {
GuestCompShortName = guestCompShortName;
}
public String getVehNum() {
return VehNum;
}
public void setVehNum(String vehNum) {
VehNum = vehNum;
}
public String getChauffName() {
return ChauffName;
}
public void setChauffName(String chauffName) {
ChauffName = chauffName;
}
public String getRentalType() {
String rtype = null;
if (RentalType == "1" || RentalType.equalsIgnoreCase("1")) {
rtype = "Local Run";
} else if (RentalType == "2" || RentalType.equalsIgnoreCase("2")) {
rtype = "Out Station";
} else if (RentalType == "3" || RentalType.equalsIgnoreCase("3")) {
rtype = "Transfer";
} else if (RentalType == "4" || RentalType.equalsIgnoreCase("4")) {
rtype = "Package";
} else if (RentalType == "5" || RentalType.equalsIgnoreCase("5")) {
rtype = "self Drive";
} else if (RentalType == "6" || RentalType.equalsIgnoreCase("6")) {
rtype = "LTR";
}
return rtype;
}
public void setRentalType(String rentalType) {
RentalType = rentalType;
}
public String getAddressRL() {
return AddressRL;
}
public void setAddressRL(String addressRL) {
AddressRL = addressRL;
}
public String getRptDate() {
String d = RptDate.substring(4, 6) + "-" + RptDate.substring(6, 8)
+ "-" + RptDate.substring(0, 4);
return d + " " + RptTime;
}
public void setRptDate(String rptDate) {
RptDate = rptDate;
}
public String getRptTime() {
return RptTime;
}
public void setRptTime(String rptTime) {
RptTime = rptTime;
}
public String getDeviceTimestamp() {
return deviceTimestamp;
}
public void setDeviceTimestamp(String deviceTimestamp) {
this.deviceTimestamp = deviceTimestamp;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getCurentLocation() {
return curentLocation;
}
public void setCurentLocation(String curentLocation) {
this.curentLocation = curentLocation;
}
public String getStatus() {
String str = null;
if (Status == "1" || Status.equals("1")) {
Status = "Received from Carpro";
} else if (Status == "2" || Status.equals("2")) {
Status = "Complete Close";
} else if (Status == "3" || Status.equals("3")) {
Status = "Recall";
} else if (Status == "4" || Status.equals("4")) {
Status = "Accepted";
} else if (Status == "5" || Status.equals("5")) {
Status = "Start Journey";
} else if (Status == "6" || Status.equals("6")) {
Status = "Reached Pickup location";
} else if (Status == "7" || Status.equals("7")) {
Status = "Reached Drop off location";
} else if (Status == "8" || Status.equals("8")) {
Status = "Duty completed";
} else if (Status == "9" || Status.equals("9")) {
Status = "Expense Pending";
} else if (Status == "10" || Status.equals("10")) {
Status = "Didn't used";
} else if (Status == "11" || Status.equals("11")) {
Status = "Didn't arrive";
} else if (Status == "12" || Status.equals("12")) {
Status = "Break Down";
} else if (Status == "13" || Status.equals("13")) {
Status = "Exchange";
} else if (Status == "14" || Status.equals("14")) {
Status = "Dispatched to mobile";
} else if (Status == "15" || Status.equals("15")) {
Status = "Not Mapped or not delivered to mobilee";
} else if (Status == "16" || Status.equals("16")) {
Status = "Not Accepted";
} else if (Status == "17" || Status.equals("17")) {
Status = "Start Button Not Pressed";
} else if (Status == "18" || Status.equals("18")) {
Status = "Pickup Button not Pressed";
} else if (Status == "19" || Status.equals("19")) {
Status = "Closure status not received";
} else if (Status == "20" || Status.equals("20")) {
Status = "No GPRS";
} else if (Status == "21" || Status.equals("21")) {
Status = "No GPS";
} else if (Status == "22") {
Status = "Didn't communicate to fleet";
}
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getAgreementNumber() {
return agreementNumber;
}
public void setAgreementNumber(String agreementNumber) {
this.agreementNumber = agreementNumber;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Map<String, Double>> getLogs() {
return logs;
}
public void setLogs(Map<String, Map<String, Double>> logs) {
this.logs = logs;
}
public String getGps() {
if (this.Status == "21" || this.Status.equalsIgnoreCase("21"))
return "YES";
else
return "NO";
}
public void setGps(String gps) {
this.gps = gps;
}
public String getGrps() {
if (this.Status == "20" || this.Status.equalsIgnoreCase("20"))
return "YES";
else
return "NO";
}
public void setGrps(String grps) {
this.grps = grps;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return RLAddr + " >>> " + Salut + ">>>>>>> " + id + "vdsvsdvs ";
}
}
but when is used
query1.addCriteria(Criteria.where("Status").is("constant"));
mongoTemplate.find(query1, Agreement.class, "eRA_live_v1");
I am getting following Error
SEVERE: Servlet.service() for servlet [mvc-dispatcher] in context with path [/avisweb] threw exception [Request processing failed; nested exception is o org.springframework.data.mapping.model.MappingException: No property status found on com.avis.bean.Agreement!] with root cause
org.springframework.data.mapping.model.MappingException: No property status found on com.avis.bean.Agreement!
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:228)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:206)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentPropertyPath(AbstractMappingContext.java:194)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.getPath(QueryMapper.java:714)
at org.springframework.data.mongodb.core.convert.QueryMapper$MetadataBackedField.<init>(QueryMapper.java:605)
at org.springframework.data.mongodb.core.convert.QueryMapper.createPropertyField(QueryMapper.java:152)
at org.springframework.data.mongodb.core.convert.QueryMapper.getMappedObject(QueryMapper.java:113)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1515)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1506)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:532)

When You Make Entity Bean Class You Have #Column Name Where Write The Column Name Which You Declare In To Database And in the intial value you declare any name

Related

null check cant get out of this

guys ı cant get out of this .can you check and infor me about the place where ı should put null check .
this for sharing the post for formality.ı didnt wanna determine the name age and salaray below.
class _Employee {
String? empName;
int? empAge;
int? empSalary;
String get employeeName {
return empName!;
}
void set employeeName(String name) {
this.empName = name;
}
void set employeeAge(int age) {
if (age == null) {
print("please give a number");
} else if (age <= 18) {
print("please give a value number");
this.empAge = age;
}
}
int get employeeAge {
return empAge!;
}
void set employeeSalary(int salary) {
salary <= 0
? print("Salary cannot be less than 0")
: this.empSalary = salary;
}
int get employeeSalary {
return empSalary!;
}
}
void main() {
_Employee emp = _Employee();
emp.employeeName;
emp.employeeAge;
emp.employeeSalary;
print("Employee's Name is : ${emp.employeeName}");
print("Employee's Age is : ${emp.employeeAge}");
print("Employee's Salary is : ${emp.employeeSalary}");
}
You can change the return dataType to nullable, instead of focing with null-assert!.
String? get employeeName {
return empName;
}
Or you can return default value on null case.
String get employeeName {
return empName ?? "Got null on empName";
}
You need to set value like
emp.employeeName = "Test";
Full snippet can be
class _Employee {
String? empName;
int? empAge;
int? empSalary;
String get employeeName {
return empName ?? "Got null on empName";
}
set employeeName(String name) {
empName = name;
}
set employeeAge(int? age) {
if (age == null) {
print("please give a number");
} else if (age <= 18) {
print("please give a value number");
empAge = age;
}
}
int get employeeAge {
return empAge ?? 0;
}
set employeeSalary(int salary) {
salary <= 0 ? print("Salary cannot be less than 0") : empSalary = salary;
}
int get employeeSalary {
return empSalary ?? 0;
}
}
void main() {
_Employee emp = _Employee();
emp.employeeName = "Test";
emp.employeeAge = 12;
emp.employeeSalary;
print("Employee's Name is : ${emp.employeeName}");
print("Employee's Age is : ${emp.employeeAge}");
print("Employee's Salary is : ${emp.employeeSalary}");
}
Find more on dart.dev/guides/language/language-tour

Unity Registeration script not working on 000webhost

I have created a login and registration on unity using php scripts and my database is mysql. Its working fine when I am using phpmyadmine localhost but as soon as I post my scripts on 000webhost .I am unable to insert data through my registration and my login is working fine . please please HELP
PHP SCRIPT
UNTIY CODE
public class Register : MonoBehaviour
{
public GameObject loginAs;
public GameObject username;
public GameObject email;
public GameObject password;
public GameObject confpassword;
public string CurrentMenu = "Login";
public GameObject Message;
private string loginas;
private string Username;
private string Email;
private string Password;
private string ConfPassword;
// private string form;
private bool EmailValid = false;
private string[] Characters = { "a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z", "A",
"B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z","1",
"2","3","4","5","6","7","8","9","0","_","-"};
private string CreateAccountURL = "https://dbanme.000webhostapp.com/Registeration.php";
// Use this for initialization
void Start()
{
}
IEnumerator CreateAccount()
{
//This is what sends messages to out php script
WWWForm Form = new WWWForm();
//These fields are the variables which we send to out php script
Form.AddField("loginas", loginas);
Form.AddField("Username", Username);
Form.AddField("Email", Email);
Form.AddField("Password", Password);
Form.AddField("ConfPassword", ConfPassword);
WWW CreateAccountWWW = new WWW(CreateAccountURL, Form);
//Wait for php to send something back to php
yield return CreateAccountWWW;
string response = CreateAccountWWW.text;
if (CreateAccountWWW.error != null)
{
string CreateAccountReturn = CreateAccountWWW.text;
if (response.Contains("failed"))
{
Message.GetComponent<Text>().text = response;
//CurrentMenu = "Login";
}
}
else
{
Message.GetComponent<Text>().text = response;
SceneManager.LoadScene("Login");
}
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
if (username.GetComponent<InputField>().isFocused)
{
email.GetComponent<InputField>().Select();
}
if (email.GetComponent<InputField>().isFocused)
{
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused)
{
confpassword.GetComponent<InputField>().Select();
}
}
}
public void gotologin()
{
SceneManager.LoadScene("Login");
}
//this is the register just telling
public void ButtonRegister()
{
loginas = loginAs.GetComponentInChildren<Text>().text;
if (loginas == "Teacher")
{
loginas = "teacher";
// SceneManager.LoadScene("Login");
}
else if (loginas == "Student")
{
loginas = "student";
// SceneManager.LoadScene("Login");
}
Username = username.GetComponent<InputField>().text;
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confpassword.GetComponent<InputField>().text;
if (Username != System.String.Empty && Email != System.String.Empty && Password != System.String.Empty && ConfPassword != System.String.Empty)
{
emailvalidation();
//StartCoroutine(CreateAccount());
}
}
void emailvalidation()
{
bool SW = false;
bool EW = false;
for (int j = 0; j < Characters.Length; j++)
{
if (Email.StartsWith(Characters[j]))
{
SW = true;
}
}
for (int j = 0; j < Characters.Length; j++)
{
if (Email.EndsWith(Characters[j]))
{
EW = true;
}
}
if (SW == true && EW == true)
{
EmailValid = true;
}
else
{
EmailValid = false;
}
bool UN = false;
bool EM = false;
bool PW = false;
bool CPW = false;
if (Username == "")
{
Debug.LogWarning("Username field Empty");
}
if (Email != "")
{
//emailvalidation();
if (EmailValid == true)
{
if (Email.Contains("#"))
{
if (Email.Contains("."))
{
Debug.Log("Form upload complete!");
EM = true;
SceneManager.LoadScene("Login");
StartCoroutine(CreateAccount());
}
else
{
Debug.LogWarning("Email Does not Contain a . sign ");
}
}
else
{
Debug.LogWarning("Email does not contain an # sign");
}
}
else
{
Debug.LogWarning("Email is Incorrect3");
}
}
else
{
Debug.LogWarning("Email field Empty");
}
if (Password != "")
{
if (Password.Length > 5)
{
PW = true;
}
else
{
Debug.LogWarning("Password Must be Atleast 6 Characters long");
}
}
else
{
Debug.LogWarning("Passowrd Field Empty");
}
if (ConfPassword != "")
{
if (ConfPassword == Password)
{
CPW = true;
}
else
{
Debug.LogWarning("Passwords dont Match");
}
}
else
{
Debug.LogWarning("Confirm Password Field is Empty");
}
if (UN == true && EM == true && PW == true && CPW == true)
{
bool Clear = true;
int i = 1;
foreach (char c in Password)
{
if (Clear)
{
Password = "";
Clear = false;
}
i++;
char Encrypted = (char)(c * i);
Password += Encrypted.ToString();
}
username.GetComponent<InputField>().text = "";
email.GetComponent<InputField>().text = "";
password.GetComponent<InputField>().text = "";
confpassword.GetComponent<InputField>().text = "";
}
}
}

web.api only serializing hidden fields

I'm experiencing a strange behaviour.
My web.api is returning only hiddenfields from my ObjectCollection on a GET request.
This is my controller:
// GET: api/UserDocuments
[Route("api/UserDocuments/User/{userName}")]
public List<DocIndex> Get(string userName)
{
User usuari = Humanisme.User.LoadByUserName(userName);
List<DocIndex> resposta = DocumentCollection.LoadIndexPerUsuari(usuari);
return resposta;
}
And this is the object as it gets generated from the BOM:
namespace Humanisme
{
using CodeFluent.Runtime;
using CodeFluent.Runtime.Utilities;
// CodeFluent Entities generated (http://www.softfluent.com). Date: Tuesday, 01 March 2016 11:52.
// Build:1.0.61214.0820
[System.CodeDom.Compiler.GeneratedCodeAttribute("CodeFluent Entities", "1.0.61214.0820")]
[System.SerializableAttribute()]
[System.ComponentModel.DataObjectAttribute()]
public partial class DocIndex : CodeFluent.Runtime.ICodeFluentLightEntity
{
private int _id = -1;
[System.NonSerializedAttribute()]
private Humanisme.User _user = ((Humanisme.User)(null));
private string _lat = default(string);
private string _lon = default(string);
private string _etapaVital = default(string);
private string _solvencia = default(string);
private int _valoracio = CodeFluentPersistence.DefaultInt32Value;
private System.DateTime _data = CodeFluentPersistence.DefaultDateTimeValue;
private string _nom = default(string);
public DocIndex()
{
}
[System.ComponentModel.DefaultValueAttribute(((int)(-1)))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=false, Type=typeof(int))]
[System.ComponentModel.DataObjectFieldAttribute(true)]
public int Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public Humanisme.User User
{
get
{
return this._user;
}
set
{
this._user = value;
}
}
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Lat
{
get
{
return this._lat;
}
set
{
this._lat = value;
}
}
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Lon
{
get
{
return this._lon;
}
set
{
this._lon = value;
}
}
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string EtapaVital
{
get
{
return this._etapaVital;
}
set
{
this._etapaVital = value;
}
}
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Solvencia
{
get
{
return this._solvencia;
}
set
{
this._solvencia = value;
}
}
[System.ComponentModel.DefaultValueAttribute(CodeFluentPersistence.DefaultInt32Value)]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=false, Type=typeof(int))]
public int Valoracio
{
get
{
return this._valoracio;
}
set
{
this._valoracio = value;
}
}
[System.Xml.Serialization.XmlElementAttribute(IsNullable=false, Type=typeof(System.DateTime))]
public System.DateTime Data
{
get
{
return this._data;
}
set
{
this._data = value;
}
}
[System.ComponentModel.DefaultValueAttribute(default(string))]
[System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Type=typeof(string))]
public string Nom
{
get
{
return this._nom;
}
set
{
this._nom = value;
}
}
protected virtual void ReadRecord(System.Data.IDataReader reader, CodeFluent.Runtime.CodeFluentReloadOptions options)
{
if ((reader == null))
{
throw new System.ArgumentNullException("reader");
}
if ((((options & CodeFluent.Runtime.CodeFluentReloadOptions.Properties)
== 0)
== false))
{
this._id = CodeFluentPersistence.GetReaderValue(reader, "Id", ((int)(-1)));
this._user = new Humanisme.User();
CodeFluent.Runtime.CodeFluentLightWeightPersistence.ReadRecord(reader, this._user, null, new CodeFluent.Runtime.Utilities.Pair<string, string>("Id", "User_Id"));
this._lat = CodeFluentPersistence.GetReaderValue(reader, "Lat", ((string)(default(string))));
this._lon = CodeFluentPersistence.GetReaderValue(reader, "Lon", ((string)(default(string))));
this._etapaVital = CodeFluentPersistence.GetReaderValue(reader, "EtapaVital", ((string)(default(string))));
this._solvencia = CodeFluentPersistence.GetReaderValue(reader, "Solvencia", ((string)(default(string))));
this._valoracio = CodeFluentPersistence.GetReaderValue(reader, "Valoracio", ((int)(CodeFluentPersistence.DefaultInt32Value)));
this._data = CodeFluentPersistence.GetReaderValue(reader, "Data", ((System.DateTime)(CodeFluentPersistence.DefaultDateTimeValue)));
this._nom = CodeFluentPersistence.GetReaderValue(reader, "Nom", ((string)(default(string))));
}
}
void CodeFluent.Runtime.ICodeFluentLightEntity.ReadRecord(System.Data.IDataReader reader)
{
this.ReadRecord(reader, CodeFluent.Runtime.CodeFluentReloadOptions.Default);
}
}
}
Calling the web.api get method returns this JSON:
[
{
"_id": 1,
"_lat": null,
"_lon": null,
"_etapaVital": null,
"_solvencia": null,
"_valoracio": 0,
"_data": "0001-01-01T00:00:00",
"_nom": null
}
]
Serializer (from WebApiConfig.cs)
JsonMediaTypeFormatter jsonFormatter = (JsonMediaTypeFormatter)config.Formatters.FirstOrDefault(f => f is JsonMediaTypeFormatter);
if (jsonFormatter != null)
{
// jsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Include;
jsonFormatter.UseDataContractJsonSerializer = true;
}
The classes generated by CodeFluent Entities are decorated by SerializableAttribute. This attribute changes the way Json.NET serialize or deserialize the object. You can configure Json.NET to ignore this attribute:
JsonMediaTypeFormatter jsonFormatter = (JsonMediaTypeFormatter)config.Formatters.FirstOrDefault(f => f is JsonMediaTypeFormatter);
if (jsonFormatter != null)
{
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableAttribute = true
};
}
http://james.newtonking.com/archive/2012/04/11/json-net-4-5-release-2-serializable-support-and-bug-fixes
Json.NET now detects types that have the SerializableAttribute and serializes all the fields on that type, both public and private, and ignores the propertie
So you can use the service producer which will add the DataMemberAttribute or you can use the Json.NET Aspect to automatically add specific Json.NET attribute: Newtonsoft.Json.JsonObjectAttribute and Newtonsoft.Json.JsonPropertyAttribute.
Finally found!
When dealing with web.api never, never, never forget to add the "Service Producer" subproducer attached to the standard BOM Producer in your model project.
You'll never notice any problem but at serializing when no attributes will be processed and only hidden properties (object fields) will be serialized at output.
Sorry for the nerd mistake, happy for the lesson learned.
Again, thanks Meziantou. You would never figured where the issue was originated, mainly because I didn't carried all the project details to the question.

How to store user sql where clause, and how to apply it on a select?

I am using JPA / Eclipselink / PostgreSQL within my application.
I have a model that list some data, and I would like to let the user of the application to create his own where clause parameters.
How can I store theses parameters ? as plain sql string ?
Then how can I apply the where clause ? as a simple string concatenation ? (I don't like this idea at all).
Bests regards.
Ok, so I solved my problem.
For information : I have created a recursive JSON representation of every where clause parameters possibility.
And I have created a query using criteria api by decoding the pojo structure from json.
The json class look like that :
public class JSonSearchCriteria
{
public static enum CriteriaType
{
asc,
desc,
count,
countDistinct,
and,
or,
not,
equal,
notEqual,
between,
gt,
ge,
lt,
le,
like,
notLike;
}
#Expose
public CriteriaType type;
#Expose
public List<JSonSearchCriteria> sub;
#Expose
public String what = null;
#Expose
public List<Integer> integerValue = null;
#Expose
public List<Long> longValue = null;
#Expose
public List<Boolean> booleanValue = null;
#Expose
public List<String> stringValue = null;
#Expose
public List<DateTime> datetimeValue = null;
public JSonSearchCriteria()
{
}
public JSonSearchCriteria(final CriteriaType type)
{
this.type = type;
}
public JSonSearchCriteria(final CriteriaType type, final String what)
{
this(type);
this.what = what;
}
public JSonSearchCriteria(final CriteriaType type, final String what, final String... values)
{
this(type, what);
for(final String value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Long... values)
{
this(type, what);
for(final Long value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Integer... values)
{
this(type, what);
for(final Integer value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final DateTime... values)
{
this(type, what);
for(final DateTime value : values)
{
value(value);
}
}
public void add(final JSonSearchCriteria subCriteria)
{
if(sub == null)
{
sub = new ArrayList<>();
}
sub.add(subCriteria);
}
public void value(final String value)
{
if(stringValue == null)
{
stringValue = new ArrayList<>();
}
stringValue.add(value);
}
public void value(final Long value)
{
if(longValue == null)
{
longValue = new ArrayList<>();
}
longValue.add(value);
}
public void value(final Integer value)
{
if(integerValue == null)
{
integerValue = new ArrayList<>();
}
integerValue.add(value);
}
public void value(final DateTime value)
{
if(datetimeValue == null)
{
datetimeValue = new ArrayList<>();
}
datetimeValue.add(value);
}
#SuppressWarnings(
{
"unchecked", "rawtypes"
})
#Transient
public Predicate buildPredicate(final CriteriaBuilder builder, final Root<Record> root, Join<Record, RecordInfo> infos)
{
switch(type)
{
case and:
case or:
final Predicate[] preds = new Predicate[sub.size()];
int cpt = 0;
for(final JSonSearchCriteria s : sub)
{
preds[cpt] = s.buildPredicate(builder, root, infos);
cpt++;
}
if(type == CriteriaType.and)
{
return builder.and(preds);
}
else if(type == CriteriaType.or)
{
return builder.or(preds);
}
break;
case equal:
case lt:
case gt:
case between:
final Path p;
if(what.startsWith("infos."))
{
p = infos.get(what.substring(6));
}
else
{
p = root.get(what);
}
if(stringValue != null && !stringValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, stringValue.get(0));
}
}
else if(longValue != null && !longValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, longValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, longValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, longValue.get(0));
}
}
else if(integerValue != null && !integerValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, integerValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, integerValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, integerValue.get(0));
}
}
else if(booleanValue != null && !booleanValue.isEmpty())
{
return builder.equal(p, booleanValue.get(0));
}
else if(datetimeValue != null && !datetimeValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, datetimeValue.get(0));
}
else if(type == CriteriaType.between && datetimeValue.size() > 1)
{
return builder.between(p, datetimeValue.get(0), datetimeValue.get(1));
}
}
break;
}
System.err.println(type + " - not implemented");
return null;
}
}
And it is used like that :
final SearchTemplate templ = DBHelper.get(SearchTemplate.class, 100);
final Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeJsonAdapter()).create();
final JSonSearchCriteria crits = gson.fromJson(templ.getTemplate(), JSonSearchCriteria.class);
final CriteriaBuilder critBuilder = DBHelper.getInstance().em().getCriteriaBuilder();
final CriteriaQuery<Record> critQuery = critBuilder.createQuery(Record.class);
final Root<Record> root = critQuery.from(Record.class);
final Join<Record, RecordInfo> infos = root.join("infos");
critQuery.where(crits.buildPredicate(critBuilder, root, infos));
final TypedQuery<Record> query = DBHelper.getInstance().em().createQuery(critQuery);
final List<Record> result = query.getResultList();
for(final Record rec : result)
{
System.err.println(rec.toString());
}

Replace bookmark contents in Word using OpenXml

I can't find any working code examples for replacing bookmark contents. The code should be able to handle both the case replace empty bookmark and replace bookmark with preexisting content.
For example: If I have this text in a Word document:
"Between the following periods comes Bookmark1.. Between next periods comes Bookmark2.."
and I want to insert the text "BM1" between the first periods, and "BM2" between the next.
After the first replacement run, the replacements are inserted correctly.
But after the next replacement run, all of the text on the line after Bookmark1 gets deleted, and then the replacement for Bookmark2 gets inserted.
This is my c# code:
var doc = WordprocessingDocument.Open(#"file.docx", true);
public static Dictionary<string, wd.BookmarkStart> FindAllBookmarksInWordFile(WordprocessingDocument file)
{
var bookmarkMap = new Dictionary<String, wd.BookmarkStart>();
foreach (var headerPart in file.MainDocumentPart.HeaderParts)
{
foreach (var bookmarkStart in headerPart.RootElement.Descendants<wd.BookmarkStart>())
{
if (!bookmarkStart.Name.ToString().StartsWith("_"))
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
}
foreach (var bookmarkStart in file.MainDocumentPart.RootElement.Descendants<wd.BookmarkStart>())
{
if (!bookmarkStart.Name.ToString().StartsWith("_"))
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
return bookmarkMap;
}
/*extension methods*/
public static bool IsEndBookmark(this OpenXmlElement element, BookmarkStart startBookmark)
{
return IsEndBookmark(element as BookmarkEnd, startBookmark);
}
public static bool IsEndBookmark(this BookmarkEnd endBookmark, BookmarkStart startBookmark)
{
if (endBookmark == null)
return false;
return endBookmark.Id.Value == startBookmark.Id.Value;
}
/* end of extension methods */
public static void SetText(BookmarkStart bookmark, string value)
{
RemoveAllTexts(bookmark);
bookmark.Parent.InsertAfter(new Run(new Text(value)), bookmark);
}
private static void RemoveAllTexts(BookmarkStart bookmark)
{
if (bookmark.ColumnFirst != null) return;
var nextSibling = bookmark.NextSibling();
while (nextSibling != null)
{
if (nextSibling.IsEndBookmark(bookmark) || nextSibling.GetType() == typeof(BookmarkStart))
break;
foreach (var item in nextSibling.Descendants<Text>())
{
item.Remove();
}
nextSibling = nextSibling.NextSibling();
}
}
I have looked around a long time for a general solution.
Any help is appreciated! -Victor
Maybe this can help you
first:delete bookmarkContent
second:find bookMark => insert value
public static void InsertTest1(WordprocessingDocument doc, string bookMark, string txt)
{
try
{
RemoveBookMarkContent(doc, bookMark);
MainDocumentPart mainPart = doc.MainDocumentPart;
BookmarkStart bmStart = findBookMarkStart(doc, bookMark);
if (bmStart == null)
{
return;
}
Run run = new Run(new Text(txt));
bmStart.Parent.InsertAfter<Run>(run, bmStart);
}
catch (Exception c)
{
//not Exception
}
}
public static void RemoveBookMarkContent(WordprocessingDocument doc, string bmName)
{
BookmarkStart bmStart = findBookMarkStart(doc, bmName);
BookmarkEnd bmEnd = findBookMarkEnd(doc, bmStart.Id);
while (true)
{
var run = bmStart.NextSibling();
if (run == null)
{
break;
}
if (run is BookmarkEnd && (BookmarkEnd)run == bmEnd)
{
break;
}
run.Remove();
}
}
private static BookmarkStart findBookMarkStart(WordprocessingDocument doc, string bmName)
{
foreach (var footer in doc.MainDocumentPart.FooterParts)
{
foreach (var inst in footer.Footer.Descendants<BookmarkStart>())
{
if (inst.Name == bmName)
{
return inst;
}
}
}
foreach (var header in doc.MainDocumentPart.HeaderParts)
{
foreach (var inst in header.Header.Descendants<BookmarkStart>())
{
if (inst.Name == bmName)
{
return inst;
}
}
}
foreach (var inst in doc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
if (inst is BookmarkStart)
{
if (inst.Name == bmName)
{
return inst;
}
}
}
return null;
}
This code works but not when the bookmark is placed within a field/formtext (a gray box).
private static void SetNewContents(wd.BookmarkStart bookmarkStart, string text)
{
if (bookmarkStart.ColumnFirst != null) return;
var itemsToRemove = new List<OpenXmlElement>();
var nextSibling = bookmarkStart.NextSibling();
while (nextSibling != null)
{
if (IsEndBookmark(nextSibling, bookmarkStart))
break;
if (nextSibling is wd.Run)
itemsToRemove.Add(nextSibling);
nextSibling = nextSibling.NextSibling();
}
foreach (var item in itemsToRemove)
{
item.RemoveAllChildren();
item.Remove();
}
bookmarkStart.Parent.InsertAfter(new wd.Run(new wd.Text(text)), bookmarkStart);
}