Unity Registeration script not working on 000webhost - unity3d

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 = "";
}
}
}

Related

my code not complete for where contact number

How to fix code my code flutter and use plugin
filterContacts() {
setState(() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere(
(contact) {
String searchTerm = searchController.text.toLowerCase().trim();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toString().toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
var phone = contact.phones.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, orElse: () => null);
return phone != null;
},
);
contactsFiltered = _contacts;
}
});
}
Flutter code How to fix code my code flutter and use plugin contacts_service,
this image is about a problem
contact.phones can be null, in this you need to check its value 1st then proceed,
you can use contact.phones?.firstWhere to handle this situation or
If you're sure it will have value, you can also do contact.phones!.firstWhere but I don't recommend this. You don't need to use orElse you want to pass null,
Item? phone = contact.phones?.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, );
You can learn more about ?. !...
[how to fix now]
error code not complete
filterContacts() {
setState(() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere(
(contact) {
String searchTerm = searchController.text.toLowerCase().trim();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toString().toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
Item? phone = contact.phones?.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn);
return phnFlattened.contains(searchTermFlatten);
}, );
return phone != null;
},
);
contactsFiltered = _contacts;
}
});
}

opcua session was closed by client

I have written the attached OpcUaConnector class for opc-ua connection related activities.
But it is not handling session. For example:
In opc ua configuration disabled the endpoint
In kepserver configuration did runtime > reinitializing
The windows service is throwing:
Source : system.Reactive.Core
InnerException : The session was closed by client
and stopping the windows service, as this error goes unhandled.
Can some one suggest how to handle session in opc-ua?
public class OpcUaConnector
{
private static SimplerAES simplerAES = new SimplerAES();
private DataContainer dataCointainer = null;
private UaTcpSessionChannel channel;
private string opcServerName = string.Empty;
private string opcUserId = string.Empty;
private string opcPassword = string.Empty;
private static ILog LogOpcStore;
private static System.IDisposable token;
private static uint id;
public OpcConnector(ILog Log)
{
IntializeLogOpcStore(Log);
}
private static void IntializeLogOpcStore(ILog Log)
{
LogOpcStore = Log;
}
public async Task OpenOpcConnection()
{
try
{
if ((!string.IsNullOrEmpty(this.opcServerName) & (this.opcServerName != AppMain.MyAppSettings.OpcServer)) ||
(!string.IsNullOrEmpty(this.opcUserId) & (this.opcUserId != AppMain.MyAppSettings.OpcUserId)) ||
(!string.IsNullOrEmpty(this.opcPassword) & (this.opcPassword != AppMain.MyAppSettings.OpcPassword)))
{
await channel.CloseAsync();
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
if (channel==null || (channel != null && (channel.State == CommunicationState.Closed || channel.State == CommunicationState.Faulted)))
{
var appDescription = new ApplicationDescription()
{
ApplicationName = "MyAppName",
ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:MyAppName",
ApplicationType = ApplicationType.Client,
};
//application data won't be deleted when uninstall
var certificateStore = new DirectoryStore(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyAppName", "pki"),
true, true
);
//if the Ethernet cable unplugs or the Wifi drops out,
//you have some timeouts that can keep the session open for a while.
//There is a SessionTimeout (default of 2 min).
this.channel = new UaTcpSessionChannel(
appDescription,
certificateStore,
SignInOpc,
AppMain.MyAppSettings.OpcServer,
null,
options: new UaTcpSessionChannelOptions { SessionTimeout = 120000 });
await channel.OpenAsync();
//LogOpcStore.Info(String.Format("Opc connection sucessful"));
}
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.HResult + " " + ex.Message, "C052");
throw serviceException;
}
}
private static async Task RecursivelyFindNode(UaTcpSessionChannel channel, NodeId nodeid)
{
BrowseRequest browseRequest = new BrowseRequest
{
NodesToBrowse = new BrowseDescription[] { new BrowseDescription { NodeId = nodeid, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } },
};
BrowseResponse browseResponse = await channel.BrowseAsync(browseRequest);
foreach (var rd1 in browseResponse.Results[0].References ?? new ReferenceDescription[0])
{
uint chid = AppMain.MyTagDatabase.GetClientHandleByTag(rd1.DisplayName.ToString());
if (chid > 0)
{
AppMain.MyTagDatabase.UpdateNodeByClientHandle(chid, rd1.NodeId.ToString());
}
await RecursivelyFindNode(channel, ExpandedNodeId.ToNodeId(rd1.NodeId, channel.NamespaceUris));
}
}
public async Task CreateSubscription(DataContainer dc)
{
double curReadingValue;
try
{
dataCointainer = dc;
await RecursivelyFindNode(channel, NodeId.Parse(ObjectIds.RootFolder));
if (AppMain.MyTagDatabase.GetCntTagsNotInOpcServer() == AppMain.MyTagDatabase.GetTagCount())
{
//no need to create subscription
return;
}
//subscription timeout that is the product of PublishingInterval * LifetimeCount:
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest);
id = subscriptionResponse.SubscriptionId;
var itemsToCreate = new MonitoredItemCreateRequest[AppMain.MyTagDatabase.GetTagHavingNodeCount()];
int i = 0;
foreach (var item in AppMain.MyTagDatabase.GetMyTagDatabase())
{
var itemKey = item.Key;
var itemValue = item.Value;
itemsToCreate[i] = new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse(itemValue.NodeId), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = itemKey, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } };
i++;
}
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = itemsToCreate,
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
}
catch (Exception ex)
{
//If the interruption lasts longer than these timeouts then the SessionChannel and Subscriptions will need to be recreated.
channel = null;
FatalServiceException fatalserviceException = new FatalServiceException(ex.Message, "C052");
throw fatalserviceException;
}
}
public async Task DeleteSubscription()
{
try
{
var request = new DeleteSubscriptionsRequest
{
SubscriptionIds = new uint[] { id }
};
await channel.DeleteSubscriptionsAsync(request);
token.Dispose();
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.Message, "C052");
throw serviceException;
}
}
private static async Task<IUserIdentity> SignInOpc(EndpointDescription endpoint)
{
IUserIdentity userIdentity = null;
if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
{
userIdentity = new AnonymousIdentity();
}
else if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
{
var userName = AppMain.MyAppSettings.OpcUserId;
var password = simplerAES.Decrypt(AppMain.MyAppSettings.OpcPassword);
userIdentity = new UserNameIdentity(userName, password);
}
return userIdentity;
}
private void AddDataPointToContainer(int dataType, string source, DateTime SourceTimestampUTC, double value)
{
ConditionValue conditionValue = new ConditionValue();
long timestamp = AppMain.ServerSyncTimeStore.ConvertDateTimeToTimeStampUTC(SourceTimestampUTC);
conditionValue.dataType = dataType;
conditionValue.source = source;
conditionValue.timestamp = timestamp;
conditionValue.SourceTimestampUTC = SourceTimestampUTC;
conditionValue.LocalTime = SourceTimestampUTC.ToLocalTime();
conditionValue.value = value;
//LogOpcStore.Info(String.Format("TagName : {0} SourceTimestampUTC : {1} timestamp : {2} LocalTime : {3} curReadingValue : {4}", source, SourceTimestampUTC, timestamp, SourceTimestampUTC.ToLocalTime(), value));
dataCointainer.AddDataPoint(conditionValue);
}
}
I see you are using the project https://github.com/convertersystems/opc-ua-client.
When a server closes the session and socket (as happens when you reinitialize Kepware) the client receives immediate notification that causes the client channel to fault. A faulted channel cannot be reopened, it should be aborted and a new channel should be created.
I made this standalone test, to show that you may have to catch an exception and recreate the channel and subscription. The point of this test is to subscribe to the CurrentTime node and collect 60 datachanges. The test should last a minute. If you re-init the Kepware server in the middle of the test, the code catches the exception and recreates the channel and subscription.
[TestMethod]
public async Task OpcConnectorTest()
{
var count = 0;
UaTcpSessionChannel channel = null;
while (count < 60)
{
try
{
channel = new UaTcpSessionChannel(
this.localDescription,
this.certificateStore,
new AnonymousIdentity(),
EndpointUrl,
SecurityPolicyUris.None,
loggerFactory: this.loggerFactory);
await channel.OpenAsync();
// create the keep alive subscription.
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false);
var id = subscriptionResponse.SubscriptionId;
var token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
Console.WriteLine($"sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}");
count++;
}
}
});
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = new MonitoredItemCreateRequest[]
{
new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse("i=2258"), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = 12345, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } }
},
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
while (channel.State == CommunicationState.Opened && count < 60)
{
await Task.Delay(1000);
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.GetType()}. {ex.Message}");
}
}
if (channel != null)
{
Console.WriteLine($"Closing session '{channel.SessionId}'.");
await channel.CloseAsync();
}
}
I know this is an old post, but I stumbled upon this problem as well. For those interested:
The problem is related to the subscription(s).
When the following code is run:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
Observable.subscribe() takes multiple arguments. You should include what to do in case of an error. For example:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(
pr => { code to run normally... },
ex => { Log.Info(ex.Message); },
() => { }
);
See http://reactivex.io/documentation/operators/subscribe.html for more information.

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());
}

MongoDB + Spring MVC

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

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);
}