id
int64 22
34.9k
| comment_id
int64 0
328
| comment
stringlengths 2
2.55k
| code
stringlengths 31
107k
| classification
stringclasses 6
values | isFinished
bool 1
class | code_context_2
stringlengths 21
27.3k
| code_context_10
stringlengths 29
27.3k
| code_context_20
stringlengths 29
27.3k
|
---|---|---|---|---|---|---|---|---|
7,893 | 56 | /* ------------------- Poll properties ---------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) { | }
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival); | } else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE: |
7,893 | 57 | /* ------------------- Poll winner -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) { | }
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival); | Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above |
7,893 | 58 | /* ------------------- Priority -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) { | }
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break; | sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE"); |
7,893 | 59 | /* ------------------- RDate -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop)); | }
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop; | sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
} |
7,893 | 60 | /* ------------------- RecurrenceID -------------------- */
// Done above | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO: | if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
} | case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs); |
7,893 | 61 | /* ------------------- RelatedTo -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo(); | case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto); | ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */ |
7,893 | 62 | /* ------------------- RequestStatus -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop); | "RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop); | break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval); |
7,893 | 63 | /* ------------------- Resources -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) { | ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
} | /* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq); |
7,893 | 64 | /* Got some resources */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) { | case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */ | final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break; |
7,893 | 65 | /* ------------------- RRule -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break; | /* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break; | case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval); |
7,893 | 66 | /* ------------------- Sequence -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) { | s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval); | chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */ |
7,893 | 67 | /* ------------------- Status -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval); | break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break; | for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval); |
7,893 | 68 | /* ------------------- Summary -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval); | ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()), | break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID: |
7,893 | 69 | /* ------------------- Transp -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency( | ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu); | /* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) { |
7,893 | 70 | /* ------------------- Uid -------------------- */
/* We did this above */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL: | pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName(); | if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break; |
7,893 | 71 | /* ------------------- Url -------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval); | if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) { | case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) { |
7,893 | 72 | /* ------------------------- x-property --------------------------- */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) { | /* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) { | pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) { |
7,893 | 73 | /* See if this is an x-category that can be
converted to a real category
*/ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP, | if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi + | pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else { |
7,893 | 74 | /* =================== Process sub-components =============== */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) { | pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent(); | }
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) { |
7,893 | 75 | /* Fix up timestamps. */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) { | pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
} | chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear(); |
7,893 | 76 | // created cannot be null now | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod()); | if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null); | if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters. |
7,893 | 77 | /* Remove any recipients and originator
*/ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear(); | chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) { | logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
} |
7,893 | 78 | /* Save a text copy of the entire event as an x-property */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */ | chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE); | chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false); |
7,893 | 79 | /* Remove potentially large values */ | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | /* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) { | processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode())); | ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) { |
7,893 | 80 | // Don't store the entire attachment - we just need the parameters. | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE); | ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString())); | // created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp); |
7,893 | 81 | // Just return notfound as this event is on its override list | public static GetEntityResponse<EventInfo> toEvent(
final IcalCallback cb,
final BwCalendar cal,
final Icalendar ical,
final Component val,
final boolean mergeAttendees) {
final var resp = new GetEntityResponse<EventInfo>();
if (val == null) {
return Response.notOk(resp, failed, "No component supplied");
}
String currentPrincipal = null;
final BwPrincipal principal = cb.getPrincipal();
if (principal != null) {
currentPrincipal = principal.getPrincipalRef();
}
final Holder<Boolean> hasXparams = new Holder<>(Boolean.FALSE);
final int methodType = ical.getMethodType();
String attUri = null;
if (mergeAttendees) {
// We'll need this later.
attUri = cb.getCaladdr(cb.getPrincipal().getPrincipalRef());
}
final String colPath;
if (cal == null) {
colPath = null;
} else {
colPath = cal.getPath();
}
try {
final PropertyList<Property> pl = val.getProperties();
boolean vpoll = false;
boolean event = false;
boolean task = false;
if (pl == null) {
// Empty component
return Response.notOk(resp, failed, "Empty component");
}
final int entityType;
if (val instanceof VEvent) {
entityType = IcalDefs.entityTypeEvent;
event = true;
} else if (val instanceof VToDo) {
entityType = IcalDefs.entityTypeTodo;
task = true;
} else if (val instanceof VJournal) {
entityType = IcalDefs.entityTypeJournal;
} else if (val instanceof VFreeBusy) {
entityType = IcalDefs.entityTypeFreeAndBusy;
} else if (val instanceof VAvailability) {
entityType = IcalDefs.entityTypeVavailability;
} else if (val instanceof Available) {
entityType = IcalDefs.entityTypeAvailable;
} else if (val instanceof VPoll) {
entityType = IcalDefs.entityTypeVpoll;
vpoll = true;
} else {
return Response.error(resp, "org.bedework.invalid.component.type: " +
val.getName());
}
// Get the guid from the component
String guid = null;
final Uid uidp = pl.getProperty(Property.UID);
if (uidp != null) {
testXparams(uidp, hasXparams);
guid = uidp.getValue();
}
if (guid == null) {
/* XXX A guid is required - but are there devices out there without a
* guid - and if so how do we handle it?
*/
return Response.notOk(resp, failed, CalFacadeException.noGuid);
}
/* See if we have a recurrence id */
BwDateTime ridObj = null;
String rid = null;
TimeZone ridTz = null;
final RecurrenceId ridp = pl.getProperty(Property.RECURRENCE_ID);
if (ridp != null) {
testXparams(ridp, hasXparams);
ridObj = BwDateTime.makeBwDateTime(ridp);
if (ridObj.getRange() != null) {
/* XXX What do I do with it? */
logger.warn("TRANS-TO_EVENT: Got a recurrence id range");
}
rid = ridObj.getDate();
}
EventInfo masterEI = null;
EventInfo evinfo = null;
final BwEvent ev;
/* If we have a recurrence id see if we already have the master (we should
* get a master + all its overrides).
*
* If so find the override and use the annnotation or if no override,
* make one.
*
* If no override retrieve the event, add it to our table and then locate the
* annotation.
*
* If there is no annotation, create one.
*
* It's possible we have been sent 'detached' instances of a recurring
* event. This may happen if we are invited to one or more instances of a
* meeting. In this case we try to retrieve the master and if it doesn't
* exist we manufacture one. We consider such an instance an update to
* that instance only and leave the others alone.
*/
/* We need this in a couple of places */
final DtStart dtStart = pl.getProperty(Property.DTSTART);
/*
if (rid != null) {
// See if we have a new master event. If so create a proxy to that event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI == null) {
masterEI = makeNewEvent(cb, chg, entityType, guid, cal);
BwEvent e = masterEI.getEvent();
// XXX This seems bogus
DtStart mdtStart;
String bogusDate = "19980118T230000";
if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + "Z");
} else if (dtStart.getTimeZone() == null) {
mdtStart = new DtStart(bogusDate);
} else {
mdtStart = new DtStart(bogusDate + "Z", dtStart.getTimeZone());
}
setDates(e, mdtStart, null, null, chg);
e.setRecurring(true);
e.addRdate(ridObj);
e.setSuppressed(true);
ical.addComponent(masterEI);
}
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
}
}
*/
/* If this is a recurrence instance see if we can find the master
We only need this because the master may follow the overrides.
*/
if (rid != null) {
// See if we have a new master event. If so create a proxy to this event.
masterEI = findMaster(guid, ical.getComponents());
if (masterEI != null) {
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
}
}
if ((evinfo == null) &&
(cal != null) &&
(cal.getCalType() != BwCalendar.calTypeInbox) &&
(cal.getCalType() != BwCalendar.calTypePendingInbox) &&
(cal.getCalType() != BwCalendar.calTypeOutbox)) {
if (logger.debug()) {
logger.debug("TRANS-TO_EVENT: try to fetch event with guid=" + guid);
}
final GetEntitiesResponse<EventInfo> eisResp =
cb.getEvent(colPath, guid);
if (eisResp.isError()) {
return Response.fromResponse(resp, eisResp);
}
final var eis = eisResp.getEntities();
if (!Util.isEmpty(eis)) {
if (eis.size() > 1) {
// DORECUR - wrong again
return Response.notOk(resp, failed,
"More than one event returned for guid.");
}
evinfo = eis.iterator().next();
}
if (logger.debug()) {
if (evinfo != null) {
logger.debug("TRANS-TO_EVENT: fetched event with guid");
} else {
logger.debug("TRANS-TO_EVENT: did not find event with guid");
}
}
if (evinfo != null) {
if (rid != null) {
// We just retrieved it's master
masterEI = evinfo;
masterEI.setInstanceOnly(true);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
ical.addComponent(masterEI);
} else if (methodType == ScheduleMethods.methodTypeCancel) {
// This should never have an rid for cancel of entire event.
evinfo.setInstanceOnly(evinfo.getEvent().getSuppressed());
} else {
// Presumably sent an update for the entire event. No longer suppressed master
evinfo.getEvent().setSuppressed(false);
}
} else if (rid != null) {
/* Manufacture a master for the instance */
masterEI = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
final BwEvent e = masterEI.getEvent();
// XXX This seems bogus
final DtStart mdtStart;
final String bogusDate = "19980118";
final String bogusTime = "T230000";
// Base dtstart on the recurrence id.
final boolean isDateType = ridObj.getDateType();
if (isDateType) {
mdtStart = new DtStart(new Date(bogusDate));
} else if (dtStart.isUtc()) {
mdtStart = new DtStart(bogusDate + bogusTime + "Z");
} else if (ridObj.getTzid() == null) {
mdtStart = new DtStart(bogusDate + bogusTime);
} else {
mdtStart = new DtStart(bogusDate + bogusTime,
Timezones.getTz(ridObj.getTzid()));
}
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
masterEI, mdtStart, null, null);
e.setRecurring(true);
// e.addRdate(ridObj);
final var sum = (Summary)pl.getProperty(Property.SUMMARY);
e.setSummary(sum.getValue());
e.setSuppressed(true);
ical.addComponent(masterEI);
evinfo = masterEI.findOverride(rid);
evinfo.recurrenceSeen = true;
masterEI.setInstanceOnly(rid != null);
}
}
if (evinfo == null) {
evinfo = CnvUtil.makeNewEvent(cb, entityType, guid, colPath);
} else if (evinfo.getEvent().getEntityType() != entityType) {
return Response.notOk(resp, failed,
"org.bedework.mismatched.entity.type: " +
val);
}
final ChangeTable chg = evinfo.getChangeset(
cb.getPrincipal().getPrincipalRef());
if (rid != null) {
final String evrid = evinfo.getEvent().getRecurrenceId();
if ((evrid == null) || (!evrid.equals(rid))) {
logger. warn("Mismatched rid ev=" + evrid + " expected " + rid);
chg.changed(PropertyInfoIndex.RECURRENCE_ID, evrid, rid); // XXX spurious???
}
if (masterEI.getEvent().getSuppressed()) {
masterEI.getEvent().addRdate(ridObj);
}
}
ev = evinfo.getEvent();
ev.setScheduleMethod(methodType);
DtEnd dtEnd = null;
if (entityType == IcalDefs.entityTypeTodo) {
final Due due = pl.getProperty(Property.DUE);
if (due != null ) {
dtEnd = new DtEnd(due.getParameters(), due.getValue());
}
} else {
dtEnd = pl.getProperty(Property.DTEND);
}
final Duration duration = pl.getProperty(Property.DURATION);
IcalUtil.setDates(cb.getPrincipal().getPrincipalRef(),
evinfo, dtStart, dtEnd, duration);
for (final Property prop: pl) {
testXparams(prop, hasXparams);
//debug("ical prop " + prop.getClass().getName());
String pval = prop.getValue();
if ((pval != null) && (pval.length() == 0)) {
pval = null;
}
final PropertyInfoIndex pi;
if (prop instanceof XProperty) {
pi = PropertyInfoIndex.XPROP;
} else {
pi = PropertyInfoIndex.fromName(prop.getName());
}
if (pi == null) {
logger.debug("Unknown property with name " + prop.getName() +
" class " + prop.getClass() +
" and value " + pval);
continue;
}
chg.present(pi);
switch (pi) {
case ACCEPT_RESPONSE:
/* ------------------- Accept Response -------------------- */
String sval = prop.getValue();
if (chg.changed(pi, ev.getPollAcceptResponse(), sval)) {
ev.setPollAcceptResponse(sval);
}
break;
case ATTACH:
/* ------------------- Attachment -------------------- */
chg.addValue(pi, IcalUtil.getAttachment((Attach)prop));
break;
case ATTENDEE:
/* ------------------- Attendee -------------------- */
if (methodType == ScheduleMethods.methodTypePublish) {
if (cb.getStrictness() == IcalCallback.conformanceStrict) {
return Response.notOk(resp, failed,
CalFacadeException.attendeesInPublish);
}
//if (cb.getStrictness() == IcalCallback.conformanceWarn) {
// warn("Had attendees for PUBLISH");
//}
}
final Attendee attPr = (Attendee)prop;
if (evinfo.getNewEvent() || !mergeAttendees) {
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
final String pUri = cb.getCaladdr(attPr.getValue());
if (pUri.equals(attUri)) {
/* Only update for our own attendee
* We're doing a PUT and this must be the attendee updating their
* partstat. We don't allow them to change other attendees
* whatever the PUT content says.
*/
chg.addValue(pi, IcalUtil.getAttendee(cb, attPr));
} else {
// Use the value we currently have
boolean found = false;
for (final BwAttendee att: ev.getAttendees()) {
if (pUri.equals(att.getAttendeeUri())) {
chg.addValue(pi, att.clone());
found = true;
break;
}
}
if (!found) {
// An added attendee
final BwAttendee att = IcalUtil
.getAttendee(cb, attPr);
att.setPartstat(IcalDefs.partstatValNeedsAction);
chg.addValue(pi, att);
}
}
}
break;
case BUSYTYPE:
final int ibt = BwEvent.fromBusyTypeString(pval);
if (chg.changed(pi,
ev.getBusyType(),
ibt)) {
ev.setBusyType(ibt);
}
break;
case CATEGORIES:
/* ------------------- Categories -------------------- */
final Categories cats = (Categories)prop;
final TextList cl = cats.getCategories();
String lang = IcalUtil.getLang(cats);
if (cl != null) {
/* Got some categories */
for (final String wd: cl) {
if (wd == null) {
continue;
}
final BwString key = new BwString(lang, wd);
final var fcResp = cb.findCategory(key);
final BwCategory cat;
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isNotFound()) {
cat = BwCategory.makeCategory();
cat.setWord(key);
cb.addCategory(cat);
} else {
cat = fcResp.getEntity();
}
chg.addValue(pi, cat);
}
}
break;
case CLASS:
/* ------------------- Class -------------------- */
if (chg.changed(pi, ev.getClassification(), pval)) {
ev.setClassification(pval);
}
break;
case COMMENT:
/* ------------------- Comment -------------------- */
chg.addValue(pi,
new BwString(null, pval));
break;
case COMPLETED:
/* ------------------- Completed -------------------- */
if (chg.changed(pi, ev.getCompleted(), pval)) {
ev.setCompleted(pval);
}
break;
case CONCEPT:
/* ------------------- Concept -------------------- */
final Concept c = (Concept)prop;
final String cval = c.getValue();
if (cval != null) {
/* Got a concept */
chg.addValue(PropertyInfoIndex.XPROP,
BwXproperty.makeIcalProperty("CONCEPT",
null,
cval));
}
break;
case CONTACT:
/* ------------------- Contact -------------------- */
final String altrep = getAltRepPar(prop);
lang = IcalUtil.getLang(prop);
final String uid = getUidPar(prop);
final BwString nm = new BwString(lang, pval);
BwContact contact = null;
if (uid != null) {
final var fcResp = cb.getContact(uid);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
final var fcResp = cb.findContact(nm);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
contact = fcResp.getEntity();
}
}
if (contact == null) {
contact = BwContact.makeContact();
contact.setCn(nm);
contact.setLink(altrep);
cb.addContact(contact);
} else {
contact.setCn(nm);
contact.setLink(altrep);
}
chg.addValue(pi, contact);
break;
case CREATED:
/* ------------------- Created -------------------- */
if (chg.changed(pi, ev.getCreated(), pval)) {
ev.setCreated(pval);
}
break;
case DESCRIPTION:
/* ------------------- Description -------------------- */
if (chg.changed(pi, ev.getDescription(), pval)) {
ev.setDescription(pval);
}
break;
case DTEND:
/* ------------------- DtEnd -------------------- */
break;
case DTSTAMP:
/* ------------------- DtStamp -------------------- */
ev.setDtstamp(pval);
break;
case DTSTART:
/* ------------------- DtStart -------------------- */
break;
case DUE:
/* -------------------- Due ------------------------ */
break;
case DURATION:
/* ------------------- Duration -------------------- */
break;
case EXDATE:
/* ------------------- ExDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case EXRULE:
/* ------------------- ExRule -------------------- */
chg.addValue(pi, pval);
break;
case FREEBUSY:
/* ------------------- freebusy -------------------- */
final FreeBusy fbusy = (FreeBusy)prop;
final PeriodList perpl = fbusy.getPeriods();
final Parameter par = IcalUtil.getParameter(fbusy, "FBTYPE");
final int fbtype;
if (par == null) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY)) {
fbtype = BwFreeBusyComponent.typeBusy;
} else if (par.equals(FbType.BUSY_TENTATIVE)) {
fbtype = BwFreeBusyComponent.typeBusyTentative;
} else if (par.equals(FbType.BUSY_UNAVAILABLE)) {
fbtype = BwFreeBusyComponent.typeBusyUnavailable;
} else if (par.equals(FbType.FREE)) {
fbtype = BwFreeBusyComponent.typeFree;
} else {
if (logger.debug()) {
logger.debug("Unsupported parameter " + par.getName());
}
return Response.notOk(resp, failed,
"Unsupported parameter " +
par.getName());
}
final BwFreeBusyComponent fbc = new BwFreeBusyComponent();
fbc.setType(fbtype);
for (final Period per : perpl) {
fbc.addPeriod(per);
}
ev.addFreeBusyPeriod(fbc);
break;
case GEO:
/* ------------------- Geo -------------------- */
final Geo g = (Geo)prop;
final BwGeo geo = new BwGeo(g.getLatitude(),
g.getLongitude());
if (chg.changed(pi, ev.getGeo(), geo)) {
ev.setGeo(geo);
}
break;
case LAST_MODIFIED:
/* ------------------- LastModified -------------------- */
if (chg.changed(pi, ev.getLastmod(), pval)) {
ev.setLastmod(pval);
}
break;
case LOCATION:
/* ------------------- Location -------------------- */
BwLocation loc = null;
//String uid = getUidPar(prop);
/* At the moment Mozilla lightning is broken and this leads to all
* sorts of problems.
if (uid != null) {
loc = cb.getLocation(uid);
}
*/
lang = IcalUtil.getLang(prop);
BwString addr = null;
if (pval != null) {
if (loc == null) {
addr = new BwString(lang, pval);
final var fcResp = cb.findLocation(addr);
if (fcResp.isError()) {
return Response.fromResponse(resp, fcResp);
}
if (fcResp.isOk()) {
loc = fcResp.getEntity();
}
}
if (loc == null) {
loc = BwLocation.makeLocation();
loc.setAddress(addr);
cb.addLocation(loc);
}
}
final BwLocation evloc = ev.getLocation();
if (chg.changed(pi, evloc, loc)) {
// CHGTBL - this only shows that it's a different location object
ev.setLocation(loc);
} else if ((loc != null) && (evloc != null)) {
// See if the value is changed
final String evval = evloc.getAddress().getValue();
final String inval = loc.getAddress().getValue();
if (!evval.equals(inval)) {
chg.changed(pi, evval, inval);
evloc.getAddress().setValue(inval);
}
}
break;
case ORGANIZER:
/* ------------------- Organizer -------------------- */
final BwOrganizer org = IcalUtil.getOrganizer(cb, (Organizer)prop);
final BwOrganizer evorg = ev.getOrganizer();
final BwOrganizer evorgCopy;
if (evorg == null) {
evorgCopy = null;
} else {
evorgCopy = (BwOrganizer)evorg.clone();
}
if (chg.changed(pi, evorgCopy, org)) {
if (evorg == null) {
ev.setOrganizer(org);
} else {
evorg.update(org);
}
}
break;
case PERCENT_COMPLETE:
/* ------------------- PercentComplete -------------------- */
Integer ival = ((PercentComplete)prop).getPercentage();
if (chg.changed(pi, ev.getPercentComplete(), ival)) {
ev.setPercentComplete(ival);
}
break;
case POLL_MODE:
/* ------------------- Poll mode -------------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollMode(), sval)) {
ev.setPollMode(sval);
}
break;
case POLL_PROPERTIES:
/* ------------------- Poll properties ---------------- */
sval = prop.getValue();
if (chg.changed(pi, ev.getPollProperties(), sval)) {
ev.setPollProperties(sval);
}
break;
case POLL_WINNER:
/* ------------------- Poll winner -------------------- */
ival = ((PollWinner)prop).getPollwinner();
if (chg.changed(pi, ev.getPollWinner(), ival)) {
ev.setPollWinner(ival);
}
break;
case PRIORITY:
/* ------------------- Priority -------------------- */
ival = ((Priority)prop).getLevel();
if (chg.changed(pi, ev.getPriority(), ival)) {
ev.setPriority(ival);
}
break;
case RDATE:
/* ------------------- RDate -------------------- */
chg.addValues(pi,
IcalUtil.makeDateTimes((DateListProperty)prop));
break;
case RECURRENCE_ID:
/* ------------------- RecurrenceID -------------------- */
// Done above
break;
case RELATED_TO:
/* ------------------- RelatedTo -------------------- */
final RelatedTo irelto = (RelatedTo)prop;
final BwRelatedTo relto = new BwRelatedTo();
final String parval = IcalUtil.getParameterVal(irelto,
"RELTYPE");
if (parval != null) {
relto.setRelType(parval);
}
relto.setValue(irelto.getValue());
if (chg.changed(pi, ev.getRelatedTo(), relto)) {
ev.setRelatedTo(relto);
}
break;
case REQUEST_STATUS:
/* ------------------- RequestStatus -------------------- */
final BwRequestStatus rs = BwRequestStatus
.fromRequestStatus((RequestStatus)prop);
chg.addValue(pi, rs);
break;
case RESOURCES:
/* ------------------- Resources -------------------- */
final TextList rl = ((Resources)prop).getResources();
if (rl != null) {
/* Got some resources */
lang = IcalUtil.getLang(prop);
for (final String s: rl) {
final BwString rsrc = new BwString(lang,
s);
chg.addValue(pi, rsrc);
}
}
break;
case RRULE:
/* ------------------- RRule -------------------- */
chg.addValue(pi, pval);
break;
case SEQUENCE:
/* ------------------- Sequence -------------------- */
final int seq = ((Sequence)prop).getSequenceNo();
if (seq != ev.getSequence()) {
chg.changed(pi, ev.getSequence(), seq);
ev.setSequence(seq);
}
break;
case STATUS:
/* ------------------- Status -------------------- */
if (chg.changed(pi, ev.getStatus(), pval)) {
ev.setStatus(pval);
}
break;
case SUMMARY:
/* ------------------- Summary -------------------- */
if (chg.changed(pi, ev.getSummary(), pval)) {
ev.setSummary(pval);
}
break;
case TRANSP:
/* ------------------- Transp -------------------- */
if (chg.changed(pi,
ev.getPeruserTransparency(
cb.getPrincipal()
.getPrincipalRef()),
pval)) {
final BwXproperty pu = ev.setPeruserTransparency(
cb.getPrincipal().getPrincipalRef(),
pval);
if (pu != null) {
chg.addValue(PropertyInfoIndex.XPROP, pu);
}
}
break;
case UID:
/* ------------------- Uid -------------------- */
/* We did this above */
break;
case URL:
/* ------------------- Url -------------------- */
if (chg.changed(pi, ev.getLink(), pval)) {
ev.setLink(pval);
}
break;
case XPROP:
/* ------------------------- x-property --------------------------- */
final String name = prop.getName();
if (name.equalsIgnoreCase(BwXproperty.bedeworkCost)) {
if (chg.changed(PropertyInfoIndex.COST, ev.getCost(),
pval)) {
ev.setCost(pval);
}
break;
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkCategories)) {
if (checkCategory(cb, chg, ev, null, pval)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkLocation)) {
if (checkLocation(cb, chg, ev, prop)) {
break;
}
}
if (name.equalsIgnoreCase(BwXproperty.xBedeworkContact)) {
if (checkContact(cb, chg, ev, null, pval)) {
break;
}
}
/* See if this is an x-category that can be
converted to a real category
*/
final XProperty xp = (XProperty)prop;
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(name,
xp.getParameters()
.toString(),
pval));
break;
default:
if (logger.debug()) {
logger.debug("Unsupported property with index " + pi +
"; class " + prop.getClass() +
" and value " + pval);
}
}
}
/* =================== Process sub-components =============== */
final ComponentList<Component> subComps;
if (val instanceof ComponentContainer) {
subComps = ((ComponentContainer<Component>)val).getComponents();
} else {
subComps = null;
}
final Set<Integer> pids;
if (vpoll) {
pids = new TreeSet<>();
final BwEvent vp = evinfo.getEvent();
if (!Util.isEmpty(vp.getPollItems())) {
vp.clearPollItems();
}
} else {
pids = null;
}
if (!Util.isEmpty(subComps)) {
for (final var subComp: subComps) {
if (subComp instanceof Available) {
if (!(val instanceof VAvailability)) {
return Response.error(resp, "AVAILABLE only valid in VAVAILABLE");
}
final var avlResp = processAvailable(cb, cal,
ical,
(VAvailability)val,
(Available)subComp,
evinfo);
if (!avlResp.isOk()) {
return Response.fromResponse(resp, avlResp);
}
continue;
}
if (subComp instanceof Participant) {
if (vpoll) {
final var vresp = processVoter(cb,
(VPoll)val,
(Participant)subComp,
evinfo,
chg,
mergeAttendees);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Participant object");
continue;
}
if (subComp instanceof VResource) {
logger.warn("Unimplemented VResource object");
continue;
}
if (subComp instanceof VLocation) {
logger.warn("Unimplemented VLocation object");
continue;
}
if (subComp instanceof VAlarm) {
final var aresp = VAlarmUtil.processAlarm(cb,
val,
(VAlarm)subComp,
ev,
currentPrincipal,
chg);
if (!aresp.isOk()) {
return Response.fromResponse(resp, aresp);
}
continue;
}
if (vpoll && (event || task)) {
final var vresp = processCandidate((VPoll)val,
subComp,
evinfo,
pids,
chg);
if (!vresp.isOk()) {
return Response.fromResponse(resp, vresp);
}
continue;
}
logger.warn("Unimplemented Component object: " + subComp);
}
}
/* Fix up timestamps. */
if (ev.getCreated() == null) {
if (ev.getLastmod() != null) {
ev.setCreated(ev.getLastmod());
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
} else {
ev.updateDtstamp();
chg.changed(PropertyInfoIndex.CREATED, null, ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
}
if (ev.getLastmod() == null) {
// created cannot be null now
ev.setLastmod(ev.getCreated());
chg.changed(PropertyInfoIndex.LAST_MODIFIED, null, ev.getLastmod());
}
processTimezones(ev, ical, chg);
/* Remove any recipients and originator
*/
if (ev.getRecipients() != null) {
ev.getRecipients().clear();
}
ev.setOriginator(null);
if (hasXparams.value) {
/* Save a text copy of the entire event as an x-property */
final Component valCopy = val.copy();
/* Remove potentially large values */
final Description desp = valCopy.getProperty(Property.DESCRIPTION);
if (desp != null) {
desp.setValue(null);
}
final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} | NONSATD | true | }
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
} | null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
} | final Attach attachp = valCopy.getProperty(Property.ATTACH);
// Don't store the entire attachment - we just need the parameters.
if (attachp != null) {
final Value v = attachp.getParameter(Parameter.VALUE);
if (v != null) {
attachp.setValue(String.valueOf(attachp.getValue().hashCode()));
}
}
chg.addValue(PropertyInfoIndex.XPROP,
new BwXproperty(BwXproperty.bedeworkIcal,
null,
valCopy.toString()));
}
chg.processChanges(ev, true, false);
ev.setRecurring(ev.isRecurringEntity());
if (logger.debug()) {
logger.debug(chg.toString());
logger.debug(ev.toString());
}
if (masterEI != null) {
// Just return notfound as this event is on its override list
return Response.notFound(resp);
}
resp.setEntity(evinfo);
return resp;
} catch (final Throwable t) {
if (logger.debug()) {
logger.error(t);
}
return Response.error(resp, t);
}
} |
16,088 | 0 | // todo: account for assembly attributes | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass();
break;
case TokenID.Struct:
parseStruct();
break;
case TokenID.Interface:
parseInterface();
break;
case TokenID.Enum:
parseEnum();
break;
case TokenID.Delegate:
parseDelegate();
break;
case TokenID.Semi:
advance();
break;
default:
return;
}
}
} | IMPLEMENTATION | true | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) { | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) { | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal: |
16,088 | 1 | // can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass();
break;
case TokenID.Struct:
parseStruct();
break;
case TokenID.Interface:
parseInterface();
break;
case TokenID.Enum:
parseEnum();
break;
case TokenID.Delegate:
parseDelegate();
break;
case TokenID.Semi:
advance();
break;
default:
return;
}
}
} | NONSATD | true | curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using: | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static: | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace(); |
16,088 | 2 | // using directive | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass();
break;
case TokenID.Struct:
parseStruct();
break;
case TokenID.Interface:
parseInterface();
break;
case TokenID.Enum:
parseEnum();
break;
case TokenID.Delegate:
parseDelegate();
break;
case TokenID.Semi:
advance();
break;
default:
return;
}
}
} | NONSATD | true | switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break; | if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract: | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass(); |
16,088 | 3 | //parseTypeModifier(); | private void parseNamespaceOrTypes() throws FeatureNotSupportedException {
while (!curtok.equals(EOF)) {
// todo: account for assembly attributes
parsePossibleAttributes(true);
if (curAttributes.size() > 0) {
for (AttributeNode an : curAttributes) {
cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass();
break;
case TokenID.Struct:
parseStruct();
break;
case TokenID.Interface:
parseInterface();
break;
case TokenID.Enum:
parseEnum();
break;
case TokenID.Delegate:
parseDelegate();
break;
case TokenID.Semi:
advance();
break;
default:
return;
}
}
} | NONSATD | true | case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance(); | break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass();
break;
case TokenID.Struct: | cu.attributes.add(an);
}
curAttributes.clear();
}
// can be usingDirectives, globalAttribs, or NamespaceMembersDecls
// NamespaceMembersDecls include namespaces, class, struct, interface, enum, delegate
switch (curtok.id) {
case TokenID.Using:
// using directive
parseUsingDirectives();
break;
case TokenID.New:
case TokenID.Public:
case TokenID.Protected:
case TokenID.Partial:
case TokenID.Static:
case TokenID.Internal:
case TokenID.Private:
case TokenID.Abstract:
case TokenID.Sealed:
//parseTypeModifier();
curmods |= modMap.get(curtok.id);
advance();
break;
case TokenID.Namespace:
parseNamespace();
break;
case TokenID.Class:
parseClass();
break;
case TokenID.Struct:
parseStruct();
break;
case TokenID.Interface:
parseInterface();
break;
case TokenID.Enum:
parseEnum();
break;
case TokenID.Delegate:
parseDelegate(); |
16,089 | 0 | // over hash | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0]; | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define: | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword(); |
16,089 | 1 | // conditional-symbol pp-newline | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) { | IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) { | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount; |
16,089 | 2 | // conditional-symbol pp-newline | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) { | IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) { | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount; |
16,089 | 3 | // pp-expression pp-newline conditional-section(opt) | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance(); | break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
} | ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif: |
16,089 | 4 | // todo: account for true, false, ||, &&, ==, !=, ! | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | IMPLEMENTATION | true | int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) { | }
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block | if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) { |
16,089 | 5 | //result = new PPIfNode(ParseExpressionToNewline()); | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance(); | if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt) | case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif: |
16,089 | 6 | // skip this block | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | }
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
} | // todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) { | }
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line: |
16,089 | 7 | // pp-expression pp-newline conditional-section(opt) | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance(); | break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
} | ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif: |
16,089 | 8 | // pp-newline conditional-section(opt) | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block | if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break; | ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message |
16,089 | 9 | // skip this block | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | }
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
} | // todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) { | }
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line: |
16,089 | 10 | // pp-newline | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block | if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break; | ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message |
16,089 | 11 | // line-indicator pp-newline | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break; | // skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break; | SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message |
16,089 | 12 | // pp-message | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break; | case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break; | // pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break; |
16,089 | 13 | // pp-message | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break; | case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break; | // pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break; |
16,089 | 14 | // pp-message | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break; | case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break; | // pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break; |
16,089 | 15 | // pp-message | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break; | case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break; | // pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break; |
16,089 | 16 | // pp-message | private PPNode parsePreprocessorDirective() throws FeatureNotSupportedException {
PPNode result = null;
int startLine = lineCount;
inPPDirective = true;
advance(); // over hash
IdentifierExpression ie = parseIdentifierOrKeyword();
String ppKind = ie.Identifier[0];
byte id = PreprocessorID.Empty;
if (preprocessor.containsKey(ppKind)) {
id = preprocessor.get(ppKind);
} else {
ReportError("Preprocessor directive must be valid identifier, rather than \"" + ppKind + "\".");
}
switch (id) {
case PreprocessorID.Define:
// conditional-symbol pp-newline
IdentifierExpression def = parseIdentifierOrKeyword();
if (!ppDefs.containsKey(def.Identifier[0])) {
ppDefs.put(def.Identifier[0], PreprocessorID.Empty);
}
result = new PPDefineNode(def);
break;
case PreprocessorID.Undef:
// conditional-symbol pp-newline
IdentifierExpression undef = parseIdentifierOrKeyword();
if (ppDefs.containsKey(undef.Identifier[0])) {
ppDefs.remove(undef.Identifier[0]);
}
result = new PPDefineNode(undef);
break;
case PreprocessorID.If:
// pp-expression pp-newline conditional-section(opt)
if (curtok.id == TokenID.LParen) {
advance();
}
int startCount = lineCount;
ppCondition = false;
// todo: account for true, false, ||, &&, ==, !=, !
IdentifierExpression ifexpr = parseIdentifierOrKeyword();
if (ppDefs.containsKey(ifexpr.Identifier[0])) {
ppCondition = true;
}
//result = new PPIfNode(ParseExpressionToNewline());
if (curtok.id == TokenID.RParen) {
advance();
}
if (ppCondition == false) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Elif:
// pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break;
}
inPPDirective = false;
return result;
} | NONSATD | true | break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break; | case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break; | // pp-expression pp-newline conditional-section(opt)
SkipToEOL(startLine);
break;
case PreprocessorID.Else:
// pp-newline conditional-section(opt)
if (ppCondition == true) {
// skip this block
SkipToElseOrEndIf();
}
break;
case PreprocessorID.Endif:
// pp-newline
result = new PPEndIfNode();
ppCondition = false;
break;
case PreprocessorID.Line:
// line-indicator pp-newline
SkipToEOL(startLine);
break;
case PreprocessorID.Error:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Warning:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Region:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Endregion:
// pp-message
SkipToEOL(startLine);
break;
case PreprocessorID.Pragma:
// pp-message
SkipToEOL(startLine);
break;
default:
break; |
7,897 | 0 | // TODO Auto-generated catch block | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} | DESIGN | true | spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent. | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} |
7,897 | 1 | // TODO: Do something intelligent. | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} | DESIGN | true | // TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems; | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} |
7,896 | 0 | // TODO: Do something intelligent. | public void initialize() {
PayloadTrieBuilder<Item> itemsByNameBuilder = PayloadTrie.builder();
itemsByNameBuilder
.ignoreCase()
.ignoreOverlaps();
spammyItems = getSpammyItems();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(ITEM_FILE));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} | DESIGN | true | } catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace(); | String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} | public void initialize() {
PayloadTrieBuilder<Item> itemsByNameBuilder = PayloadTrie.builder();
itemsByNameBuilder
.ignoreCase()
.ignoreOverlaps();
spammyItems = getSpammyItems();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(ITEM_FILE));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} |
7,896 | 1 | // TODO: Do something intelligent. | public void initialize() {
PayloadTrieBuilder<Item> itemsByNameBuilder = PayloadTrie.builder();
itemsByNameBuilder
.ignoreCase()
.ignoreOverlaps();
spammyItems = getSpammyItems();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(ITEM_FILE));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} | DESIGN | true | } catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace(); | String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} | public void initialize() {
PayloadTrieBuilder<Item> itemsByNameBuilder = PayloadTrie.builder();
itemsByNameBuilder
.ignoreCase()
.ignoreOverlaps();
spammyItems = getSpammyItems();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(ITEM_FILE));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} |
16,097 | 0 | /*
Returns a list of filenames (just the filename, not the path) in working directory.
Todo: currently this skips over subdirs.
This will throw an IOException exception if the working directory is deleted (or possibly if
a file is removed) while this method is executing.
*/ | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} | DESIGN | true | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} |
16,097 | 1 | /*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/ | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} | NONSATD | true | String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
} | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} | public List<FileHandler.FileAttributes> listWorkingDirectory() throws IOException, Exception
{
FileHandler fileHandler = null;
try
{
Tool tool = getTool();
fileHandler = tool.getToolResource().getFileHandler();
String workingDirectory = tool.getToolResource().getWorkingDirectory(task.getJobHandle());
List<FileHandler.FileAttributes> list = fileHandler.list(workingDirectory);
/*
log.debug("In listWorkingDirectory, directory is " + workingDirectory + " and there are " +
list.size() + " files.");
*/
return list;
}
finally
{
if (fileHandler != null)
{
fileHandler.close();
}
}
} |
7,912 | 0 | /**
* Returns a bean descriptor representing this meta data object. A new
* descriptor instance is created with each invocation. The descriptor might
* be cached internally in the future should that need arise.
*
* @return A bean descriptor for this meta data object.
*/ | private BeanDescriptorImpl<T> getBeanDescriptorInternal() {
return new BeanDescriptorImpl<T>(
beanClass,
getClassLevelConstraintsAsDescriptors(),
getConstrainedPropertiesAsDescriptors(),
getMethodsAsDescriptors(),
defaultGroupSequenceIsRedefined(),
getDefaultGroupSequence( null )
);
} | NONSATD | true | private BeanDescriptorImpl<T> getBeanDescriptorInternal() {
return new BeanDescriptorImpl<T>(
beanClass,
getClassLevelConstraintsAsDescriptors(),
getConstrainedPropertiesAsDescriptors(),
getMethodsAsDescriptors(),
defaultGroupSequenceIsRedefined(),
getDefaultGroupSequence( null )
);
} | private BeanDescriptorImpl<T> getBeanDescriptorInternal() {
return new BeanDescriptorImpl<T>(
beanClass,
getClassLevelConstraintsAsDescriptors(),
getConstrainedPropertiesAsDescriptors(),
getMethodsAsDescriptors(),
defaultGroupSequenceIsRedefined(),
getDefaultGroupSequence( null )
);
} | private BeanDescriptorImpl<T> getBeanDescriptorInternal() {
return new BeanDescriptorImpl<T>(
beanClass,
getClassLevelConstraintsAsDescriptors(),
getConstrainedPropertiesAsDescriptors(),
getMethodsAsDescriptors(),
defaultGroupSequenceIsRedefined(),
getDefaultGroupSequence( null )
);
} |
16,106 | 0 | // FIXME haven't even started yet... need to busy-wait, perhaps | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} | DEFECT | true | Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try { | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e); | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} |
16,106 | 1 | // FIXME failed to startup or was interrupted during startup; maybe throw to the caller? | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} | DEFECT | true | return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) { | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} |
16,106 | 2 | // FIXME got tired of waiting, maybe do something special here? | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} | DEFECT | true | throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
} | if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} | public static String getData() {
Future<String> f = getInstance().startupFuture.get();
if (f == null) {
// FIXME haven't even started yet... need to busy-wait, perhaps
}
try {
String data = f.get(30, TimeUnit.SECONDS);
return data;
} catch (InterruptedException | ExecutionException e) {
// FIXME failed to startup or was interrupted during startup; maybe throw to the caller?
throw new IllegalStateException(e);
} catch (TimeoutException e) {
// FIXME got tired of waiting, maybe do something special here?
throw new IllegalStateException(e);
}
} |
7,935 | 0 | // WARNING
// INCOMPLETE see processSubtypeConstraints | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | IMPLEMENTATION | true | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod()); | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
} | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti)); |
7,935 | 1 | // the constraint S >> R', provided R is not void | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | NONSATD | true | Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement())); | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) { | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F())); |
7,935 | 2 | // additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | NONSATD | true | constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference(); | TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement())); | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints(); |
7,935 | 3 | // JLS: Any equality constraints are resolved ... | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | NONSATD | true | }
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument | constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
} | }
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} |
7,935 | 4 | // JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk) | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | NONSATD | true | // JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred | }
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param)); | for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} |
7,935 | 5 | //Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ]. | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | NONSATD | true | // Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace()))); | }
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} |
7,935 | 6 | //FIXME Perform substitution | private void processUnresolved(TypeReference Sref) throws LookupException {
// WARNING
// INCOMPLETE see processSubtypeConstraints
TypeReference RRef = (TypeReference) invokedGenericMethod().returnTypeReference();
FirstPhaseConstraintSet constraints = new FirstPhaseConstraintSet(invocation(), invokedGenericMethod());
View view = RRef.view();
TypeReference SprimeRef = box(Sref);
Java7 java = view.language(Java7.class);
if(! RRef.getElement().sameAs(java.voidType(RRef.view().namespace()))) {
// the constraint S >> R', provided R is not void
TypeReference RprimeRef = substitutedReference(RRef);
constraints.add(new GGConstraint(SprimeRef, RprimeRef.getElement()));
}
// additional constraints Bi[T1=B(T1) ... Tn=B(Tn)] >> Ti where Bi is the declared bound of Ti
for(TypeParameter param: typeParameters()) {
TypeReference Bi = param.upperBoundReference();
TypeReference BiAfterSubstitution = substitutedReference(Bi);
Type Ti = (Type) param.selectionDeclaration();
Type BTi = assignments().type(param);
if(BTi == null) {
BTi = Ti;
}
constraints.add(new GGConstraint(BiAfterSubstitution, Ti));
constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | IMPLEMENTATION | true | seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param)); | seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} | constraints.add(new SSConstraint(java.reference(BTi), BiAfterSubstitution.getElement()));
}
for(GGConstraint constraint: _origin.generatedGG()) {
constraints.add(new GGConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
for(EQConstraint constraint: _origin.generatedEQ()) {
constraints.add(new EQConstraint(substitutedReference(constraint.ARef()), constraint.F()));
}
SecondPhaseConstraintSet seconds = constraints.secondPhase();
// JLS: Any equality constraints are resolved ...
seconds.processEqualityConstraints();
// JLS: ..., and then, for each remaining constraint of the form Ti <: Uk, the argument
// Ti is inferred to be glb(U1,...,Uk)
seconds.processSubtypeConstraints();
//Any remaining type variable T that has not yet been inferred is then inferred
// to have type Object . If a previously inferred type variable P uses T , then P is
// inferred to be P [T =Object ].
for(TypeParameter param: seconds.unresolvedParameters()) {
seconds.add(new ActualTypeAssignment(param, java.getDefaultSuperClass(view.namespace())));
}
//FIXME Perform substitution
for(TypeParameter param: unresolvedParameters()) {
add(seconds.assignments().assignment(param));
}
} |
16,146 | 0 | //there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet); | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook |
16,146 | 1 | //now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | DESIGN | true | //here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) { | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length(); | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) { |
16,146 | 2 | //now we use the ExcelGenerator to generate the workbooks | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) { | for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf); | //there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable |
16,146 | 3 | //create a config for this workbook | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable | sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) { | //here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
}); |
16,146 | 4 | //TODO configurable | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | IMPLEMENTATION | true | //create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) { | workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig(); | //now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts) |
16,146 | 5 | //TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | DESIGN | true | sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k); | for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options); | for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing |
16,146 | 6 | //TODO maybe make a getSingleOrDefault method | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | DESIGN | true | ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset); | workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class); | }
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
} |
16,146 | 7 | //draw the ExcelCell matrix from ExcelTable | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset | sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else { | //now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf); |
16,146 | 8 | //it uses the tableConf offset | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | //draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
}); | //TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
} | for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf); |
16,146 | 9 | //TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts) | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | IMPLEMENTATION | true | });
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) { | ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
} | //TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder); |
16,146 | 10 | //in one sheet multiple tables could be existing | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & "); | d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i); | // so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping()); |
16,146 | 11 | //sheet name comes from table content | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf); | if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null; | Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping()); |
16,146 | 12 | //per sheet | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i); | throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) { | tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS); |
16,146 | 13 | //System.out.println("save workbook " + i);
//no extra folder when only one workbook | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder); | //in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard); | d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) { |
16,146 | 14 | //write provenance ================================================= | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null; | }
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel(); | ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter( |
16,146 | 15 | //used in rdfProvenance for fast lookup reified statements | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance | new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge | provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
} |
16,146 | 16 | //need here sheetname for provenance | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | //used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet); | new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue; | provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel); |
16,146 | 17 | //this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
} | //used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) { | new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) { |
16,146 | 18 | //no provenance information for this cell | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
} | for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel); | csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) { |
16,146 | 19 | //write to files | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz"); | }
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz"); | //this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) { |
16,146 | 20 | //key is sheet name | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage); | }
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) { | } catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1); |
16,146 | 21 | //count how often | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) { | } catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) { | File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage); |
16,146 | 22 | //skip the ones with no prov and no address (temp cells) | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue; | if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>()); | throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray(); |
16,146 | 23 | //because json array hash is always different | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
} | Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet()); | throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
} |
16,146 | 24 | //per workbook | public void create(File dstFolder, List<ExcelTable> tables, ExcelSproutOptions options) {
Random rnd = new Random(options.getRandomSeed());
//there are many tables
//we have to decide: what table to what sheet, and what sheet to what workbook
//we should not repeat tables about the same class, so there are possible groups
//maybe a workbook should be full to have the best expected.ttl from the original model
//here we calculate: what table to what workbook
List<List<ExcelTable>> workbookClusters = getWorkbookClusters(tables, rnd);
//now we have to decide which table will be in which sheet
//the cleanest way is to have a table per sheet
//TODO make this variable so more messy version are possible
List<List<List<ExcelTable>>> workbookSheetTables = new ArrayList<>();
for (List<ExcelTable> workbookTables : workbookClusters) {
List<List<ExcelTable>> sheetTables = new ArrayList<>();
for (ExcelTable tbl : workbookTables) {
List<ExcelTable> sheet = Arrays.asList(tbl);
sheetTables.add(sheet);
}
workbookSheetTables.add(sheetTables);
}
int maxDigits = String.valueOf(workbookSheetTables.size() - 1).length();
Map<List<ExcelTable>, ExcelGeneratorSheetConfig> sheetConfigMap = new HashMap<>();
//now we use the ExcelGenerator to generate the workbooks
ExcelGenerator excelGenerator = new ExcelGenerator();
for (int i = 0; i < workbookSheetTables.size(); i++) {
List<List<ExcelTable>> sheets = workbookSheetTables.get(i);
//create a config for this workbook
ExcelGeneratorWorkbookConfig workbookConf = new ExcelGeneratorWorkbookConfig();
//TODO configurable
workbookConf.setFileName("workbook.xlsx");
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConf = new ExcelGeneratorSheetConfig();
sheetConfigMap.put(sheet, sheetConf);
StringBuilder sheetNameSB = new StringBuilder();
//TODO a second table in the sheet means we maybe have to move the offset
// so that it will not overlap
for (int k = 0; k < sheet.size(); k++) {
ExcelTable excelTable = sheet.get(k);
ExcelGeneratorTableConfig tableConf = new ExcelGeneratorTableConfig();
//TODO maybe make a getSingleOrDefault method
Point offset = (Point) excelTable.getSetup().getOrDefault("offset", new Point(0, 0));
tableConf.setOffset(offset);
//draw the ExcelCell matrix from ExcelTable
tableConf.setStaticCellDrawer(d -> {
//it uses the tableConf offset
d.exceltable(excelTable, options);
});
sheetConf.getTableConfigs().add(tableConf);
//TODO if only one table with one class: add provenance sheetname -> insts a class. (for all insts)
ClassConfig classConfig = excelTable.getSetup().getOrThrow("classes", ClassConfig.class);
if (classConfig.hasLabel()) {
sheetNameSB.append(classConfig.getLabel());
} else {
throw new RuntimeException("ClassConfig should give a label to name the sheet");
}
//in one sheet multiple tables could be existing
if (k != sheet.size() - 1) {
sheetNameSB.append(" & ");
}
}
//sheet name comes from table content
sheetConf.setSheetName(sheetNameSB.toString());
workbookConf.getSheetConfigs().add(sheetConf);
}//per sheet
ExcelGeneratorResult result = excelGenerator.generate(null, workbookConf);
//System.out.println("save workbook " + i);
//no extra folder when only one workbook
File workbookFolder = workbookSheetTables.size() == 1 ? dstFolder : new File(dstFolder, String.format("%0" + maxDigits + "d", i));
result.saveExcel(workbookFolder);
//write provenance =================================================
Model expectedModel = null;
Model provenanceModel = null;
CSVPrinter provenanceCSV = null;
if (options.isWriteExpectedModel()) {
expectedModel = ModelFactory.createDefaultModel();
expectedModel.setNsPrefixes(options.getPrefixMapping());
expectedModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceModel()) {
provenanceModel = ModelFactory.createDefaultModel();
provenanceModel.setNsPrefixes(options.getPrefixMapping());
provenanceModel.setNsPrefix("prov", PROV.NS);
provenanceModel.setNsPrefix("csvw", CSVW.NS);
provenanceModel.setNsPrefix("ss", SS.NS);
provenanceModel.setNsPrefixes(PrefixMapping.Standard);
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV = CSVFormat.DEFAULT.print(
new OutputStreamWriter(
new GZIPOutputStream(
new FileOutputStream(
new File(workbookFolder, "provenance.csv.gz")
))));
csvProvenanceHeader(provenanceCSV);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
//used in rdfProvenance for fast lookup reified statements
Map<Statement, Resource> stmt2res = new HashMap<>();
//need here sheetname for provenance
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
for (ExcelTable table : sheet) {
for (Entry<ExcelCell, Provenance> cell2prov : table.getCellProvMap().entrySet()) {
ExcelCell cell = cell2prov.getKey();
Provenance prov = cell2prov.getValue();
if (cell.getAddress() == null) {
//this was a temporary cell created for a merge
//in TableGenerator putMultipleObjects method
continue;
}
if (prov.getStatements().isEmpty()) {
//no provenance information for this cell
continue;
}
if (options.isWriteExpectedModel()) {
expectedModel.add(prov.getStatements());
}
if (options.isWriteProvenanceModel()) {
rdfProvenance(cell, sheetConfig.getSheetName(), prov, stmt2res, provenanceModel);
}
if (options.isWriteProvenanceCSV()) {
csvProvenance(cell, sheetConfig.getSheetName(), prov, provenanceCSV, provenanceModel);
}
}
}
}
//write to files
if (options.isWriteExpectedModel()) {
File file = new File(workbookFolder, "expected.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
expectedModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceModel()) {
File file = new File(workbookFolder, "provenance.ttl.gz");
try (OutputStream os = file.getName().endsWith("gz") ? new GZIPOutputStream(new FileOutputStream(file)) : new FileOutputStream(file)) {
provenanceModel.write(os, "TTL");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteProvenanceCSV()) {
try {
provenanceCSV.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if (options.isWriteGenerationSummaryJson()) {
//key is sheet name
JSONObject perSheetPatternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(perSheetPatternUsage);
for (List<ExcelTable> sheet : sheets) {
ExcelGeneratorSheetConfig sheetConfig = sheetConfigMap.get(sheet);
//count how often
Map<String, Map<Object, Integer>> pattern2value2count = new HashMap<>();
for (ExcelTable tbl : sheet) {
for (Entry<ExcelCell, Provenance> entry : tbl.getCellProvMap().entrySet()) {
//skip the ones with no prov and no address (temp cells)
if (entry.getKey().getAddress() == null || entry.getValue().getStatements().isEmpty()) {
continue;
}
for (Entry<String, Object> e : entry.getValue().getUsedPatterns().entrySet()) {
Object val = e.getValue();
if(val instanceof JSONArray) {
//because json array hash is always different
val = val.toString();
}
Map<Object, Integer> value2count = pattern2value2count.computeIfAbsent(e.getKey(), k -> new HashMap<>());
value2count.put(val, value2count.getOrDefault(val, 0) + 1);
}
}
}
JSONObject patternUsage = new JSONObject();
JsonUtility.forceLinkedHashMap(patternUsage);
List<Entry<String, Map<Object, Integer>>> pattern2value2countList = new ArrayList<>(pattern2value2count.entrySet());
pattern2value2countList.sort((a,b) -> a.getKey().compareTo(b.getKey()));
for (Entry<String, Map<Object, Integer>> pattern2value2countEntry : pattern2value2countList) {
JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | NONSATD | true | }
}
}//per workbook
} | perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} | JSONArray array = new JSONArray();
for (Entry<Object, Integer> e : pattern2value2countEntry.getValue().entrySet()) {
JSONObject v2c = new JSONObject();
JsonUtility.forceLinkedHashMap(v2c);
v2c.put("value", e.getKey());
v2c.put("count", e.getValue());
array.put(v2c);
}
patternUsage.put(pattern2value2countEntry.getKey(), array);
}
perSheetPatternUsage.put(sheetConfig.getSheetName(), patternUsage);
}
options.getGenerationSummary().put("patternUsagePerSheet", perSheetPatternUsage);
File file = new File(workbookFolder, "summary.json");
try {
FileUtils.writeStringToFile(file, options.getGenerationSummary().toString(2), StandardCharsets.UTF_8);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}//per workbook
} |
7,967 | 0 | // FIXME Uncomment when overrides can be handled
// @OutSchema("wdk.users.get-by-id") | @GET
@Produces(MediaType.APPLICATION_JSON)
// FIXME Uncomment when overrides can be handled
// @OutSchema("wdk.users.get-by-id")
public JSONObject getById(@QueryParam("includePreferences") Boolean includePreferences) throws WdkModelException {
UserBundle userBundle = getUserBundle(Access.PUBLIC);
List<UserPropertyName> propDefs = getWdkModel().getModelConfig()
.getAccountDB().getUserPropertyNames();
return formatUser(userBundle.getTargetUser(), userBundle.isSessionUser(),
getFlag(includePreferences), propDefs);
} | DESIGN | true | @GET
@Produces(MediaType.APPLICATION_JSON)
// FIXME Uncomment when overrides can be handled
// @OutSchema("wdk.users.get-by-id")
public JSONObject getById(@QueryParam("includePreferences") Boolean includePreferences) throws WdkModelException {
UserBundle userBundle = getUserBundle(Access.PUBLIC); | @GET
@Produces(MediaType.APPLICATION_JSON)
// FIXME Uncomment when overrides can be handled
// @OutSchema("wdk.users.get-by-id")
public JSONObject getById(@QueryParam("includePreferences") Boolean includePreferences) throws WdkModelException {
UserBundle userBundle = getUserBundle(Access.PUBLIC);
List<UserPropertyName> propDefs = getWdkModel().getModelConfig()
.getAccountDB().getUserPropertyNames();
return formatUser(userBundle.getTargetUser(), userBundle.isSessionUser(),
getFlag(includePreferences), propDefs);
} | @GET
@Produces(MediaType.APPLICATION_JSON)
// FIXME Uncomment when overrides can be handled
// @OutSchema("wdk.users.get-by-id")
public JSONObject getById(@QueryParam("includePreferences") Boolean includePreferences) throws WdkModelException {
UserBundle userBundle = getUserBundle(Access.PUBLIC);
List<UserPropertyName> propDefs = getWdkModel().getModelConfig()
.getAccountDB().getUserPropertyNames();
return formatUser(userBundle.getTargetUser(), userBundle.isSessionUser(),
getFlag(includePreferences), propDefs);
} |
16,159 | 0 | // Probably incorrect - comparing Object[] arrays with Arrays.equals | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterizedTypeImpl that = (ParameterizedTypeImpl) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(actualTypeArguments, that.actualTypeArguments)) return false;
if (ownerType != null ? !ownerType.equals(that.ownerType) : that.ownerType != null) return false;
return rawType != null ? rawType.equals(that.rawType) : that.rawType == null;
} | DEFECT | true | if (o == null || getClass() != o.getClass()) return false;
ParameterizedTypeImpl that = (ParameterizedTypeImpl) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(actualTypeArguments, that.actualTypeArguments)) return false;
if (ownerType != null ? !ownerType.equals(that.ownerType) : that.ownerType != null) return false; | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterizedTypeImpl that = (ParameterizedTypeImpl) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(actualTypeArguments, that.actualTypeArguments)) return false;
if (ownerType != null ? !ownerType.equals(that.ownerType) : that.ownerType != null) return false;
return rawType != null ? rawType.equals(that.rawType) : that.rawType == null;
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ParameterizedTypeImpl that = (ParameterizedTypeImpl) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(actualTypeArguments, that.actualTypeArguments)) return false;
if (ownerType != null ? !ownerType.equals(that.ownerType) : that.ownerType != null) return false;
return rawType != null ? rawType.equals(that.rawType) : that.rawType == null;
} |
8,012 | 0 | /**
* Codegen IFlexModuleFactory.callInContext();
*
* public final override function callInContext(fn:Function, thisArg:Object, argArray:Array, returns:Boolean=true) : *
* {
* var ret : * = fn.apply(thisArg, argArray);
* if (returns) return ret;
* return;
* }
*
* @param classGen
* @param isOverride true if the generated method overrides a base class
* method, false otherwise.
*/ | protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride)
{
IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(),
NamespaceDefinition.getAS3NamespaceDefinition(), "apply");
InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} | NONSATD | true | protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride)
{
IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(),
NamespaceDefinition.getAS3NamespaceDefinition(), "apply");
InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} | protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride)
{
IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(),
NamespaceDefinition.getAS3NamespaceDefinition(), "apply");
InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} | protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride)
{
IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(),
NamespaceDefinition.getAS3NamespaceDefinition(), "apply");
InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} |
8,012 | 1 | // TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed. | protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride)
{
IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(),
NamespaceDefinition.getAS3NamespaceDefinition(), "apply");
InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} | DESIGN | true | callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>() | InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} | protected final void codegenCallInContextMethod(ClassGeneratorHelper classGen, boolean isOverride)
{
IResolvedQualifiersReference applyReference = ReferenceFactory.resolvedQualifierQualifiedReference(royaleProject.getWorkspace(),
NamespaceDefinition.getAS3NamespaceDefinition(), "apply");
InstructionList callInContext = new InstructionList();
callInContext.addInstruction(ABCConstants.OP_getlocal1);
callInContext.addInstruction(ABCConstants.OP_getlocal2);
callInContext.addInstruction(ABCConstants.OP_getlocal3);
callInContext.addInstruction(ABCConstants.OP_callproperty, new Object[] {applyReference.getMName(), 2});
callInContext.addInstruction(ABCConstants.OP_getlocal, 4);
Label callInContextReturnVoid = new Label();
callInContext.addInstruction(ABCConstants.OP_iffalse, callInContextReturnVoid);
callInContext.addInstruction(ABCConstants.OP_returnvalue);
callInContext.labelNext(callInContextReturnVoid);
// TODO This should be OP_returnvoid, but the Boolean default value
// for the 'returns' parameter isn't defaulting to true.
// Fix this after CMP-936 is fixed.
callInContext.addInstruction(ABCConstants.OP_returnvalue);
ImmutableList<Name> callInContextParams = new ImmutableList.Builder<Name>()
.add(new Name(IASLanguageConstants.Function))
.add(new Name(IASLanguageConstants.Object))
.add(new Name(IASLanguageConstants.Array))
.add(new Name(IASLanguageConstants.Boolean))
.build();
classGen.addITraitsMethod(new Name("callInContext"), callInContextParams, null,
Collections.<Object> singletonList(Boolean.TRUE), false, true, isOverride, callInContext);
} |
24,399 | 0 | // TODO make all other tags contextual tags here. for now we take only
// the counterpart
// tag of the current learning process: (opening/closing tags) | protected List<LP2Rule> createContextStartRulesForStartRule(final LP2Rule aStartRule) {
List<LP2Rule> result = new ArrayList<LP2Rule>();
// TODO make all other tags contextual tags here. for now we take only
// the counterpart
// tag of the current learning process: (opening/closing tags)
LP2RuleItem ctxItem = new LP2RuleItem();
MLLP2ContextConstraint ctxConstraint = new MLLP2ContextConstraint(
slotMaximumTokenCountMap.get(aStartRule.getTarget().getSingleSlotRawTypeName()),
aStartRule);
ctxItem.setContextConstraint(ctxConstraint);
LP2Rule ctxStartRule = new LP2Rule(this, aStartRule.getTarget());
ctxStartRule.setIsContextualRule(true);
if (aStartRule.getTarget().type == MLTargetType.SINGLE_LEFT_BOUNDARY)
ctxStartRule.addPostFillerItem(ctxItem);
else
ctxStartRule.addPreFillerItem(ctxItem);
result.add(ctxStartRule);
return result;
} | IMPLEMENTATION | true | protected List<LP2Rule> createContextStartRulesForStartRule(final LP2Rule aStartRule) {
List<LP2Rule> result = new ArrayList<LP2Rule>();
// TODO make all other tags contextual tags here. for now we take only
// the counterpart
// tag of the current learning process: (opening/closing tags)
LP2RuleItem ctxItem = new LP2RuleItem();
MLLP2ContextConstraint ctxConstraint = new MLLP2ContextConstraint( | protected List<LP2Rule> createContextStartRulesForStartRule(final LP2Rule aStartRule) {
List<LP2Rule> result = new ArrayList<LP2Rule>();
// TODO make all other tags contextual tags here. for now we take only
// the counterpart
// tag of the current learning process: (opening/closing tags)
LP2RuleItem ctxItem = new LP2RuleItem();
MLLP2ContextConstraint ctxConstraint = new MLLP2ContextConstraint(
slotMaximumTokenCountMap.get(aStartRule.getTarget().getSingleSlotRawTypeName()),
aStartRule);
ctxItem.setContextConstraint(ctxConstraint);
LP2Rule ctxStartRule = new LP2Rule(this, aStartRule.getTarget());
ctxStartRule.setIsContextualRule(true);
if (aStartRule.getTarget().type == MLTargetType.SINGLE_LEFT_BOUNDARY)
ctxStartRule.addPostFillerItem(ctxItem);
else | protected List<LP2Rule> createContextStartRulesForStartRule(final LP2Rule aStartRule) {
List<LP2Rule> result = new ArrayList<LP2Rule>();
// TODO make all other tags contextual tags here. for now we take only
// the counterpart
// tag of the current learning process: (opening/closing tags)
LP2RuleItem ctxItem = new LP2RuleItem();
MLLP2ContextConstraint ctxConstraint = new MLLP2ContextConstraint(
slotMaximumTokenCountMap.get(aStartRule.getTarget().getSingleSlotRawTypeName()),
aStartRule);
ctxItem.setContextConstraint(ctxConstraint);
LP2Rule ctxStartRule = new LP2Rule(this, aStartRule.getTarget());
ctxStartRule.setIsContextualRule(true);
if (aStartRule.getTarget().type == MLTargetType.SINGLE_LEFT_BOUNDARY)
ctxStartRule.addPostFillerItem(ctxItem);
else
ctxStartRule.addPreFillerItem(ctxItem);
result.add(ctxStartRule);
return result;
} |
8,028 | 0 | // TODO Update open changes according to event. For now, just read them all | public void webHookEvent(GerritProjectEvent projectEvent) {
log.info("Got Webhook:" + projectEvent);
// TODO Update open changes according to event. For now, just read them all
scheduleRefresh();
} | IMPLEMENTATION | true | public void webHookEvent(GerritProjectEvent projectEvent) {
log.info("Got Webhook:" + projectEvent);
// TODO Update open changes according to event. For now, just read them all
scheduleRefresh();
} | public void webHookEvent(GerritProjectEvent projectEvent) {
log.info("Got Webhook:" + projectEvent);
// TODO Update open changes according to event. For now, just read them all
scheduleRefresh();
} | public void webHookEvent(GerritProjectEvent projectEvent) {
log.info("Got Webhook:" + projectEvent);
// TODO Update open changes according to event. For now, just read them all
scheduleRefresh();
} |
24,418 | 0 | //It is actually a gas tank | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 2) { //Dump the tank
gasTank.setEmpty();
}
}
} else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) {
//It is actually an infusion tank
IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank;
//TODO: Implement at some point
}
}
//TODO: Handle other chemical tanks like maybe infusion tanks
} else if (tank instanceof IExtendedFluidTank) {
IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank;
if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) {
return;
}
GasStack storedGas = GasStack.EMPTY;
Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (gasCapability.isPresent()) {
IGasHandler gasHandlerItem = gasCapability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
storedGas = gasHandlerItem.getGasInTank(0);
}
}
if (button == 2) { //Dump the tank
fluidTank.setEmpty();
}
Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack));
if (!capability.isPresent()) {
//If something went wrong and we don't have a fluid handler on our tank, then fail
return;
}
IFluidHandlerItem fluidHandlerItem = capability.get();
if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) {
//TODO: Decide if we want to support someone replacing our fluid handler with another?
//If it isn't one of our fluid handlers fail
return;
}
IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null);
if (itemFluidTank == null) {
//If something went wrong and we don't have a fluid tank fail
return;
}
if (button == 0) { //Insert fluid into dropper
if (!storedGas.isEmpty() || fluidTank.isEmpty()) {
return;
}
FluidStack fluidInTank = fluidTank.getFluid();
FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL);
int remainder = simulatedRemainder.getAmount();
int amount = fluidInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the fluid from our tank into the item
FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!extractedFluid.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract fluid from dropper
if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) {
return;
}
FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL);
int fluidInItemAmount = storedFluid.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < fluidInItemAmount) {
FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!drainedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
}
}
}
} | NONSATD | true | IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY)); | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
} | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item |
24,418 | 1 | //Validate something didn't go terribly wrong and we actually do have the tank we expect to have | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 2) { //Dump the tank
gasTank.setEmpty();
}
}
} else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) {
//It is actually an infusion tank
IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank;
//TODO: Implement at some point
}
}
//TODO: Handle other chemical tanks like maybe infusion tanks
} else if (tank instanceof IExtendedFluidTank) {
IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank;
if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) {
return;
}
GasStack storedGas = GasStack.EMPTY;
Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (gasCapability.isPresent()) {
IGasHandler gasHandlerItem = gasCapability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
storedGas = gasHandlerItem.getGasInTank(0);
}
}
if (button == 2) { //Dump the tank
fluidTank.setEmpty();
}
Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack));
if (!capability.isPresent()) {
//If something went wrong and we don't have a fluid handler on our tank, then fail
return;
}
IFluidHandlerItem fluidHandlerItem = capability.get();
if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) {
//TODO: Decide if we want to support someone replacing our fluid handler with another?
//If it isn't one of our fluid handlers fail
return;
}
IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null);
if (itemFluidTank == null) {
//If something went wrong and we don't have a fluid tank fail
return;
}
if (button == 0) { //Insert fluid into dropper
if (!storedGas.isEmpty() || fluidTank.isEmpty()) {
return;
}
FluidStack fluidInTank = fluidTank.getFluid();
FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL);
int remainder = simulatedRemainder.getAmount();
int amount = fluidInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the fluid from our tank into the item
FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!extractedFluid.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract fluid from dropper
if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) {
return;
}
FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL);
int fluidInItemAmount = storedFluid.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < fluidInItemAmount) {
FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!drainedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
}
}
}
} | NONSATD | true | IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) { | FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE); | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
} |
24,418 | 2 | //Insert gas into dropper | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 2) { //Dump the tank
gasTank.setEmpty();
}
}
} else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) {
//It is actually an infusion tank
IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank;
//TODO: Implement at some point
}
}
//TODO: Handle other chemical tanks like maybe infusion tanks
} else if (tank instanceof IExtendedFluidTank) {
IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank;
if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) {
return;
}
GasStack storedGas = GasStack.EMPTY;
Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (gasCapability.isPresent()) {
IGasHandler gasHandlerItem = gasCapability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
storedGas = gasHandlerItem.getGasInTank(0);
}
}
if (button == 2) { //Dump the tank
fluidTank.setEmpty();
}
Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack));
if (!capability.isPresent()) {
//If something went wrong and we don't have a fluid handler on our tank, then fail
return;
}
IFluidHandlerItem fluidHandlerItem = capability.get();
if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) {
//TODO: Decide if we want to support someone replacing our fluid handler with another?
//If it isn't one of our fluid handlers fail
return;
}
IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null);
if (itemFluidTank == null) {
//If something went wrong and we don't have a fluid tank fail
return;
}
if (button == 0) { //Insert fluid into dropper
if (!storedGas.isEmpty() || fluidTank.isEmpty()) {
return;
}
FluidStack fluidInTank = fluidTank.getFluid();
FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL);
int remainder = simulatedRemainder.getAmount();
int amount = fluidInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the fluid from our tank into the item
FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!extractedFluid.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract fluid from dropper
if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) {
return;
}
FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL);
int fluidInItemAmount = storedFluid.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < fluidInItemAmount) {
FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!drainedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
}
}
}
} | NONSATD | true | return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return; | IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL); | ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) { |
24,418 | 3 | //We are able to fit at least some of the gas from our tank into the item | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 2) { //Dump the tank
gasTank.setEmpty();
}
}
} else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) {
//It is actually an infusion tank
IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank;
//TODO: Implement at some point
}
}
//TODO: Handle other chemical tanks like maybe infusion tanks
} else if (tank instanceof IExtendedFluidTank) {
IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank;
if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) {
return;
}
GasStack storedGas = GasStack.EMPTY;
Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (gasCapability.isPresent()) {
IGasHandler gasHandlerItem = gasCapability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
storedGas = gasHandlerItem.getGasInTank(0);
}
}
if (button == 2) { //Dump the tank
fluidTank.setEmpty();
}
Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack));
if (!capability.isPresent()) {
//If something went wrong and we don't have a fluid handler on our tank, then fail
return;
}
IFluidHandlerItem fluidHandlerItem = capability.get();
if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) {
//TODO: Decide if we want to support someone replacing our fluid handler with another?
//If it isn't one of our fluid handlers fail
return;
}
IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null);
if (itemFluidTank == null) {
//If something went wrong and we don't have a fluid tank fail
return;
}
if (button == 0) { //Insert fluid into dropper
if (!storedGas.isEmpty() || fluidTank.isEmpty()) {
return;
}
FluidStack fluidInTank = fluidTank.getFluid();
FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL);
int remainder = simulatedRemainder.getAmount();
int amount = fluidInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the fluid from our tank into the item
FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!extractedFluid.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract fluid from dropper
if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) {
return;
}
FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL);
int fluidInItemAmount = storedFluid.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < fluidInItemAmount) {
FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!drainedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
}
}
}
} | NONSATD | true | int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) { | }
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper | //It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) { |
24,418 | 4 | //If we were able to actually extract it from our tank, then insert it into the item | public static void useDropper(PlayerEntity player, Object tank, int button) {
ItemStack stack = player.inventory.getItemStack();
if (stack.isEmpty() || !(stack.getItem() instanceof ItemGaugeDropper)) {
return;
}
if (!stack.isEmpty()) {
FluidStack storedFluid = StorageUtils.getStoredFluidFromNBT(stack);
if (tank instanceof IChemicalTank) {
IChemicalTank<?, ?> chemicalTank = (IChemicalTank<?, ?>) tank;
if (chemicalTank.getEmptyStack() == GasStack.EMPTY) {
//It is actually a gas tank
IChemicalTank<Gas, GasStack> gasTank = (IChemicalTank<Gas, GasStack>) chemicalTank;
Optional<IGasHandler> capability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 2) { //Dump the tank
gasTank.setEmpty();
}
}
} else if (chemicalTank.getEmptyStack() == InfusionStack.EMPTY) {
//It is actually an infusion tank
IChemicalTank<InfuseType, InfusionStack> infusionTank = (IChemicalTank<InfuseType, InfusionStack>) chemicalTank;
//TODO: Implement at some point
}
}
//TODO: Handle other chemical tanks like maybe infusion tanks
} else if (tank instanceof IExtendedFluidTank) {
IExtendedFluidTank fluidTank = (IExtendedFluidTank) tank;
if (!storedFluid.isEmpty() && !fluidTank.isEmpty() && !storedFluid.isFluidEqual(fluidTank.getFluid())) {
return;
}
GasStack storedGas = GasStack.EMPTY;
Optional<IGasHandler> gasCapability = MekanismUtils.toOptional(stack.getCapability(Capabilities.GAS_HANDLER_CAPABILITY));
if (gasCapability.isPresent()) {
IGasHandler gasHandlerItem = gasCapability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
storedGas = gasHandlerItem.getGasInTank(0);
}
}
if (button == 2) { //Dump the tank
fluidTank.setEmpty();
}
Optional<IFluidHandlerItem> capability = MekanismUtils.toOptional(FluidUtil.getFluidHandler(stack));
if (!capability.isPresent()) {
//If something went wrong and we don't have a fluid handler on our tank, then fail
return;
}
IFluidHandlerItem fluidHandlerItem = capability.get();
if (!(fluidHandlerItem instanceof IMekanismFluidHandler)) {
//TODO: Decide if we want to support someone replacing our fluid handler with another?
//If it isn't one of our fluid handlers fail
return;
}
IExtendedFluidTank itemFluidTank = ((IMekanismFluidHandler) fluidHandlerItem).getFluidTank(0, null);
if (itemFluidTank == null) {
//If something went wrong and we don't have a fluid tank fail
return;
}
if (button == 0) { //Insert fluid into dropper
if (!storedGas.isEmpty() || fluidTank.isEmpty()) {
return;
}
FluidStack fluidInTank = fluidTank.getFluid();
FluidStack simulatedRemainder = itemFluidTank.insert(fluidInTank, Action.SIMULATE, AutomationType.MANUAL);
int remainder = simulatedRemainder.getAmount();
int amount = fluidInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the fluid from our tank into the item
FluidStack extractedFluid = fluidTank.extract(amount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!extractedFluid.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!itemFluidTank.insert(extractedFluid, Action.EXECUTE, AutomationType.MANUAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract fluid from dropper
if (!storedGas.isEmpty() || fluidTank.getNeeded() == 0) {
return;
}
FluidStack simulatedRemainder = fluidTank.insert(storedFluid, Action.SIMULATE, AutomationType.MANUAL);
int fluidInItemAmount = storedFluid.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < fluidInItemAmount) {
FluidStack drainedGas = itemFluidTank.extract(fluidInItemAmount - remainder, Action.EXECUTE, AutomationType.MANUAL);
if (!drainedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!fluidTank.insert(drainedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
}
}
}
} | NONSATD | true | GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error | return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return; | if (capability.isPresent()) {
IGasHandler gasHandlerItem = capability.get();
if (gasHandlerItem.getGasTankCount() > 0) {
//Validate something didn't go terribly wrong and we actually do have the tank we expect to have
GasStack storedGas = gasHandlerItem.getGasInTank(0);
if (!storedGas.isTypeEqual(gasTank.getStack())) {
return;
}
if (button == 0) { //Insert gas into dropper
if (!storedFluid.isEmpty() || gasTank.isEmpty()) {
return;
}
GasStack gasInTank = gasTank.getStack();
GasStack simulatedRemainder = gasHandlerItem.insertGas(gasInTank, Action.SIMULATE);
int remainder = simulatedRemainder.getAmount();
int amount = gasInTank.getAmount();
if (remainder < amount) {
//We are able to fit at least some of the gas from our tank into the item
GasStack extractedGas = gasTank.extract(amount - remainder, Action.EXECUTE, AutomationType.INTERNAL);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from our tank, then insert it into the item
if (!gasHandlerItem.insertGas(extractedGas, Action.EXECUTE).isEmpty()) {
//TODO: Print warning/error
}
((ServerPlayerEntity) player).sendContainerToPlayer(player.openContainer);
}
}
} else if (button == 1) { //Extract gas from dropper
if (!storedFluid.isEmpty() || gasTank.getNeeded() == 0) {
//If the dropper has fluid or the tank interacting with is already full of gas
return;
}
GasStack simulatedRemainder = gasTank.insert(storedGas, Action.SIMULATE, AutomationType.INTERNAL);
int gasInItemAmount = storedGas.getAmount();
int remainder = simulatedRemainder.getAmount();
if (remainder < gasInItemAmount) {
GasStack extractedGas = gasHandlerItem.extractGas(0, gasInItemAmount - remainder, Action.EXECUTE);
if (!extractedGas.isEmpty()) {
//If we were able to actually extract it from the item, then insert it into our gas tank
if (!gasTank.insert(extractedGas, Action.EXECUTE, AutomationType.INTERNAL).isEmpty()) {
//TODO: Print warning/error |