}
default: {
localPath = null;
}
}
ByteDataInput input = null;
try {
input = new SimpleByteDataInput(inputStream);
expectHeader(input, DomainControllerProtocol.PARAM_NUM_FILES);
int numFiles = input.readInt();
log.debugf("Received %d files for %s", numFiles, localPath);
switch (numFiles) {
case -1: { // Not found on DC
break;
}
case 0: { // Found on DC, but was an empty dir
if (!localPath.mkdirs()) {
throw new IOException("Unable to create local directory: " + localPath);
}
break;
}
default: { // Found on DC
for (int i = 0; i < numFiles; i++) {
expectHeader(input, DomainControllerProtocol.FILE_START);
expectHeader(input, DomainControllerProtocol.PARAM_FILE_PATH);
final String path = input.readUTF();
expectHeader(input, DomainControllerProtocol.PARAM_FILE_SIZE);
final long length = input.readLong();
log.debugf("Received file [%s] of length %d", path, length);
final File file = new File(localPath, path);
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
throw new IOException("Unable to create local directory " + localPath.getParent());
}
long totalRead = 0;
OutputStream fileOut = null;
try {
fileOut = new BufferedOutputStream(new FileOutputStream(file));
final byte[] buffer = new byte[8192];
int read;
while (totalRead < length && (read = input.read(buffer, 0, Math.min((int) (length - totalRead), buffer.length))) != -1) {
if (read > 0) {
fileOut.write(buffer, 0, read);
totalRead += read;
}
}
} finally {
if (fileOut != null) {
fileOut.close();
}
}
if (totalRead != length) {
throw new IOException("Did not read the entire file. Missing: " + (length - totalRead));
}
expectHeader(input, DomainControllerProtocol.FILE_END);
}
}
}
input.close();
} finally {
StreamUtils.safeClose(input);
}
return localPath;
}