How to react on newly created Appointments? - java

I am looking for a way to get a delta of Appointments. Basically what I want is to react on newly created Appointments.
To get newly created / unread messages there is a SearchFilter in the java ews api that I use. Unfortunately AppointmentSchema does not provide any fitting Enum for the filter.
new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
I get the Appointments like:
CalendarFolder calendarFolder = CalendarFolder.bind(service, WellKnownFolderName.Calendar, new PropertySet());
var result = calendarFolder.findAppointments(cView);
so back to my question. How can I notice if someone invited me to a new Appointment or an email with a new Appointment invitation?

I have already found a solution, luckily. MeetingRequest is the Item I am looking for.
FindItemsResults<Item> result = service.findItems(new FolderId(WellKnownFolderName.Inbox, new Mailbox(getCredentials())), getUnreadEmailFilter(), new ItemView(10));
result.forEach(n -> {
if (n instanceof MeetingRequest) {
System.out.println("New Appointment - MeetingRequest found!");
MeetingRequest req = (MeetingRequest) n;
req.accept(true);
}
}

Related

Google calendar event, conference details are not being set

I'm trying to create the Google Calendar event with the conference(Google Meet) using Java SDK V3. The event is getting created but the conference details are not being set. Not sure what's missing
Create request:
Calendar service = new Calendar
.Builder(GoogleNetHttpTransport.newTrustedTransport(),
getDefaultInstance(),
new HttpCredentialsAdapter(googleCalendarCredentials()))
.setApplicationName(APPLICATION_NAME)
.build();
Event event = new Event();
event.setStart(new EventDateTime().setDateTime(new DateTime(currentTimeMillis())));
event.setEnd(new EventDateTime().setDateTime(new DateTime(currentTimeMillis() + 10000000)));
ConferenceData conferenceData = new ConferenceData();
conferenceData.setCreateRequest(
new CreateConferenceRequest()
.setConferenceSolutionKey(
new ConferenceSolutionKey()
.setType("hangoutsMeet")));
event.setConferenceData(conferenceData);
service.events().insert("primary", event).execute();
Get Request:
Events events = service.events()
.list("primary")
.execute();
List<Event> items = events.getItems();
if (items.isEmpty()) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event eventRs : items) {
System.out.printf("%s\n", eventRs.getConferenceData().getConferenceId());
}
}
Getting eventRs.getConferenceData() as null.
If you check the documentaiton on Event.insert you will see that you need to set the option parameter conferenceDataVersion inorder to enable it to set the conference data.
Version 0 assumes no conference data support and ignores conference data in the event's body. Version 1 enables support for copying of ConferenceData

how can i get only latest email mail body using EWS

This is my code:
PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
itempropertyset.setRequestedBodyType(BodyType.Text);
ItemView itemview = new ItemView(100);
itemview.setPropertySet(itempropertyset);
SearchFilter srchFilter = new SearchFilter.IsGreaterThan(ItemSchema.DateTimeReceived, d.parse(date));
FindItemsResults<Item> results = service.findItems(folder.getId(),srchFilter,itemview)
for (Item item : results) {
ItemId itemId = item.getId();
Item itm = Item.bind(service, itemId,PropertySet.FirstClassProperties);
item.load(itempropertyset);
System.out.println("item.getBody():: "+item.getBody());
}
item.getBody() printing all emails mailbody from mail chain. I want to fetch only latest one email body(top email body).
Return all the emails you're interested in via service.findItems and sort them into desc order by the getDateTimeReceived()and get the first EmailMessage obj in the list?
EWS won't do this for you as its the API its only job is to return the actual content of the body property. Because there is so much variance in what your asking (eg what happens if somebody does an inline response) you need to look at using another library to scan and detect that type of thing eg http://blog.mailgun.com/open-sourcing-our-email-signature-parsing-library/ but underlying from a technical perspective its very difficult.

Milo OPC UA Server with Historical Data Access

Hy,
I’m new to milo (and OPC-UA) and try to implement an OPC-UA server with Historical Data Access. I reused the current milo server example and create a history node. On this node I can query (with the Prosys OPC UA Client) the empty history. I know that I have to implement the persistency of the history nodes by myself.
So far so good – but I could not found any information about to handle the history read request and how to return the response. More precisely how to add the HistoryData to an HistoryReadResult
#Override
public void historyRead(HistoryReadContext context, HistoryReadDetails readDetails, TimestampsToReturn timestamps,
List<HistoryReadValueId> readValueIds)
{
List<HistoryReadResult> results = Lists.newArrayListWithCapacity(readValueIds.size());
for (HistoryReadValueId readValueId : readValueIds){
//return 3 historical entries
DataValue v1 = new DataValue(new Variant(new Double(1)), StatusCode.GOOD, new DateTime(Date.from(Instant.now().minus(1, ChronoUnit.MINUTES))));
DataValue v2 = new DataValue(new Variant(new Double(2)), StatusCode.GOOD, new DateTime(Date.from(Instant.now().minus(2, ChronoUnit.MINUTES))));
DataValue v3 = new DataValue(new Variant(new Double(3)), StatusCode.GOOD, new DateTime(Date.from(Instant.now().minus(3, ChronoUnit.MINUTES))));
HistoryData data = new HistoryData(new DataValue[] {v1,v2,v3});
//???
HistoryReadResult result = new HistoryReadResult(StatusCode.GOOD, ByteString.NULL_VALUE, ??? );
results.add(result);
}
context.complete(results);
}
You're going to need access to the spec to successfully implement historical access services. Part 4 and Part 11.
The last parameter in the HistoryReadResult constructor is supposed to be a HistoryData structure. ExtensionObject is basically the container that structures are encoded and transferred in.
To create that ExtensionObject you would first create a HistoryData (or HistoryModifiedData, depends... see the spec) and then do something like ExtensionObject.encode(historyData) to get the object you need to finish building the HistoryReadResult.
Overrides historyRead is the correct way to do.
HistoryReadResult result = new HistoryReadResult(StatusCode.GOOD, ByteString.NULL_VALUE,ExtensionObject.encode(data) );
However method was not called by generic client such as UA-Expert before defining my variableNode with specific AccessLevel and Historizing mode like this :
Set<AccessLevel> acclevels = new LinkedHashSet<>();
acclevels.add(AccessLevel.CurrentRead);
acclevels.add(AccessLevel.CurrentWrite);
acclevels.add(AccessLevel.HistoryRead);
UaVariableNode node = new UaVariableNode.UaVariableNodeBuilder(server.getNodeMap())
.setNodeId(new NodeId(namespaceIndex, "HelloWorld/Test/" + name))
.setAccessLevel(ubyte(AccessLevel.getMask(acclevels)))
.setUserAccessLevel(ubyte(AccessLevel.getMask(acclevels)))
.setBrowseName(new QualifiedName(namespaceIndex, name))
.setDisplayName(LocalizedText.english(name))
.setDataType(typeId)
.setTypeDefinition(Identifiers.BaseDataVariableType)
.setHistorizing(true)
.build();

Paypal "create" adaptive payments being instantly charged

I'm trying to set up a payment system with paypal for a site where the charging should not happen at payment confirmation time. I understand this is what the "CREATE" action type is for, you make the payment and then you use the execute payment to actually charge the account. Unfortunately, from what I'm seeing in the sandbox, the buyer gets charged immediately, and the execute payment returns a "paykey already used for a payment" error. The IPN notification similarly tells me the payment has already happened.
I'm currently using adaptive payments with 2 receivers. I'm sending the request from Java, using the code pasted below to get the paykey. Then I redirect the user to paypal and the payment is done (and charged).
Am I missing something?
List<PaymentReceiver> receiverList = setReceiversSingleProject(order);
Element root = new Element("PayRequest");
root.addNamespaceDeclaration("ns2", "http://svcs.paypal.com/types/ap");
// requestEnvelope and errorLanguage
Element requestEnvelopeElement = new Element("requestEnvelope");
Element errorLanguageElement = new Element("errorLanguage");
errorLanguageElement.appendChild(errorLanguage);
requestEnvelopeElement.appendChild(errorLanguageElement);
root.appendChild(requestEnvelopeElement);
// cancelUrl
Element cancelUrlElement = new Element("cancelUrl");
cancelUrlElement.appendChild(themeDisplay.getPortalURL()+"/basket");
root.appendChild(cancelUrlElement);
// actionType
Element actionTypeElement = new Element("actionType");
actionTypeElement.appendChild("CREATE");
root.appendChild(actionTypeElement);
// currencyCode
Element currencyCodeElement = new Element("currencyCode");
String projectCurrency = order.getMainProject().getCurrency();
Currency currency = CurrencyLocalServiceUtil.getCurrency(projectCurrency);
currencyCodeElement.appendChild(currency.getPaypalCode());
root.appendChild(currencyCodeElement);
// receiverList
Element receiverListElement = new Element("receiverList");
for (PaymentReceiver receiver : receiverList) {
Element receiverElement = new Element("receiver");
Element amountElement = new Element("amount");
amountElement.appendChild(String.valueOf(receiver.getAmount()));
Element emailElement = new Element("email");
emailElement.appendChild(receiver.getEmail());
Element primaryElement = new Element("primary");
primaryElement.appendChild(receiver.isPrimary()?"true":"false");
receiverElement.appendChild(amountElement);
receiverElement.appendChild(emailElement);
receiverElement.appendChild(primaryElement);
receiverListElement.appendChild(receiverElement);
}
root.appendChild(receiverListElement);
// returnUrl
Element returnUrlElement = new Element("returnUrl");
returnUrlElement.appendChild(returnURL);
root.appendChild(returnUrlElement);
// notifyUrl
Element notifyUrlElement = new Element("ipnNotificationUrl");
notifyUrlElement.appendChild(notifyURL);
root.appendChild(notifyUrlElement);
// Create document object
Document doc = new Document(root);
String result = doc.toXML();
return result;

How to program availability check and to create new meeting to Outlook?

I am creating a Java web app to manage meetings between a set of students and teachers. All of them already use Outlook to manage their email and personal calendar.
I would like to know if it's even possible to build the schedule feature of my web app using Exchange, Office365 or Sharepoint Team Calendar via REST service in order to check the availability and create a meeting for a student and one of the teachers available:
SharePoint 2013 REST service
So far, the most promising mechanism I have found is Microsoft Sharepoint Server's calendar, which collaborative features makes possible to create a meeting and check availability for a list of users. The downside is that it does not support one to one meetings but for the entire team (as far I have found).
My second option would be to require everyone in the group (students and teachers of the department) to make public their personal calendar so the web app be able to check the availability of both student and teacher and send a meeting request. The obvious problem is the privacy/security concern derived from this approach.
My last option (and by far the less favourite because it feels like re-inventing the wheel) is to build a proprietary calendar within the web app and send iCal requests to each person. The obvious problem with this approach is synchronisation between the two separated calendars.
In addition, this feature must be a pretty common need so there should be tons of blogs explaining how to take advantage of Exchange/Sharepoint/Office365 to implement it (other platforms are not considered since my employer's infrastructure is based on Microsoft). However, whether it is so obvious that nobody talks about it or I have not searched in the right place. Any advice to point me in the right direction?
Exchange natively shows user calendar availability exposed in EWS (Exchange Web Services), your network administrator must configure Exchange server enabling EWS.
But guess what... Office 365 (as I know) have EWS services enabled, due exchange is part of office 365 offer.
As EWS are normal Web services you should create a "service stub" or proxy in whatever you use in java to create services references mapping wsdl files.
Exchanged EWS is my preferred solution.
Hope this helps.
This is the reference page, this link show how to use the service references from C# to make the right API calls.
http://msdn.microsoft.com/en-us/library/exchange/aa494212(v=exchg.140).aspx
static void GetUserAvailability(ExchangeServiceBinding esb)
{
// Identify the time to compare free/busy information.
Duration duration = new Duration();
duration.StartTime = DateTime.Now;
duration.EndTime = DateTime.Now.AddHours(4);
// Identify the options for comparing free/busy information.
FreeBusyViewOptionsType fbViewOptions = new FreeBusyViewOptionsType();
fbViewOptions.TimeWindow = duration;
fbViewOptions.RequestedView = FreeBusyViewType.MergedOnly;
fbViewOptions.RequestedViewSpecified = true;
fbViewOptions.MergedFreeBusyIntervalInMinutes = 35;
fbViewOptions.MergedFreeBusyIntervalInMinutesSpecified = true;
MailboxData[] mailboxes = new MailboxData[1];
mailboxes[0] = new MailboxData();
// Identify the user mailbox to review for free/busy data.
EmailAddress emailAddress = new EmailAddress();
emailAddress.Address = "tplate#contoso.com";
emailAddress.Name = String.Empty;
mailboxes[0].Email = emailAddress;
mailboxes[0].ExcludeConflicts = false;
// Make the request.
GetUserAvailabilityRequestType request = new GetUserAvailabilityRequestType();
// Set the time zone of the request.
request.TimeZone = new SerializableTimeZone();
request.TimeZone.Bias = 480;
request.TimeZone.StandardTime = new SerializableTimeZoneTime();
request.TimeZone.StandardTime.Bias = 0;
request.TimeZone.StandardTime.DayOfWeek = DayOfWeekType.Sunday.ToString();
request.TimeZone.StandardTime.DayOrder = 1;
request.TimeZone.StandardTime.Month = 11;
request.TimeZone.StandardTime.Time = "02:00:00";
request.TimeZone.DaylightTime = new SerializableTimeZoneTime();
request.TimeZone.DaylightTime.Bias = -60;
request.TimeZone.DaylightTime.DayOfWeek = DayOfWeekType.Sunday.ToString();
request.TimeZone.DaylightTime.DayOrder = 2;
request.TimeZone.DaylightTime.Month = 3;
request.TimeZone.DaylightTime.Time = "02:00:00";
// Add the mailboxes to the request.
request.MailboxDataArray = mailboxes;
// Add the view options to the request.
request.FreeBusyViewOptions = fbViewOptions;
try
{
// Send the request and get the response.
GetUserAvailabilityResponseType response = esb.GetUserAvailability(request);
// Access free/busy information.
if (response.FreeBusyResponseArray.Length < 1)
{
throw new Exception("No free/busy response data available.");
}
else
{
foreach (FreeBusyResponseType fbrt in response.FreeBusyResponseArray)
{
if (fbrt.ResponseMessage.ResponseClass == ResponseClassType.Error)
{
Console.WriteLine(string.Format("Error: {0}", fbrt.ResponseMessage.MessageText));
}
else
{
// Show the free/busy stream.
FreeBusyView fbv = fbrt.FreeBusyView;
Console.WriteLine(string.Format("Merged free/busy data: {0}", fbv.MergedFreeBusy));
}
}
}
}
catch (Exception e)
{
// Perform error processing.
Console.WriteLine(e.Message);
Console.ReadLine();
}
}

Categories