Example usage for java.util UUID nameUUIDFromBytes

List of usage examples for java.util UUID nameUUIDFromBytes

Introduction

In this page you can find the example usage for java.util UUID nameUUIDFromBytes.

Prototype

public static UUID nameUUIDFromBytes(byte[] name) 

Source Link

Document

Static factory to retrieve a type 3 (name based) UUID based on the specified byte array.

Usage

From source file:org.apache.usergrid.persistence.cassandra.ConnectionRefImpl.java

public static UUID getIndexId(EntityRef connectingEntity, String connectionType, String connectedEntityType,
        ConnectedEntityRef... pairedConnections) {

    UUID uuid = null;/*from  w ww  .ja v a 2s. c o  m*/
    try {

        if (connectionsNull(pairedConnections) && ((connectionType == null) && (connectedEntityType == null))) {
            return connectingEntity.getUuid();
        }

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream(16 + (32 * pairedConnections.length));

        byteStream.write(uuidToBytesNullOk(connectingEntity.getUuid()));

        for (ConnectedEntityRef connection : pairedConnections) {
            String type = connection.getConnectionType();
            UUID id = connection.getUuid();

            byteStream.write(ascii(StringUtils.lowerCase(type)));
            byteStream.write(uuidToBytesNullOk(id));
        }

        if (connectionType == null) {
            connectionType = NULL_ENTITY_TYPE;
        }
        if (connectedEntityType == null) {
            connectedEntityType = NULL_ENTITY_TYPE;
        }

        byteStream.write(ascii(StringUtils.lowerCase(connectionType)));
        byteStream.write(ascii(StringUtils.lowerCase(connectedEntityType)));

        byte[] raw_id = byteStream.toByteArray();

        logger.info("raw connection index id: " + Hex.encodeHexString(raw_id));

        uuid = UUID.nameUUIDFromBytes(raw_id);

        logger.info("connection index uuid: " + uuid);
    } catch (IOException e) {
        logger.error("Unable to create connection index UUID", e);
    }
    return uuid;
}

From source file:com.cloud.hypervisor.xenserver.resource.Xenserver625StorageProcessorTest.java

@Test
@PrepareForTest({ Host.class, SR.class })
public void createNewFileSrTestThrowingDbUniqueException() throws XenAPIException, XmlRpcException {
    String uuid = "hostUuid";
    Mockito.when(citrixResourceBase._host.getUuid()).thenReturn(uuid);

    SR srMock = Mockito.mock(SR.class);
    Mockito.doReturn(srMock).when(xenserver625StorageProcessor)
            .retrieveAlreadyConfiguredSrWithoutException(connectionMock, pathMock);
    String srUuid = UUID.nameUUIDFromBytes(pathMock.getBytes()).toString();

    Host hostMock = Mockito.mock(Host.class);

    PowerMockito.mockStatic(Host.class);
    PowerMockito.when(Host.getByUuid(connectionMock, uuid)).thenReturn(hostMock);

    PowerMockito.mockStatic(SR.class);
    InternalError dbUniquenessException = new InternalError(
            "message: Db_exn.Uniqueness_constraint_violation(\"SR\", \"uuid\", \"fd3edbcf-f142-83d1-3fcb-029ca2446b68\")");

    PowerMockito.when(SR.introduce(Mockito.eq(connectionMock), Mockito.eq(srUuid), Mockito.eq(pathMock),
            Mockito.eq(pathMock), Mockito.eq("file"), Mockito.eq("file"), Mockito.eq(false),
            Mockito.anyMapOf(String.class, String.class))).thenThrow(dbUniquenessException);

    Mockito.doNothing().when(xenserver625StorageProcessor).removeSrAndPbdIfPossible(Mockito.eq(connectionMock),
            Mockito.any(SR.class), Mockito.any(PBD.class));

    SR sr = xenserver625StorageProcessor.createNewFileSr(connectionMock, pathMock);

    Assert.assertEquals(srMock, sr);/* ww  w .  j  a v  a 2s.  com*/
    Mockito.verify(xenserver625StorageProcessor, times(0)).removeSrAndPbdIfPossible(Mockito.eq(connectionMock),
            Mockito.any(SR.class), Mockito.any(PBD.class));
    Mockito.verify(xenserver625StorageProcessor).retrieveAlreadyConfiguredSrWithoutException(connectionMock,
            pathMock);
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTests.java

private void submitAndCheckJob(final int documentationId) throws Exception {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    final String commandArgs = "-c 'echo hello world'";

    final String clusterTag = "localhost";
    final List<ClusterCriteria> clusterCriteriaList = Lists
            .newArrayList(new ClusterCriteria(Sets.newHashSet(clusterTag)));

    final String setUpFile = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile")
            .getFile().getAbsolutePath();

    final String depFile1 = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "dep1")
            .getFile().getAbsolutePath();
    final Set<String> dependencies = Sets.newHashSet(depFile1);

    final String commandTag = "bash";
    final Set<String> commandCriteria = Sets.newHashSet(commandTag);
    final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, commandArgs,
            clusterCriteriaList, commandCriteria).withDisableLogArchival(true).withSetupFile(setUpFile)
                    .withDependencies(dependencies).withDescription(JOB_DESCRIPTION).build();

    final String id = this.submitJob(documentationId, jobRequest, null);
    this.waitForDone(id);

    this.checkJobStatus(documentationId, id);
    this.checkJob(documentationId, id, commandArgs);
    this.checkJobOutput(documentationId, id);
    this.checkJobRequest(documentationId, id, commandArgs, setUpFile, clusterTag, commandTag, depFile1);
    this.checkJobExecution(documentationId, id);
    this.checkJobCluster(documentationId, id);
    this.checkJobCommand(documentationId, id);
    this.checkJobApplications(documentationId, id);
    this.checkFindJobs(documentationId, id, JOB_USER);

    Assert.assertThat(this.jobRepository.count(), Matchers.is(1L));
    Assert.assertThat(this.jobRequestRepository.count(), Matchers.is(1L));
    Assert.assertThat(this.jobRequestMetadataRepository.count(), Matchers.is(1L));
    Assert.assertThat(this.jobExecutionRepository.count(), Matchers.is(1L));

    // Check if the cluster setup file is cached
    final String clusterSetUpFilePath = this.resourceLoader
            .getResource(BASE_DIR + CMD1_ID + FILE_DELIMITER + "setupfile").getFile().getAbsolutePath();
    Assert.assertTrue(Files.exists(Paths.get(new URI(this.baseCacheLocation).getPath(),
            UUID.nameUUIDFromBytes(clusterSetUpFilePath.getBytes(Charset.forName("UTF-8"))).toString())));
    // Test for conflicts
    this.testForConflicts(id, commandArgs, clusterCriteriaList, commandCriteria);
}

From source file:org.apache.nifi.admin.dao.impl.StandardUserDAO.java

@Override
public NiFiUser createUser(NiFiUser user) throws DataAccessException {
    if (user.getIdentity() == null) {
        throw new IllegalArgumentException("User identity must be specified.");
    }/*w w w.j  a  v  a 2s. com*/

    // ensure the user identity is not too lengthy
    if (user.getIdentity().length() > 4096) {
        throw new IllegalArgumentException("User identity must be less than 4096 characters.");
    }

    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        final String id = UUID.nameUUIDFromBytes(user.getIdentity().getBytes(StandardCharsets.UTF_8))
                .toString();

        // create a statement
        statement = connection.prepareStatement(INSERT_USER, Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, id);
        statement.setString(2, StringUtils.left(user.getIdentity(), 4096));
        statement.setString(3, StringUtils.left(user.getUserName(), 4096));
        statement.setString(4, StringUtils.left(user.getUserGroup(), 100));
        if (user.getLastVerified() != null) {
            statement.setTimestamp(5, new java.sql.Timestamp(user.getLastVerified().getTime()));
        } else {
            statement.setTimestamp(5, null);
        }
        statement.setString(6, StringUtils.left(user.getJustification(), 500));
        statement.setString(7, user.getStatus().toString());

        // insert the user
        int updateCount = statement.executeUpdate();
        if (updateCount == 1) {
            user.setId(id);
        } else {
            throw new DataAccessException("Unable to insert user.");
        }

        return user;
    } catch (SQLException sqle) {
        throw new DataAccessException(sqle);
    } catch (DataAccessException dae) {
        throw dae;
    } finally {
        RepositoryUtils.closeQuietly(rs);
        RepositoryUtils.closeQuietly(statement);
    }
}

From source file:com.cloud.hypervisor.xen.resource.Xenserver625StorageProcessor.java

@Override
public Answer backupSnapshot(CopyCommand cmd) {
    Connection conn = hypervisorResource.getConnection();
    DataTO srcData = cmd.getSrcTO();//from  www.  j a v  a 2s .  c o  m
    DataTO cacheData = cmd.getCacheTO();
    DataTO destData = cmd.getDestTO();
    int wait = cmd.getWait();
    PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore();
    String primaryStorageNameLabel = primaryStore.getUuid();
    String secondaryStorageUrl = null;
    NfsTO cacheStore = null;
    String destPath = null;
    if (cacheData != null) {
        cacheStore = (NfsTO) cacheData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = cacheData.getPath();
    } else {
        cacheStore = (NfsTO) destData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = destData.getPath();
    }

    SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData;
    SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData;
    String snapshotUuid = snapshotTO.getPath();

    String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
    String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
    Map<String, String> options = cmd.getOptions();
    // By default assume failure
    String details = null;
    String snapshotBackupUuid = null;
    boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
    try {
        SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
        if (primaryStorageSR == null) {
            throw new InternalErrorException(
                    "Could not backup snapshot because the primary Storage SR could not be created from the name label: "
                            + primaryStorageNameLabel);
        }
        // String psUuid = primaryStorageSR.getUuid(conn);
        Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));

        VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
        String snapshotPaUuid = null;

        URI uri = new URI(secondaryStorageUrl);
        String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
        DataStoreTO destStore = destData.getDataStore();
        String folder = destPath;
        String finalPath = null;

        String localMountPoint = BaseMountPointOnHost + File.separator
                + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
        if (fullbackup) {
            SR snapshotSr = null;
            Task task = null;
            try {
                String localDir = "/var/cloud_mount/"
                        + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes());
                mountNfs(conn, secondaryStorageMountPath, localDir);
                boolean result = makeDirectory(conn, localDir + "/" + folder);
                if (!result) {
                    details = " Filed to create folder " + folder + " in secondary storage";
                    s_logger.warn(details);
                    return new CopyCmdAnswer(details);
                }

                snapshotSr = createFileSr(conn, secondaryStorageMountPath, folder);

                task = snapshotVdi.copyAsync2(conn, snapshotSr, null, null);
                // poll every 1 seconds ,
                hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
                hypervisorResource.checkForSuccess(conn, task);
                VDI backedVdi = Types.toVDI(task, conn);
                snapshotBackupUuid = backedVdi.getUuid(conn);

                if (destStore instanceof SwiftTO) {
                    try {
                        String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                        String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore,
                                snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait);
                        String swiftPath = container + File.separator + destSnapshotName;
                        finalPath = swiftPath;
                    } finally {
                        try {
                            deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath,
                                    snapshotBackupUuid);
                        } catch (Exception e) {
                            s_logger.debug("Failed to delete snapshot on cache storages", e);
                        }
                    }

                } else if (destStore instanceof S3TO) {
                    try {
                        finalPath = backupSnapshotToS3(conn, (S3TO) destStore, snapshotSr.getUuid(conn), folder,
                                snapshotBackupUuid, isISCSI, wait);
                        if (finalPath == null) {
                            throw new CloudRuntimeException(
                                    "S3 upload of snapshots " + snapshotBackupUuid + " failed");
                        }
                    } finally {
                        try {
                            deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath,
                                    snapshotBackupUuid);
                        } catch (Exception e) {
                            s_logger.debug("Failed to delete snapshot on cache storages", e);
                        }
                    }
                    // finalPath = folder + File.separator + snapshotBackupUuid;
                } else {
                    finalPath = folder + File.separator + snapshotBackupUuid;
                }

            } finally {
                if (task != null) {
                    try {
                        task.destroy(conn);
                    } catch (Exception e) {
                        s_logger.warn(
                                "unable to destroy task(" + task.toWireString() + ") due to " + e.toString());
                    }
                }
                if (snapshotSr != null) {
                    hypervisorResource.removeSR(conn, snapshotSr);
                }
            }
        } else {
            String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
            if (destStore instanceof SwiftTO) {
                String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid,
                        snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait);
                finalPath = container + File.separator + snapshotBackupUuid;
            } else if (destStore instanceof S3TO) {
                finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder,
                        snapshotPaUuid, isISCSI, wait);
                if (finalPath == null) {
                    throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed");
                }
            } else {
                snapshotBackupUuid = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder,
                        secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI,
                        wait);

                finalPath = folder + File.separator + snapshotBackupUuid;
            }
        }
        String volumeUuid = snapshotTO.getVolume().getPath();
        destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);

        SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(finalPath);
        if (fullbackup) {
            newSnapshot.setParentSnapshotPath(null);
        } else {
            newSnapshot.setParentSnapshotPath(prevBackupUuid);
        }
        return new CopyCmdAnswer(newSnapshot);
    } catch (Types.XenAPIException e) {
        details = "BackupSnapshot Failed due to " + e.toString();
        s_logger.warn(details, e);
    } catch (Exception e) {
        details = "BackupSnapshot Failed due to " + e.getMessage();
        s_logger.warn(details, e);
    }

    return new CopyCmdAnswer(details);
}

From source file:com.cloud.hypervisor.xenserver.resource.Xenserver625StorageProcessorTest.java

@Test
@PrepareForTest({ Host.class, SR.class, PBD.class })
public void createNewFileSrTest() throws XenAPIException, XmlRpcException {
    String uuid = "hostUuid";
    Mockito.when(citrixResourceBase._host.getUuid()).thenReturn(uuid);

    SR srMock = Mockito.mock(SR.class);
    Mockito.doReturn(srMock).when(xenserver625StorageProcessor)
            .retrieveAlreadyConfiguredSrWithoutException(connectionMock, pathMock);
    String srUuid = UUID.nameUUIDFromBytes(pathMock.getBytes()).toString();

    Host hostMock = Mockito.mock(Host.class);

    PowerMockito.mockStatic(Host.class);
    PowerMockito.when(Host.getByUuid(connectionMock, uuid)).thenReturn(hostMock);

    PowerMockito.mockStatic(SR.class);
    PowerMockito.when(SR.introduce(Mockito.eq(connectionMock), Mockito.eq(srUuid), Mockito.eq(pathMock),
            Mockito.eq(pathMock), Mockito.eq("file"), Mockito.eq("file"), Mockito.eq(false),
            Mockito.anyMapOf(String.class, String.class))).thenReturn(srMock);

    PowerMockito.mockStatic(PBD.class);
    PBD pbdMock = Mockito.mock(PBD.class);
    PowerMockito.when(PBD.create(Mockito.eq(connectionMock), Mockito.any(Record.class))).thenReturn(pbdMock);

    Mockito.doNothing().when(xenserver625StorageProcessor).removeSrAndPbdIfPossible(Mockito.eq(connectionMock),
            Mockito.any(SR.class), Mockito.any(PBD.class));
    SR sr = xenserver625StorageProcessor.createNewFileSr(connectionMock, pathMock);

    Assert.assertEquals(srMock, sr);/*from w  w  w.  j a  v  a  2  s. com*/
    Mockito.verify(xenserver625StorageProcessor, times(0)).removeSrAndPbdIfPossible(Mockito.eq(connectionMock),
            Mockito.any(SR.class), Mockito.any(PBD.class));
    Mockito.verify(xenserver625StorageProcessor, times(0))
            .retrieveAlreadyConfiguredSrWithoutException(connectionMock, pathMock);

    Mockito.verify(srMock).scan(connectionMock);
    Mockito.verify(pbdMock).plug(connectionMock);

    PowerMockito.verifyStatic();
    SR.introduce(Mockito.eq(connectionMock), Mockito.eq(srUuid), Mockito.eq(pathMock), Mockito.eq(pathMock),
            Mockito.eq("file"), Mockito.eq("file"), Mockito.eq(false),
            Mockito.anyMapOf(String.class, String.class));
    PBD.create(Mockito.eq(connectionMock), Mockito.any(Record.class));
}

From source file:org.opendaylight.genius.interfacemanager.renderer.ovs.utilities.SouthboundUtils.java

public static String generateOfTunnelName(BigInteger dpId, IfTunnel ifTunnel) {
    String sourceKey = new String(ifTunnel.getTunnelSource().getValue());
    String remoteKey = new String(ifTunnel.getTunnelDestination().getValue());
    if (ifTunnel.isTunnelSourceIpFlow() != null) {
        sourceKey = "flow";
    }// ww  w. j a  v  a2 s . co m
    if (ifTunnel.isTunnelRemoteIpFlow() != null) {
        remoteKey = "flow";
    }
    String tunnelNameKey = dpId.toString() + sourceKey + remoteKey;
    String uuidStr = UUID.nameUUIDFromBytes(tunnelNameKey.getBytes()).toString().substring(0, 12).replace("-",
            "");
    return String.format("%s%s", "tun", uuidStr);
}

From source file:org.dragonet.net.DragonetSession.java

public void processDataPacket(RaknetDataPacket dataPacket) {
    if (dataPacket.getSequenceNumber() - this.lastSequenceNum > 1) {
        for (int i = this.lastSequenceNum + 1; i < dataPacket.getSequenceNumber(); i++) {
            this.queueNACK.add(i);
        }/*from   w w  w  . j  av  a2s  .co m*/
    } else {
        this.lastSequenceNum = dataPacket.getSequenceNumber();
    }
    this.queueACK.add(dataPacket.getSequenceNumber());
    if (dataPacket.getEncapsulatedPackets().isEmpty()) {
        return;
    }
    for (EncapsulatedPacket epacket : dataPacket.getEncapsulatedPackets()) {
        PEPacket packet = PEPacket.fromBinary(epacket.buffer);
        if (packet == null) {
            continue;
        }
        switch (packet.pid()) {
        case PEPacketIDs.PING:
            PingPongPacket pkPong = new PingPongPacket();
            pkPong.pingID = ((PingPongPacket) packet).pingID;
            this.send(pkPong, 0);
            break;
        case PEPacketIDs.CLIENT_CONNECT:
            if (this.loginStage != 0)
                break;
            this.clientSessionID = ((ClientConnectPacket) packet).sessionID;
            ServerHandshakePacket pkServerHandshake = new ServerHandshakePacket();
            pkServerHandshake.port = (short) (this.remotePort & 0xFFFF);
            pkServerHandshake.session = this.clientSessionID;
            pkServerHandshake.session2 = 0x04440BA9L;
            this.loginStage = 1;
            this.send(pkServerHandshake);
            break;
        case PEPacketIDs.CLIENT_HANDSHAKE:
            if (this.loginStage != 1)
                break;
            this.loginStage = 2;
            break;
        case PEPacketIDs.LOGIN_PACKET:
            if (this.loginStage != 2)
                break;
            LoginPacket packetLogin = (LoginPacket) packet;
            this.username = packetLogin.username;

            this.translator = TranslatorProvider.getByPEProtocolID(this, packetLogin.protocol1);
            if (!(this.translator instanceof BaseTranslator)) {
                LoginStatusPacket pkLoginStatus = new LoginStatusPacket();
                pkLoginStatus.status = 2;
                this.send(pkLoginStatus);
                this.disconnect("Unsupported game version! ");
                break;
            }

            LoginStatusPacket pkLoginStatus = new LoginStatusPacket();
            pkLoginStatus.status = 0;
            this.send(pkLoginStatus);

            this.getLogger().info("Sent LoginStatusPacket! ");

            Matcher matcher = patternUsername.matcher(this.username);
            if (!matcher.matches()) {
                this.disconnect("Bad username! ");
                break;
            }

            this.loginStage = 3;
            this.setPlayer(new PlayerProfile(this.username,
                    UUID.nameUUIDFromBytes(MD5Encrypt.encryptString(this.username))));
            break;
        default:
            if (this.loginStage != 3)
                break;
            if (!(this.translator instanceof BaseTranslator))
                break;
            this.dServer.getThreadPool().submit(new ProcessPEPacketTask(this, packet));
            break;
        }
    }
}

From source file:com.hybris.mobile.Hybris.java

public void setUuid(Context context) {
    final String uuid = Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_UUID);
    UUID unique_uid;//from   w w  w.  j  a  v a  2  s.c  om
    if (uuid.isEmpty()) {
        final String id = Hybris.getSharedPreferenceString(InternalConstants.KEY_PREF_DEVICE_ID);
        if (!id.isEmpty()) {
            // Use the ids previously computed and stored in the prefs file
            try {
                unique_uid = UUID.nameUUIDFromBytes(id.getBytes("utf8"));
            } catch (UnsupportedEncodingException e) {
                LoggingUtils.e(LOG_TAG, "Error creating UUID " + e.getLocalizedMessage(), getAppContext());
                throw new RuntimeException(e);
            }
        } else {
            try {
                final String deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                        .getDeviceId();
                unique_uid = deviceId != null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8"))
                        : UUID.randomUUID();
            } catch (UnsupportedEncodingException e) {
                LoggingUtils.e(LOG_TAG, "Error creating UUID " + e.getLocalizedMessage(), getAppContext());
                throw new RuntimeException(e);
            }
        }
        // Write the value out to the prefs file
        Hybris.setSharedPreferenceString(InternalConstants.KEY_PREF_UUID, unique_uid.toString());

    }
}

From source file:com.cloud.hypervisor.xenserver.resource.Xenserver625StorageProcessor.java

@Override
public Answer backupSnapshot(final CopyCommand cmd) {
    final Connection conn = hypervisorResource.getConnection();
    final DataTO srcData = cmd.getSrcTO();
    final DataTO cacheData = cmd.getCacheTO();
    final DataTO destData = cmd.getDestTO();
    final int wait = cmd.getWait();
    final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore();
    final String primaryStorageNameLabel = primaryStore.getUuid();
    String secondaryStorageUrl = null;
    NfsTO cacheStore = null;//  w w w.  j  av  a  2  s . com
    String destPath = null;
    if (cacheData != null) {
        cacheStore = (NfsTO) cacheData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = cacheData.getPath();
    } else {
        cacheStore = (NfsTO) destData.getDataStore();
        secondaryStorageUrl = cacheStore.getUrl();
        destPath = destData.getPath();
    }

    final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData;
    final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData;
    final String snapshotUuid = snapshotTO.getPath();

    final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
    final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
    final Map<String, String> options = cmd.getOptions();
    // By default assume failure
    String details = null;
    String snapshotBackupUuid = null;
    final boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
    Long physicalSize = null;
    try {
        final SR primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
        if (primaryStorageSR == null) {
            throw new InternalErrorException(
                    "Could not backup snapshot because the primary Storage SR could not be created from the name label: "
                            + primaryStorageNameLabel);
        }
        // String psUuid = primaryStorageSR.getUuid(conn);
        final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));

        final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
        final String snapshotPaUuid = null;

        final URI uri = new URI(secondaryStorageUrl);
        final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
        final DataStoreTO destStore = destData.getDataStore();
        final String folder = destPath;
        String finalPath = null;

        final String localMountPoint = BaseMountPointOnHost + File.separator
                + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
        if (fullbackup) {
            SR snapshotSr = null;
            Task task = null;
            try {
                final String localDir = "/var/cloud_mount/"
                        + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes());
                mountNfs(conn, secondaryStorageMountPath, localDir);
                final boolean result = makeDirectory(conn, localDir + "/" + folder);
                if (!result) {
                    details = " Filed to create folder " + folder + " in secondary storage";
                    s_logger.warn(details);
                    return new CopyCmdAnswer(details);
                }

                snapshotSr = createFileSr(conn, secondaryStorageMountPath, folder);

                task = snapshotVdi.copyAsync(conn, snapshotSr, null, null);
                // poll every 1 seconds ,
                hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
                hypervisorResource.checkForSuccess(conn, task);
                final VDI backedVdi = Types.toVDI(task, conn);
                snapshotBackupUuid = backedVdi.getUuid(conn);
                physicalSize = backedVdi.getPhysicalUtilisation(conn);

                if (destStore instanceof SwiftTO) {
                    try {
                        final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                        final String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore,
                                snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait);
                        final String swiftPath = container + File.separator + destSnapshotName;
                        finalPath = swiftPath;
                    } finally {
                        try {
                            deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath,
                                    snapshotBackupUuid);
                        } catch (final Exception e) {
                            s_logger.debug("Failed to delete snapshot on cache storages", e);
                        }
                    }

                } else if (destStore instanceof S3TO) {
                    try {
                        finalPath = backupSnapshotToS3(conn, (S3TO) destStore, snapshotSr.getUuid(conn), folder,
                                snapshotBackupUuid, isISCSI, wait);
                        if (finalPath == null) {
                            throw new CloudRuntimeException(
                                    "S3 upload of snapshots " + snapshotBackupUuid + " failed");
                        }
                    } finally {
                        try {
                            deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath,
                                    snapshotBackupUuid);
                        } catch (final Exception e) {
                            s_logger.debug("Failed to delete snapshot on cache storages", e);
                        }
                    }
                    // finalPath = folder + File.separator +
                    // snapshotBackupUuid;
                } else {
                    finalPath = folder + File.separator + snapshotBackupUuid;
                }

            } finally {
                if (task != null) {
                    try {
                        task.destroy(conn);
                    } catch (final Exception e) {
                        s_logger.warn(
                                "unable to destroy task(" + task.toWireString() + ") due to " + e.toString());
                    }
                }
                if (snapshotSr != null) {
                    hypervisorResource.removeSR(conn, snapshotSr);
                }
            }
        } else {
            final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
            if (destStore instanceof SwiftTO) {
                final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
                snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid,
                        snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait);
                finalPath = container + File.separator + snapshotBackupUuid;
            } else if (destStore instanceof S3TO) {
                finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder,
                        snapshotPaUuid, isISCSI, wait);
                if (finalPath == null) {
                    throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed");
                }
            } else {
                final String result = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder,
                        secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI,
                        wait);
                final String[] tmp = result.split("#");
                snapshotBackupUuid = tmp[0];
                physicalSize = Long.parseLong(tmp[1]);
                finalPath = folder + File.separator + snapshotBackupUuid;
            }
        }
        final String volumeUuid = snapshotTO.getVolume().getPath();
        destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);

        final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
        newSnapshot.setPath(finalPath);
        newSnapshot.setPhysicalSize(physicalSize);
        if (fullbackup) {
            newSnapshot.setParentSnapshotPath(null);
        } else {
            newSnapshot.setParentSnapshotPath(prevBackupUuid);
        }
        return new CopyCmdAnswer(newSnapshot);
    } catch (final Types.XenAPIException e) {
        details = "BackupSnapshot Failed due to " + e.toString();
        s_logger.warn(details, e);
    } catch (final Exception e) {
        details = "BackupSnapshot Failed due to " + e.getMessage();
        s_logger.warn(details, e);
    }

    return new CopyCmdAnswer(details);
}