Skip to content

Instantly share code, notes, and snippets.

@axeda
Created July 26, 2011 14:34
Show Gist options
  • Select an option

  • Save axeda/1106907 to your computer and use it in GitHub Desktop.

Select an option

Save axeda/1106907 to your computer and use it in GitHub Desktop.
Retrieve an asset-uploaded file
import com.axeda.drm.sdk.Context
import com.axeda.drm.sdk.data.UploadedFile
import com.axeda.drm.sdk.data.UploadedFileFinder
import com.axeda.drm.sdk.device.Device
import com.axeda.drm.sdk.device.DeviceFinder
// This script requires parameter "id"
Context ctx = Context.create(parameters.username);
def response = ''
try {
DeviceFinder deviceFinder = new DeviceFinder(ctx, new Identifier(parameters.id as Integer));
Device device = deviceFinder.find();
UploadedFileFinder uff = new UploadedFileFinder(ctx)
uff.device = device
uff.hint = 'photo'
def ufiles = uff.findAll()
UploadedFile ufile
if (ufiles.size() > 0) {
ufile = ufiles[0]
File f = ufile.extractFile()
response = getBytes(f).encodeBase64(false).toString()
}
}
catch (Exception e) {
logger.info(e.message);
response = [
faultcode: 'Groovy Exception',
faultstring: e.message
];
}
return ['Content-Type': 'data:image/png;base64', 'Content': response];
static byte[] getBytes(File file) throws IOException {
return getBytes(new FileInputStream(file));
}
static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream answer = new ByteArrayOutputStream();
// reading the content of the file within a byte buffer
byte[] byteBuffer = new byte[8192];
int nbByteRead /* = 0*/;
try {
while ((nbByteRead = is.read(byteBuffer)) != -1) {
// appends buffer
answer.write(byteBuffer, 0, nbByteRead);
}
} finally {
is.close()
}
return answer.toByteArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment