I am having a real deal that I can't get over with. I am using ScheduleComponent in ReactJS to create a calendar and some appointments.
Here is my component which uses a ScheduleComponent. I have no idea how can I update some data from my API.
const CalendarComponent = () => {
const [schedules, setSchedules] = useState([]);
const dataManager = new DataManager({
url: `http://localhost:8080/schedule/calendar`,
crudUrl: `http://localhost:8080/schedule/updateCalendar`,
adaptor: new ODataV4Adaptor,
crossDomain: true
});
return(
<section className="adminSection">
<ScheduleComponent width='100%' currentView='Month' eventSettings={{dataSource: dataManager}}>
<ViewsDirective>
<ViewDirective option='Day'/>
<ViewDirective option='Week'/>
<ViewDirective option='Month'/>
<ViewDirective option='Agenda'/>
<ViewDirective option='MonthAgenda'/>
<ViewDirective option='TimelineDay'/>
<ViewDirective option='TimelineMonth'/>
</ViewsDirective>
<Inject services={[Day, Week, WorkWeek, Month, Agenda, MonthAgenda, TimelineViews, TimelineMonth]} />
</ScheduleComponent>
</section>
);
};
export default CalendarComponent;
And there is my Java ScheduleResponse for getting apropriate data from database.
public record ScheduleResponse(
#JsonProperty("StartTime") LocalDateTime startTime,
#JsonProperty("EndTime") LocalDateTime endTime,
#JsonProperty("Subject") String subject
) {
public static ScheduleResponse fromSchedule(Schedule schedule){
return new ScheduleResponse(
schedule.getDateTimeFrom(),
schedule.getDateTimeTo(),
schedule.getSubject());
}
}
I would like to know how can I refer to a single data from dataSource using this component, and I have no clue.
We suggest you use addParams of Query to handle the filtering in server and for the same we have prepared a sample below.
Service: https://www.syncfusion.com/downloads/support/directtrac/general/ze/Service-294388409
Sample: https://stackblitz.com/edit/add-param-front-end?file=index.js
In the above sample based on Subject field we have filtered the data from back end.
UG Link: https://ej2.syncfusion.com/react/documentation/schedule/data-binding/#passing-additional-parameters-to-the-server
Client side code
public onCheckBoxChange(): void {
let predicate: any;
const checkBoxes: CheckBox[] = [this.confirmObj];
checkBoxes.forEach((checkBoxObj: CheckBox) => {
if (checkBoxObj.checked) {
predicate = predicate ? predicate + ',' + checkBoxObj.label : checkBoxObj.label;
}
});
this.scheduleObj.eventSettings.query = new Query().addParams(
'Subject',
predicate ? predicate : ''
);
}
Server side code:
public JsonResult LoadData(Params param) // Here we get the Start and End Date and based on that can filter the data and return to Scheduler
{
DateTime start = param.StartDate;
DateTime end = param.EndDate;
var subject = param.Subject;
var data = db.ScheduleEventDatas.Where(app => (app.StartTime >= start && app.StartTime <= end) || (app.RecurrenceRule != null && app.RecurrenceRule != "")).ToList(); // Here filtering the events based on the start and end date value.
if (param.Subject != null)
{
// Filter data based on additional parameter
data = db.ScheduleEventDatas.Where(app => (app.StartTime >= start && app.StartTime <= end && app.Subject == subject) || (app.RecurrenceRule != null && app.RecurrenceRule != "")).ToList();
}
return Json(data, JsonRequestBehavior.AllowGet);
}
public class Params
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Subject { get; set; }
}
Related
Hope you are all healthy!
I have a situation in which I have a backend application that exposes a rest api to create data related to expense reporting. The main entity that this API allows to be created is an "Expense Report" which has other entities related to it, such as the country on which the expenses took place and the user that created it.
Thing is, my controller receives a DTO, converts it into a JPA entity and then sends it to the service class. In my service class, I have to check if a related entity field like the username for User or the country code for Country, and then go into the corresponding entity repository and get the corresponding entity.
public ExpenseReport save(ExpenseReport expenseReport) {
if (expenseReport.getId() != null) {
expenseReportRepository.findById(expenseReport.getId())
.ifPresent(currentObject -> {
expenseReport.setId(currentObject.getId());
expenseReport.setVersion(currentObject.getVersion());
});
}
if (expenseReport.getUser() != null && expenseReport.getUser().getUsername() != null) {
String username = expenseReport.getUser().getUsername();
userRepository.findByUsername(username)
.ifPresentOrElse(user -> {
expenseReport.setUser(user);
},
() -> {
throw new InvalidDataException(User.class, "username", username);
});
}
if (expenseReport.getCountry() != null && expenseReport.getCountry().getCode() != null) {
String countryCode = expenseReport.getCountry().getCode();
countryRepository.findByCode(countryCode)
.ifPresentOrElse(country -> {
expenseReport.setCountry(country);
},
() -> {
throw new InvalidDataException(Country.class, "countryCode", countryCode);
});
}
for (ExpenseItem expenseItem : expenseReport.getExpenses()) {
if (expenseItem.getCurrency() != null && expenseItem.getCurrency().getCode() != null) {
String currencyCode = expenseItem.getCurrency().getCode();
currencyRepository.findByCode(currencyCode)
.ifPresentOrElse(currency -> {
expenseItem.setCurrency(currency);
},
() -> {
throw new InvalidDataException(Currency.class, "currencyCode", currencyCode);
});
}
if (expenseItem.getExpenseCity() != null && expenseItem.getExpenseCity().getCode() != null) {
String expenseCityCode = expenseItem.getExpenseCity().getCode();
cityRepository.findByCode(expenseCityCode)
.ifPresentOrElse(city -> {
expenseItem.setExpenseCity(city);
},
() -> {
throw new InvalidDataException(City.class, "expenseCityCode", expenseCityCode);
});
}
if (expenseItem.getCategory() != null && expenseItem.getCategory().getCode() != null) {
String categoryCode = expenseItem.getCategory().getCode();
categoryRepository.findByCode(categoryCode)
.ifPresentOrElse(expenseCategory -> {
expenseItem.setCategory(expenseCategory);
},
() -> {
throw new InvalidDataException(ExpenseCategory.class, "expenseCategoryCode", categoryCode);
});
}
}
return expenseReportRepository.save(expenseReport);
}
My question is, is this the best way to do this? I feel that if the object gets too complex, I'll have to create this super huge save method.
Does JPA offer a better solution to this? I was thinking also to change the parameterized types (like country, city, state) to use the code itself as it's primary key, rather than an auto-generated id.
Regards.
I'm trying to figure aout, why my firestore function is always returning null.
Here is my firestore function:
exports.isUserOnListFunction = functions.https.onCall(async (data, context) => {
const userID = context.auth.uid;
const userEmail = context.auth.token.email;
const atIndex = userEmail.indexOf('#');
const dotIndex = userEmail.indexOf('.');
var userName = userEmail.slice(0, dotIndex);
var userSurname = userEmail.slice(dotIndex+1, atIndex);
userName = capitalizeFirstLetter(userName);
userSurname = capitalizeFirstLetter(userSurname);
return db.collection('allowed_users')
.where("name", "==", userName)
.where("surname", "==", userSurname)
.get().then(snap => {
if (!snap.empty) {
db.collection("users").doc(userID).update({
onList: true
});
return {onList : true};
}
}).catch(()=>{
console.log("Some error!")
})
});
and here is my android (java) function calling firestore function:
private Task<String> isUserOnList(){
return mFunctions
.getHttpsCallable("isUserOnListFunction")
.call()
.continueWith(new Continuation<HttpsCallableResult, String>() {
#Override
public String then(#NonNull Task<HttpsCallableResult> task) throws Exception {
String result = (String) task.getResult().getData();
System.out.println(result);
return result;
}
});
}
Could someone please tell me what im doing wrong?
According to this doc
If returned is JS object with keys and values, which I suppose it is in this situation, getData() returns Map object.
I think task.getResult().getData().toString() method should be used to convert it (instead of (String) task.getResult().getData();)
I would expect exception thrown, but maybe you have caught it in other parts of code not posted here.
Hope this will helps you.
I'm implementing an API that uses an update_mask of type Field Mask to specify the fields that should be updated on a resource.
The API is similar to:
rpc UpdateBook(UpdateBookRequest) returns (Book)
message UpdateBookRequest {
Book book=1;
google.protobuf.FieldMask update_mask = 2;
}
Currently the code looks something like:
override suspend fun updateBook(request: UpdateBookRequest): Book {
if (!FieldMaskUtil.isValid(Book::class.java, request.updateMask)) {
throwStatusRuntimeException {
code = Code.INVALID_ARGUMENT_VALUE
message = "Invalid field mask"
}
}
request.book.let { book ->
request.updateMask.pathsList.let { updateMask ->
var displayName: BookDisplayNameValue? = null
var description: BookDescriptionValue? = null
if (updateMask.contains(BookFields.DISPLAY_NAME_FIELD)) {
displayName = BookDisplayNameValue(book.displayName)
}
if (updateMask.contains(BookFields.DESCRIPTION_FIELD)) {
description = BookDescriptionValue(book.description.ifBlank { null })
}
bookService.update(
bookId = BookIdValue(book.name),
displayName = displayName,
description = description,
)
}
}
//...
}
Which, although it works, is pretty horrendous for maintenance as more fields are added.
Are there any best practices as to how to implement this behaviour on the server (Kotlin + Spring framework + GRPC) that can reduce the amount of boilerplate.
We are working for internationalizing an old application with some dirty code. For example, we have an object DTO InstrumentDto:
private String label;
private Quotation quotation;
private ExprQuote quoteExp;
public String getTypeCouponCouru() {
if (this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_CPN_INCLUS)
|| this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_INTERET)) {
return "Coupon attaché";
} else if(this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_PIED_CPN)){
return "Coupon détaché";
} else {
return "";
}
}
public String getFormattedLabel() {
StringBuilder formattedLabel = new StringBuilder(this.label);
Quotation quote = this.quotation;
if (this.quotation != null) {
formattedLabel.append(" ");
formattedLabel.append(FormatUtil.formatDecimal(this.quotation.getCryQuote());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(" %");
} else {
formattedLabel.append(" ");
formattedLabel.append(this.quotation.getCurrency().getCode());
}
formattedLabel.append(" le ");
formattedLabel.append(DateUtil.formatDate(this.quotation.getValoDate()));
}
return formattedLabel.toString();
}
Then, those methods are used on JSPs. For example for getFormattedLabel(), we have :
<s:select name = "orderUnitaryForm.fieldInstrument"
id = "fieldInstrument"
list = "orderUnitaryForm.instrumentList"
listKey = "id"
listValue = "formattedLabel" />
IMO, the first method doesn't have its place on the DTO. We are expecting the view to manage the label to print. And in this view (the JSP), no problem to translate those words.
Additionally, this method is just used in 2 JSP. Not a problem to "repeat" the conditional tests.
But it's more difficult for getFormattedLabel() : this method is used in a lot of JSP, and the building of the formatted label is "complicated". And it's not possible having the i18n service in the DTO.
So how to do that ?
Your code in getFormattedLabel() seems to be business logic.
A DTO is a simple object without any complex test/behavior (see wiki definition).
IMO, you should move this chunk of code to your Action and split your *.properties file like this:
Your *.properties:
message1= {0} % le {1}
message2= {0} {1} le {2}
Your Action:
public MyAction extends ActionSupport {
public String execute(){
//useful code here
InstrumentDto dto = new InstrumentDto();
StringBuilder formattedLabel = new StringBuilder(label);
if (this.quotation != null) {
String cryQuote = FormatUtil.formatDecimal(this.quotation.getCryQuote());
String date = DateUtil.formatDate(this.quotation.getValoDate());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(getText("message1", new String[] { cryQuote, date }));
} else {
String cryCode = this.quotation.getCurrency().getCode();
formattedLabel.append(getText("message2", new String[] { cryQuote, cryCode, date }));
}
}
dto.setFormattedLabel(formattedLabel);
}
}
Hope this will help ;)
I am checking for a change in value of a date. The ValueChangeHandler is recognising a date (e.g. 1/5/2014 is updated to the DB when entered). However, when I delete a date it is not recognised (i.e., the DB is not updated to null - I have tried Backspace, highlight and Del, overtyping with spaces). I then entered a new date (2/5/2014) and this was updated to the DB. Any ideas as to why this code does not recognise that I have removed the date please.
Regards,
Glyn
I have updated this with the code suggested by Braj. Unfortunately this did not work.
final DateBox awardedDate = new DateBox();
awardedDate.setFormat(new DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
awardedDate.setValue(ymAwards.getCaAwardedDate());
awardedDate.setWidth("75px");
//Add change handler for the awarded date.
//Only a Leader or Administrator can update the date
if (accountLevel.equals("Leader") || accountLevel.equals("Administrator")) {
awardedDate.addValueChangeHandler(new ValueChangeHandler<java.util.Date>() {
int pog = 0;
public void onValueChange(ValueChangeEvent<java.util.Date> event) {
if (pog == 0) {
pog++;
Window.alert("First change hadler.");
//Check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateAwarded = awardedDate.getValue() == null ? null : new java.sql.Date(awardedDate.getValue().getTime());
AsyncCallback<YMAwards> callback = new YMAwardedDateHandler<YMAwards>();
rpc.updateYMAwarded(youthMemberID, returnAwID, sqlDateAwarded, callback);
}else{
pog = 0;
}
}
});
awardedDate.getTextBox().addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (event.getValue() == null) {
Window.alert("Second change hadler.");
//Check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateAwarded = awardedDate.getValue() == null ? null : new java.sql.Date(awardedDate.getValue().getTime());
AsyncCallback<YMAwards> callback = new YMAwardedDateHandler<YMAwards>();
rpc.updateYMAwarded(youthMemberID, returnAwID, sqlDateAwarded, callback);
}
}
});
}
Add this line:
awardDate.setFireNullValues(true);
This was added in GWT 2.5.
Try this one also
final DateBox dateBox = new DateBox();
dateBox.getTextBox().addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (dateBox.getValue() == null) {
System.out.println("date value is empty");
// your code here
}
}
});
output:
date value is empty
DateBox#addValueChangeHandler() fires when there is any change in date via date picker.
You can check the value in text box using TextBox#addValueChangeHandler().