Google fit history API won't retrieve dataset? - java

I am currently trying to display today's current steps through my application. I have the following code below which Authenticates most of the time alright. I have added the SHA1 certificate to the developers console as well.
I keep getting the error "There was a problem inserting the dataset." in my log through with nothing else after that showing up and i'm a bit confused as to why?
Also this seems to be temperamental, sometimes it works and shows 7 data sets with random numbers (not my step count) so my second question is how do I get it to display just today's?
Authentication
private void buildFitnessClient() {
if (mClient == null) {
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.HISTORY_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs.
new InsertAndVerifyDataTask().execute();
}
#Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
Toast.makeText(getBaseContext(), "Connection lost. Cause: Network Lost.", Toast.LENGTH_LONG).show();
} else if (i
== GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG,
"Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Google Play services connection failed. Cause: " +
result.toString());
Toast.makeText(getBaseContext(), "Google Play services connection failed. Cause: " +
result.toString(), Toast.LENGTH_LONG).show();
}
})
.build();
}
}
Where I think the issue resides.
private class InsertAndVerifyDataTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
//First, create a new dataset and insertion request.
DataSet dataSet = insertFitnessData();
// [START insert_dataset]
// Then, invoke the History API to insert the data and await the result, which is
// possible here because of the {#link AsyncTask}. Always include a timeout when calling
// await() to prevent hanging that can occur from the service being shutdown because
// of low memory or other conditions.
Log.i(TAG, "Inserting the dataset in the History API");
com.google.android.gms.common.api.Status insertStatus =
Fitness.HistoryApi.insertData(mClient, dataSet)
.await(1, TimeUnit.MINUTES);
// Before querying the data, check to see if the insertion succeeded.
if (!insertStatus.isSuccess()) {
Log.i(TAG, "There was a problem inserting the dataset.");
return null;
}
// At this point, the data has been inserted and can be read.
Log.i(TAG, "Data insert was successful!");
// [END insert_dataset]
// Begin by creating the query.
DataReadRequest readRequest = queryFitnessData();
// [START read_dataset]
// Invoke the History API to fetch the data with the query and await the result of
// the read request.
DataReadResult dataReadResult =
Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
// [END read_dataset]
// For the sake of the sample, we'll print the data so we can see what we just added.
// In general, logging fitness information should be avoided for privacy reasons.
printData(dataReadResult);
return null;
}
}
private DataSet insertFitnessData() {
Log.i(TAG, "Creating a new data insert request");
// [START build_insert_data_request]
// Set a start and end time for our data, using a start time of 1 hour before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.HOUR_OF_DAY, -1);
long startTime = cal.getTimeInMillis();
// Create a data source
DataSource dataSource = new DataSource.Builder()
.setAppPackageName(this)
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setName(TAG + " - step count")
.setType(DataSource.TYPE_RAW)
.build();
// Create a data set
int stepCountDelta = 1000;
DataSet dataSet = DataSet.create(dataSource);
// For each data point, specify a start time, end time, and the data value -- in this case,
// the number of new steps.
DataPoint dataPoint = dataSet.createDataPoint()
.setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
dataPoint.getValue(Field.FIELD_STEPS).setInt(stepCountDelta);
dataSet.add(dataPoint);
// [END build_insert_data_request]
return dataSet;
}

Got it working with the following code gets todays steps:
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 00);
long startTime = cal.getTimeInMillis();
int steps = 0;
DataSource ESTIMATED_STEP_DELTAS = new DataSource.Builder()
.setDataType(DataType.TYPE_STEP_COUNT_DELTA)
.setType(DataSource.TYPE_DERIVED)
.setStreamName("estimated_steps")
.setAppPackageName("com.google.android.gms").build();
// fill result with just the steps from the start and end time of the present day
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(mClient, DataType.AGGREGATE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(60, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
steps = totalSet.isEmpty() ? -1 : totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
}
s = String.valueOf(steps);
DataReadRequest readRequest = queryFitnessData();
DataReadResult dataReadResult =
Fitness.HistoryApi.readData(mClient, readRequest).await(1, TimeUnit.MINUTES);
feedItemList.clear();
printData(dataReadResult);
return null;

Sometime, we also want to get data step in a specific time range, and here it's a reason in that case.
There're some probable causes:
1) Have you subscribed this type of data yet?
2) Your app doesn't connect properly with google service. Have you created OAuth Client ID from Google develop console? This's compulsory in instruction of google to connect to its GG Fit service (Please notice that, if you clone another app, on the same computer or not, you need to re-create another OAuth Client ID and one more thing you need 2 separated account, one to login Google develop console to create OAuth Client ID and one to sign in after starting your app, and it will ask you to sign in to accept its permission,... not sure why it's is, but it would work)
Note: Btw you can make a search about Google setting in your device (Setting --> Google), Here you can find which app connects to google service (including GG Fit service). I recommend you disconnect all and delete OAuth Client ID, your app, then re-create all of them!
Mttdat.

Related

How to transcribe bandwidth call recordings in java

My application uses https://app.bandwidth.com/ for receiving incoming calls. I have an api to handle the incoming calls which record the calls when the call is not answered(This recording is treated as a voice mail).
if (eventType.equalsIgnoreCase(EventType.ANSWER.toString())) {
Timestamp callStartTime = new Timestamp(TimeUtil.now().getTime());
incomingCall.setCallTime(callStartTime);
callStatus = transferCall(callId, incomingCall.getVoiceForwardNumber(), 1);
}
else if (eventType.equalsIgnoreCase(EventType.TIMEOUT.toString())) {
voiceMailIntro(callId);
}
else if (eventType.equalsIgnoreCase(EventType.SPEAK.toString()) && PLAYBACK_STOP.equalsIgnoreCase(callState)) {
recordVoiceMail(callId);
}
else if (eventType.equalsIgnoreCase(EventType.RECORDING.toString()) &&
state.equalsIgnoreCase(BandwidthCallStatus.COMPLETE.toString())) {
createTranscription(recordingId);
}
else if (eventType.equalsIgnoreCase(EventType.TRANSCRIPTION.toString()) && status.equalsIgnoreCase(BandwidthCallStatus.COMPLETED.toString())) {
incomingCall.setVoiceMail(text);
}
This is the code for recording call
private void recordVoiceMail(String callId) {
BandwidthClient client = BandwidthClient.getInstance();
client.setCredentials(bandwidthUserId, bandwidthApiToken, bandwidthApiSecret);
try {
Call call = Call.get(client, callId);
call.recordingOn();
} catch (Exception e) {
log.error("An exception occurred while recording voice mail : " +
e.getMessage(), e);
}
}
Now i need to transcribe these vocie mails.
From documentation i got methods in python, js, c#, ruby etc. to transcribe the recordings using the recordings.
For example in js,
client.Recording.createTranscription(recordingId, function(err, transcription){});
I searched every where, but i couldn't find any method in java for that.
Can any one help me if you know ?
Anyway, as I see, you need that link for java doc.
And here you can follow to java sdk located on Github.
And, also, you can find some more information about transcriptions API here which you are looking for.
First of all, why do you need that? Perhaps, you do not need that.
As I find, you can't do transcribe with POJO, but you can do something like that.
If you want to do that, you can make it with
public void transcribeOn() throws Exception {
final List<Recording> list = Recording.list(0, 5);
if (!list.isEmpty()) {
final Recording recording = Recording.get(list.get(0).getId());
System.out.println("\nRecording by Id");
System.out.println(recording);
final String recordingUri = mockClient.getUserResourceUri(BandwidthConstants.RECORDINGS_URI_PATH);
client.post(recordingUri + "/" + list.get(0).getId() + "/transcriptions", null);
final JSONObject jsonObject = call.toJSONObject(client.get(recordingUri, null));
call.updateProperties(jsonObject);
}
}
I'm not sure it works correctly, but I hope it put you on correct way

Grpc Server keeps processing the data even when client get disconnected

I have a server which streams the data for a given request below is the method which does that function
#Override
public void getChangeFeed(ChangeFeedRequest request, StreamObserver<ChangeFeedResponse> responseObserver) {
long queryDate = request.getFromDate();
long offset = request.getPageNo();
ChangeFeedResponse changeFeedResponse = processData(responseObserver, queryDate, offset);
while(true){
if(changeFeedResponse!=null && !changeFeedResponse.getFinalize()){
responseObserver.onNext(changeFeedResponse);
changeFeedResponse = processData(responseObserver, changeFeedResponse.getToDate(), changeFeedResponse.getPageNo());
}else{
break;
}
}
responseObserver.onNext(changeFeedResponse);
responseObserver.onCompleted();
}
When the client get disconnected the server still keeps on processing, this might be issue when multiple clients are fetching the data. Need to know how to tell server to stop processing
There's two fairly-equivalent ways. One is to use the Context, which is cancelled when the RPC is completed/cancelled:
while(!Context.current().isCancelled()){ // THIS LINE CHANGED
if(changeFeedResponse!=null && !changeFeedResponse.getFinalize()){
responseObserver.onNext(changeFeedResponse);
changeFeedResponse = processData(responseObserver, changeFeedResponse.getToDate(), changeFeedResponse.getPageNo());
}else{
break;
}
}
The other would be to use the ServerCallStreamObserver:
// THE NEXT TWO LINES CHANGED
ServerCallStreamObserver scso = (ServerCallStreamObserver) responseObserver;
while(!scso.isCancelled()){
if(changeFeedResponse!=null && !changeFeedResponse.getFinalize()){
responseObserver.onNext(changeFeedResponse);
changeFeedResponse = processData(responseObserver, changeFeedResponse.getToDate(), changeFeedResponse.getPageNo());
}else{
break;
}
}
Both approaches can also provide notification when a cancellation occurs, but polling is easiest in your case.

How to find steps with Google Fit API for Android?

I have done a couple of days of research regarding this. All I need is a Simple TextView area in my application to display today's steps.
I have managed to get the Authentication working with the code below. It pops up asks for permission and think I have the right one selected.
But I can not figure out how to simple gain the Step Count information. I hope this is only a couple of lines of code. Any help would be appreciated. Thanks
EDIT 1: I just need to get the Step count number. I can figure out how to display it later. I also have Toasts in just to help me figure out what is going on.
private void buildFitnessClient() {
if (mClient == null) {
mClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addConnectionCallbacks(
new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected!!!");
// Now you can make calls to the Fitness APIs.
Toast.makeText(getBaseContext(), "Connected!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionSuspended(int i) {
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
Toast.makeText(getBaseContext(), "Connection lost. Cause: Network Lost.", Toast.LENGTH_LONG).show();
} else if (i
== GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG,
"Connection lost. Reason: Service Disconnected");
}
}
}
)
.enableAutoManage(this, 0, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Google Play services connection failed. Cause: " +
result.toString());
Toast.makeText(getBaseContext(), "Google Play services connection failed. Cause: " +
result.toString(), Toast.LENGTH_LONG).show();
}
})
.build();
}
}
GoogleApiClient is deprecated according to the new updates. As well as the HistoryApi is also deprecated. So first have to use the GoogleSignInAccount instead of GoogleApiClient and also use HistoryClient of Google Fit instead of HistoryApi.
Setting Fitness Options
val fitnessOptions: GoogleSignInOptionsExtension = FitnessOptions.builder()
.addDataType(TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_READ).build()
Setting Google SignIn Option
val googleSignInOptions =
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.addExtension(fitnessOptions).requestEmail().build()
val googleSignInClient = GoogleSignIn.getClient(requireActivity(), googleSignInOptions)
val signIntent = googleSignInClient.signInIntent
startActivityForResult(signIntent, 0)
Getting Account
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val account = task.getResult(ApiException::class.java)
if (account != null) {
getGoogleFitData(account)
}
}
}
Now for getting step data
val response: Task<DataReadResponse> =
Fitness.getHistoryClient(mContext, mSignInAccount)
.readData(
DataReadRequest.Builder()
.read(TYPE_STEP_COUNT_DELTA)
.setTimeRange(
startTime,
endTime,
TimeUnit.MILLISECONDS
)
.build()
)
val readDataResult: DataReadResponse? = Tasks.await(response)
val dataSet: DataSet = readDataResult!!.getDataSet(TYPE_STEP_COUNT_DELTA)
var total = 0
if (!dataSet.isEmpty) {
val dataPoints = dataSet.dataPoints
if (dataPoints.size > 0) {
for (i in 0 until dataPoints.size) {
total += dataSet.dataPoints[i].getValue(Field.FIELD_STEPS).asInt()
}
Log.e(TAG, "Total Steps : $total")
}
}
Here startTime and endTime are timemills of any date and time.
Thank You.
Check out this official documentation from Google on how to read the data from Fit:
// Setting a start and end date using a range of 1 week before this moment.
Calendar cal = Calendar.getInstance();
Date now = new Date();
cal.setTime(now);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.WEEK_OF_YEAR, -1);
long startTime = cal.getTimeInMillis();
java.text.DateFormat dateFormat = getDateInstance();
Log.i(TAG, "Range Start: " + dateFormat.format(startTime));
Log.i(TAG, "Range End: " + dateFormat.format(endTime));
DataReadRequest readRequest = new DataReadRequest.Builder()
// The data request can specify multiple data types to return, effectively
// combining multiple data queries into one call.
// In this example, it's very unlikely that the request is for several hundred
// datapoints each consisting of a few steps and a timestamp. The more likely
// scenario is wanting to see how many steps were walked per day, for 7 days.
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
// Analogous to a "Group By" in SQL, defines how data should be aggregated.
// bucketByTime allows for a time span, whereas bucketBySession would allow
// bucketing by "sessions", which would need to be defined in code.
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
History API Sample app on GitHub:
Check the sample project on GitHub here.
Direct link to MainActivity.java (in the above sample project) containing the required code: Link

Migration from dcm4che2 to dcm4che3

I have used below mentioned API of dcm4che2 from this repository http://www.dcm4che.org/maven2/dcm4che/ in my java project.
dcm4che-core-2.0.29.jar
org.dcm4che2.data.DicomObject
org.dcm4che2.io.StopTagInputHandler
org.dcm4che2.data.BasicDicomObject
org.dcm4che2.data.UIDDictionary
org.dcm4che2.data.DicomElement
org.dcm4che2.data.SimpleDcmElement
org.dcm4che2.net.service.StorageCommitmentService
org.dcm4che2.util.CloseUtils
dcm4che-net-2.0.29.jar
org.dcm4che2.net.CommandUtils
org.dcm4che2.net.ConfigurationException
org.dcm4che2.net.NetworkApplicationEntity
org.dcm4che2.net.NetworkConnection
org.dcm4che2.net.NewThreadExecutor
org.dcm4che3.net.service.StorageService
org.dcm4che3.net.service.VerificationService
Currently i want to migrate to dcm4che3 but, above listed API is not found in dcm4che3 which i have downloaded from this repository http://sourceforge.net/projects/dcm4che/files/dcm4che3/
Could you please guide me for alternate approach?
As you have already observed, the BasicDicomObject is history -- alongside quite a few others.
The new "Dicom object" is Attributes -- an object is a collection of attributes.
Therefore, you create Attributes, populate them with the tags you need for RQ-behaviour (C-FIND, etc) and what you get in return is another Attributes object from which you pull the tags you want.
In my opinion, dcm4che 2.x was vague on the subject of dealing with individual value representations. dcm4che 3.x is quite a bit clearer.
The migration demands a rewrite of your code regarding how you query and how you treat individual tags. On the other hand, dcm4che 3.x makes the new code less convoluted.
On request, I have added the initial setup of a connection to some service class provider (SCP):
// Based on org.dcm4che:dcm4che-core:5.25.0 and org.dcm4che:dcm4che-net:5.25.0
import org.dcm4che3.data.*;
import org.dcm4che3.net.*;
import org.dcm4che3.net.pdu.AAssociateRQ;
import org.dcm4che3.net.pdu.PresentationContext;
import org.dcm4che3.net.pdu.RoleSelection;
import org.dcm4che3.net.pdu.UserIdentityRQ;
// Client side representation of the connection. As a client, I will
// not be listening for incoming traffic (but I could choose to do so
// if I need to transfer data via MOVE)
Connection local = new Connection();
local.setHostname("client.on.network.com");
local.setPort(Connection.NOT_LISTENING);
// Remote side representation of the connection
Connection remote = new Connection();
remote.setHostname("pacs.on.network.com");
remote.setPort(4100);
remote.setTlsProtocols(local.getTlsProtocols());
remote.setTlsCipherSuites(local.getTlsCipherSuites());
// Calling application entity
ApplicationEntity ae = new ApplicationEntity("MeAsAServiceClassUser".toUpperCase());
ae.setAETitle("MeAsAServiceClassUser");
ae.addConnection(local); // on which we may not be listening
ae.setAssociationInitiator(true);
ae.setAssociationAcceptor(false);
// Device
Device device = new Device("MeAsAServiceClassUser".toLowerCase());
device.addConnection(local);
device.addApplicationEntity(ae);
// Configure association
AAssociateRQ rq = new AAssociateRQ();
rq.setCallingAET("MeAsAServiceClassUser");
rq.setCalledAET("NameThatIdentifiesTheProvider"); // e.g. "GEPACS"
rq.setImplVersionName("MY-SCU-1.0"); // Max 16 chars
// Credentials (if appropriate)
String username = "username";
String passcode = "so secret";
if (null != username && username.length() > 0 && null != passcode && passcode.length() > 0) {
rq.setUserIdentityRQ(UserIdentityRQ.usernamePasscode(username, passcode.toCharArray(), true));
}
Example, pinging the PACS (using the setup above):
String[] TRANSFER_SYNTAX_CHAIN = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian
};
// Define transfer capabilities for verification SOP class
ae.addTransferCapability(
new TransferCapability(null,
/* SOP Class */ UID.Verification,
/* Role */ TransferCapability.Role.SCU,
/* Transfer syntax */ TRANSFER_SYNTAX_CHAIN)
);
// Setup presentation context
rq.addPresentationContext(
new PresentationContext(
rq.getNumberOfPresentationContexts() * 2 + 1,
/* abstract syntax */ UID.Verification,
/* transfer syntax */ TRANSFER_SYNTAX_CHAIN
)
);
rq.addRoleSelection(new RoleSelection(UID.Verification, /* is SCU? */ true, /* is SCP? */ false));
try {
// 1) Open a connection to the SCP
Association association = ae.connect(local, remote, rq);
// 2) PING!
DimseRSP rsp = association.cecho();
rsp.next(); // Consume reply, which may fail
// Still here? Success!
// 3) Close the connection to the SCP
if (as.isReadyForDataTransfer()) {
as.waitForOutstandingRSP();
as.release();
}
} catch (Throwable ignore) {
// Failure
}
Another example, retrieving studies from a PACS given accession numbers; setting up the query and handling the result:
String modality = null; // e.g. "OT"
String accessionNumber = "1234567890";
//--------------------------------------------------------
// HERE follows setup of a query, using an Attributes object
//--------------------------------------------------------
Attributes query = new Attributes();
// Indicate character set
{
int tag = Tag.SpecificCharacterSet;
VR vr = ElementDictionary.vrOf(tag, query.getPrivateCreator(tag));
query.setString(tag, vr, "ISO_IR 100");
}
// Study level query
{
int tag = Tag.QueryRetrieveLevel;
VR vr = ElementDictionary.vrOf(tag, query.getPrivateCreator(tag));
query.setString(tag, vr, "STUDY");
}
// Accession number
{
int tag = Tag.AccessionNumber;
VR vr = ElementDictionary.vrOf(tag, query.getPrivateCreator(tag));
query.setString(tag, vr, accessionNumber);
}
// Optionally filter on modality in study if 'modality' is provided,
// otherwise retrieve modality
{
int tag = Tag.ModalitiesInStudy;
VR vr = ElementDictionary.vrOf(tag, query.getPrivateCreator(tag));
if (null != modality && modality.length() > 0) {
query.setString(tag, vr, modality);
} else {
query.setNull(tag, vr);
}
}
// We are interested in study instance UID
{
int tag = Tag.StudyInstanceUID;
VR vr = ElementDictionary.vrOf(tag, query.getPrivateCreator(tag));
query.setNull(tag, vr);
}
// Do the actual query, needing an AppliationEntity (ae),
// a local (local) and remote (remote) Connection, and
// an AAssociateRQ (rq) set up earlier.
try {
// 1) Open a connection to the SCP
Association as = ae.connect(local, remote, rq);
// 2) Query
int priority = 0x0002; // low for the sake of demo :)
as.cfind(UID.StudyRootQueryRetrieveInformationModelFind, priority, query, null,
new DimseRSPHandler(as.nextMessageID()) {
#Override
public void onDimseRSP(Association assoc, Attributes cmd,
Attributes response) {
super.onDimseRSP(assoc, cmd, response);
int status = cmd.getInt(Tag.Status, -1);
if (Status.isPending(status)) {
//--------------------------------------------------------
// HERE follows handling of the response, which
// is just another Attributes object
//--------------------------------------------------------
String studyInstanceUID = response.getString(Tag.StudyInstanceUID);
// etc...
}
}
});
// 3) Close the connection to the SCP
if (as.isReadyForDataTransfer()) {
as.waitForOutstandingRSP();
as.release();
}
}
catch (Exception e) {
// Failure
}
More on this at https://github.com/FrodeRanders/dicom-tools

How to get rights to access another mailbox calendar using EWS JAVA API

I am able to get the meeting rooms available in my Organisation using the below code, I need to get the appointment of the particular room, so i have used the below code for it.`
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
static ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
ExchangeCredentials credentials = new WebCredentials("xxx#yy.com", "zzzz");
service.setCredentials(credentials);
try {
System.out.println("Check");
service.autodiscoverUrl("xxx#yy.com",new RedirectionUrlCallback());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NameResolutionCollection nameResolutions = service.resolveName("MeetingRoom1",ResolveNameSearchLocation.DirectoryOnly, true);
System.out.println("nameResolutions==="+nameResolutions.getCount());
for(NameResolution nameResolution : nameResolutions)
{
System.out.println("NAME==="+nameResolution.getContact().getDisplayName());
}
Date startDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DATE, 30); // add 10 days
Date endDate = cal.getTime();
Mailbox meetingMailbox = new Mailbox("meetingroom-1#yy.com");
FolderId CalendarId = new FolderId(WellKnownFolderName.Calendar, meetingMailbox);
CalendarView cView = new CalendarView(startDate, endDate);
FindItemsResults<Appointment> appointments = service.findAppointments(CalendarId, cView);
for (Appointment a : appointments)
{
System.out.println("Subject: " + a.getSubject().toString() + " ");
System.out.println("Start: " + a.getStart().toString() + " ");
System.out.println("End: " + a.getEnd().toString());
System.out.println();
}
}`
If i execute this code, i am able to get the list of all meeting room available in my Organisation with name MeetingRoom1, then i am trying to access the particular meetingroom-1#yy.com to get the appointments for that room ,but throwing some exception like below.
Exception in thread "main" microsoft.exchange.webservices.data.ServiceResponseException: The specified folder could not be found in the store.
at microsoft.exchange.webservices.data.ServiceResponse.internalThrowIfNecessary(ServiceResponse.java:262)
at microsoft.exchange.webservices.data.ServiceResponse.throwIfNecessary(ServiceResponse.java:251)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:146)
at microsoft.exchange.webservices.data.ExchangeService.findItems(ExchangeService.java:807)
at microsoft.exchange.webservices.data.ExchangeService.findAppointments(ExchangeService.java:1089)
at com.hcl.GetRoomClass.main(GetRoomClass.java:58)
I guess it may be due to that i dont have access rights to access the calendar of the meeting room. How to proceed further to get the appointment. please help me .I need it in EWS-JAVA API.
Thanks in advance.
The account that your code is running under needs delegate access to the meeting room's calendar in order for that code to work. That's something that your admins need to configure for you on the server.

Categories