Skip to content

Instantly share code, notes, and snippets.

@rherrick
Created July 23, 2014 16:49
Show Gist options
  • Save rherrick/c6ce1a45f7c107f46f22 to your computer and use it in GitHub Desktop.
Save rherrick/c6ce1a45f7c107f46f22 to your computer and use it in GitHub Desktop.
Demonstrates the difference between getting a subject with user or null
/*
* org.nrg.xnat.restlet.extensions.GetRandomSubjectRestlet
* TIP is developed by the Neuroinformatics Research Group
* XNAT http://www.xnat.org
* Copyright (c) 2014, Washington University School of Medicine
* All Rights Reserved
*
* Released under the Simplified BSD.
*
* Last modified 7/22/14 9:24 AM
*/
package org.nrg.xnat.restlet.extensions;
import org.nrg.xdat.om.XnatSubjectdata;
import org.nrg.xft.presentation.FlattenedItemA;
import org.nrg.xft.presentation.ItemJSONBuilder;
import org.nrg.xnat.restlet.XnatRestlet;
import org.nrg.xnat.restlet.representations.JSONObjectRepresentation;
import org.nrg.xnat.restlet.resources.SecureResource;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
@XnatRestlet("/random/{SECURE}/{SUBJECT_ID}")
public class GetRandomSubjectRestlet extends SecureResource {
public static final String PARAM_SUBJECT_ID = "SUBJECT_ID";
public static final String PARAM_SECURE = "SECURE";
private final String _subjectId;
private final boolean _secure;
public GetRandomSubjectRestlet(Context context, Request request, Response response) {
super(context, request, response);
this.getVariants().add(new Variant(MediaType.ALL));
_subjectId = (String) getRequest().getAttributes().get(PARAM_SUBJECT_ID);
_secure = ((String) getRequest().getAttributes().get(PARAM_SECURE)).equalsIgnoreCase("secure");
}
@Override
public Representation represent(Variant variant) throws ResourceException {
FlattenedItemA.HistoryConfigI history = new FlattenedItemA.HistoryConfigI() {
@Override
public boolean getIncludeHistory() {
return false;
}
};
// Here add a test: if this is insecure access and the user is not approved for insecure access, throw an exception.
XnatSubjectdata subject = XnatSubjectdata.getXnatSubjectdatasById(_subjectId, _secure ? user : null, true);
if (subject != null) {
try {
return new JSONObjectRepresentation(MediaType.APPLICATION_JSON, (new ItemJSONBuilder()).call(subject.getItem(), history, false));
} catch (Exception e) {
throw new ResourceException(e);
}
} else {
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "Didn't find the subject " + _subjectId + " that was accessible by the current user " + user.getLogin());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment