auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: if (getDisk().getDiskStorageType() == DiskStorageType.LUN) { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK_NO_DOMAIN START : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK_NO_DOMAIN; END } else { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK; } default: return AuditLogType.UNASSIGNED; } } lun disks removal can't fail actually in the execute part, as it's a simple removal from the db..but i don't mind having it for the future in case we'll add ops that might fail.

Target:
public AuditLogType getAuditLogTypeValue() { switch (getActionState()) { case EXECUTE: if (getDisk().getDiskStorageType() == DiskStorageType.LUN) { return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK_NO_DOMAIN : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK_NO_DOMAIN; } return getSucceeded() ? AuditLogType.USER_FINISHED_REMOVE_DISK : AuditLogType.USER_FINISHED_FAILED_REMOVE_DISK; default: return AuditLogType.UNASSIGNED; } }
Source:
protected void endStepJobCommitted() { START endStepJob(JobExecutionStatus.FINISHED, getStepMessageMap(JobExecutionStatus.FINISHED, " "), true); END } why sending space?

Target:
protected void endStepJobCommitted() { endStepJob(JobExecutionStatus.FINISHED, getStepMessageMap(JobExecutionStatus.FINISHED, null), true); }
Source:
public List<File> getExtensionsDirectories() { String path = getProperty("ENGINE_EXTENSION_PATH"); if (path == null) { START log.warn("No extension configurations directories were provided"); END return Collections.emptyList(); } List<File> results = new ArrayList<File>(); for (String currentPath : path.split(":")) { if (StringUtils.isNotBlank(currentPath)) { results.add(new File(currentPath)); } } return results; } the need of warning is up to caller not this infrastructure component.

Target:
public List<File> getExtensionsDirectories() { String path = getProperty("ENGINE_EXTENSION_PATH"); if (path == null) { return Collections.emptyList(); } List<File> results = new ArrayList<File>(); for (String currentPath : path.split(":")) { if (StringUtils.isNotBlank(currentPath)) { results.add(new File(currentPath)); } } return results; }
Source:
public String getProfileName() { Properties config = (Properties) context.get(ExtensionProperties.CONFIGURATION); START return config.getProperty("ovirt.engine.aaa.authz.profile.name"); END } why do you need config temp variable?

Target:
public String getProfileName() { return ((Properties) context.get(ExtensionProperties.CONFIGURATION)).getProperty("ovirt.engine.aaa.authz.profile.name"); }
Source:
private DbUserCacheManager() { for (AuthenticationProfile profile : AuthenticationProfileRepository.getInstance().getProfiles()) { directoriesMap.put(profile.getDirectory().getName(), profile.getDirectory()); START } END } I am unsure why you need to cache yet another instance of this map... just query the repository at each iteration.

Target:
private DbUserCacheManager() { }
Source:
private static void createOutputDirectory(String outputDirectory) { START File outputDir = new File(outputDirectory); END if (!outputDir.exists()) { outputDir.mkdirs(); } } I think we should reuse this File object, returning it, for example, and then pass it to the copy medhod, instead of the string.

Target:
private static File createOutputDirectory(String outputDirectory) { File outputDir = new File(outputDirectory); if (!outputDir.exists()) { outputDir.mkdirs(); } return outputDir; }
Source:
public NotificationService(NotificationProperties prop) throws NotificationServiceException { this.prop = prop; this.eventsManager = new EventsManager(); this.firstMatchSimpleFilter = new FirstMatchSimpleFilter(); Smtp smtp = new Smtp(prop); smtp.addObserver(this.eventsManager); START addTransport(smtp); END this.firstMatchSimpleFilter.registerTransport(smtp); configurationFilters = FirstMatchSimpleFilter.parse(prop.getProperty(NotificationProperties.FILTER)); markOldEventsAsProcessed(); } if transports is private, there is not really need for a method that wraps list add.

Target:
public NotificationService(NotificationProperties prop) throws NotificationServiceException { this.prop = prop; this.eventsManager = new EventsManager(); this.firstMatchSimpleFilter = new FirstMatchSimpleFilter(); configurationFilters = FirstMatchSimpleFilter.parse(prop.getProperty(NotificationProperties.FILTER)); markOldEventsAsProcessed(); }
Source:
START protected java.util.ArrayList<Guid> getTemplatesList() { END return getParameters().getEntitiesId(); } please import java.util instead of explicitly writing here

Target:
protected ArrayList<Guid> getTemplatesList() { return getParameters().getEntitiesId(); }
Source:
START private boolean networkExists() { END List<NetworkCluster> networks = getNetworkClusterDAO().getAllForCluster(getVdsGroupId()); for (NetworkCluster networkCluster : networks) { if (networkCluster.getNetworkId().equals( getNetworkCluster().getNetworkId())) { return true; } } return false; } Why not just use the get method that accepts NetworkClusterId?

Target:
private boolean networkExists() { return getNetworkClusterDAO().get(getNetworkCluster().getId()) != null; }
Source:
public VdsManager GetVdsManager(Guid vdsId) { START return GetVdsManager(vdsId, true); END } true=>false

Target:
public VdsManager GetVdsManager(Guid vdsId) { return GetVdsManager(vdsId, false); }
Source:
public VdsIdVDSCommandBase(P parameters) { START this(parameters, true); END } true=>false

Target:
public VdsIdVDSCommandBase(P parameters) { this(parameters, false); }
Source:
public boolean isEmpty(){ START return getItems() == null || getItems().size() == 0; END } Don't think items can be null, and ArrayList (as well as List and Collection) has an isEmpty() method itself...

Target:
public boolean isEmpty(){ return getItems() == null || getItems().isEmpty(); }
Source:
START public static Map<Integer, Map<Version, Boolean>> getBalloonSupportMap() { END return balloonSupportMap; } no need to have this getter public

Target:
private static Map<Integer, Map<Version, Boolean>> getBalloonSupportMap() { return balloonSupportMap; }
Source:
protected Permit addParents(Permit permit) { if (permit == null) { START System.out.println("permit is null"); END } if (parent == null) { System.out.println("parent is null"); } return parent.addParents(permit); } Sorry wrong patch, will fix these

Target:
protected Permit addParents(Permit permit) { return parent.addParents(permit); }
Source:
public static EventNotificationMethod valueOfString(String value) { START return valueOf(value != null ? value.toUpperCase() : null); END } valueOf does not support nulls - this will cause an NPE, just like the code before the patch. I'm guessing you meant to do something like this: return value != null ? valueOf(value.toUpperCase()) : null;

Target:
public static EventNotificationMethod valueOfString(String value) { return value != null ? valueOf(value.toUpperCase()) : null; }
Source:
public void testDoGet_NotFound_MissingFile() throws IOException, ServletException { final IConfigUtilsInterface configUtils = Mockito.mock(IConfigUtilsInterface.class); START Config.setConfigUtils(configUtils); END // The file should not exist, and thus return a 404. testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendError(HttpServletResponse.SC_NOT_FOUND); } are you sure this is required?

Target:
public void testDoGet_NotFound_MissingFile() throws IOException, ServletException { // The file should not exist, and thus return a 404. testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendError(HttpServletResponse.SC_NOT_FOUND); }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Locate the requested file: File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); // Send the content of the file: // type is the default MIME type of the Servlet. START ServletUtils.sendFile(request, response, file, type, cache, file == base && required); END } remove file==base as the entire tree should be effected.

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Locate the requested file: File file = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); file = checkForIndex(request, response, file, request.getPathInfo()); // Send the content of the file: // type is the default MIME type of the Servlet. ServletUtils.sendFile(request, response, file, type, cache, required); }
Source:
protected boolean isGhost(EntityModel<String> value) { String text = value.getEntity(); START return text == null || text.isEmpty(); END } Please use StringHelper.isNullOrEmpty()

Target:
protected boolean isGhost(EntityModel<String> value) { return StringUtils.isEmpty(value.getEntity()); }
Source:
void onWindowFocusChange(boolean inFocus) { GridTimer modelTimer = getModelTimer(); // Change refresh rate only when the model timer is currently active and not paused if (modelTimer.isActive() && !modelTimer.isPaused()) { if (inFocus) { START modelTimer.stop(); END modelTimer.setRefreshRate(readRefreshRate()); } else { modelTimer.stop(); modelTimer.setRefreshRate(OUT_OF_FOCUS_REFRESH_RATE); } modelTimer.start(); } } Hm, any reason why not add: modelTimer.stop(); before the if block, which is analogous to having: modelTimer.start(); after the if block?

Target:
void onWindowFocusChange(boolean inFocus) { GridTimer modelTimer = getModelTimer(); // Change refresh rate only when the model timer is currently active and not paused if (modelTimer.isActive() && !modelTimer.isPaused()) { modelTimer.stop(); if (inFocus) { modelTimer.setRefreshRate(readRefreshRate()); } else { modelTimer.setRefreshRate(OUT_OF_FOCUS_REFRESH_RATE); } modelTimer.start(); } }
Source:
public void setComment(String value) { if (value == null) { this.comment = ""; } else { this.comment = value; START } END } this.comment = (value == null) ? "" : value;

Target:
public void setComment(String value) { this.comment = (value == null) ? "" : value; }
Source:
public void authenticate(String user, String password) { String adminUser = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.name"); String adminPassword = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.password"); if (!ObjectUtils.equals(user, adminUser) START || !ObjectUtils.equals(password, adminPassword)) { END throw new AAAExtensionException(AAAExtensionException.AAAExtensionError.INCORRECT_CREDENTIALS, ""); } } hmmm... why not: !(equals && equals) :)

Target:
public void authenticate(String user, String password) { String adminUser = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.name"); String adminPassword = ((Properties)context.get(ExtensionProperties.CONFIGURATION)).getProperty("config.authn.user.password"); if (!user.equals(adminUser) || !password.equals(adminPassword)) { throw new AAAExtensionException(AAAExtensionException.AAAExtensionError.INCORRECT_CREDENTIALS, ""); } }
Source:
public ExtensionEntry(Properties props) { START this.file = null; END context = new EnumMap<>(ExtensionProperties.class); load(props); } no need for this.file = null as it will be null.

Target:
public ExtensionEntry(Properties props) { load(props); }
Source:
private BrokerCommandBase CreateCommand(AdActionType action, LdapBrokerBaseParameters parameters) { Class type; try { type = Class.forName(GetCommandTypeName(action)); Constructor info = ReflectionUtils.findConstructor(type, parameters.getClass()); Object tempVar = info.newInstance(parameters); return (BrokerCommandBase) ((tempVar instanceof BrokerCommandBase) ? tempVar : null); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException START | InvocationTargetException e) { END log.errorFormat("LdapBrokerCommandBase: Failed to get type information using reflection for Action: {0}", action); return null; } } Why not simply catch Exception, since you don't do special handling for each exception class?

Target:
private BrokerCommandBase CreateCommand(AdActionType action, LdapBrokerBaseParameters parameters) { try { Class type = Class.forName(GetCommandTypeName(action)); Constructor info = ReflectionUtils.findConstructor(type, parameters.getClass()); Object tempVar = info.newInstance(parameters); return (BrokerCommandBase) ((tempVar instanceof BrokerCommandBase) ? tempVar : null); } catch (Exception e) { log.errorFormat("LdapBrokerCommandBase: Failed to get type information using reflection for Action: {0}", action); return null; } }
Source:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { START runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null, null); END } you can call runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false);

Target:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false); }
Source:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { START runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null); END } I agree, however the question is, how will this change (aggregate error messages by default) affect existing code using this method.

Target:
public void runMultipleActions(final List<VdcActionType> actionTypes, final List<VdcActionParametersBase> parameters, final List<IFrontendActionAsyncCallback> callbacks, final IFrontendActionAsyncCallback failureCallback, final Object state) { runMultipleActions(actionTypes, parameters, callbacks, failureCallback, state, false, null, null); }
Source:
protected void executeQueryCommand() { START Integer numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); END getQueryReturnValue().setReturnValue(numOfVms); } why integer and not int? i dont think this can return null

Target:
protected void executeQueryCommand() { int numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); getQueryReturnValue().setReturnValue(numOfVms); }
Source:
protected LockProperties getLockingPropertiesSettings() { START return new LockProperties().setObtainLock(false); END } I expect this should be false by default... return new LockProperties(); And if you want to lock you: return new LockProperties.setObtainLock(true);

Target:
protected LockProperties getLockingPropertiesSettings() { return new LockProperties(); }
Source:
protected boolean verifySnapshotsStatus(List<Snapshot> snapshots) { for (Snapshot snapshot : snapshots) { START if (snapshot.getStatus() != SnapshotStatus.OK && snapshot.getStatus() != SnapshotStatus.BROKEN) { END return false; } } return true; } not sure why broken is considered valid - btu, note the broken status might be removed

Target:
protected boolean verifySnapshotsStatus(List<Snapshot> snapshots) { for (Snapshot snapshot : snapshots) { if (snapshot.getStatus() != SnapshotStatus.OK) { return false; } } return true; }
Source:
protected void updateOriginalTemplate(VmStatic vmStatic) { vmStatic.setOriginalTemplateGuid(getParameters().getVmStaticData().getOriginalTemplateGuid()); START vmStatic.setOriginalTemplateName(getParameters().getVmStaticData().getOriginalTemplateName()); END } it looks a bit weird to get getParameters().getVmStaticData() again since it is the same as the method argument vmStatic.. in other places, not in ovirt-engine, I would suggest to use the argument instead, but in order to comply with the standards in our commands infrastructure I would suggest to remove the argument (and change AddVmCommand accordingly). anyway, those two solution will be fine by me

Target:
protected void updateOriginalTemplate(VmStatic vmStatic) { // do not update it - it is already correctly configured from the snapshot }
Source:
public static VdcActionParametersBase getParameters(CommandEntity commandEntity) { return commandEntity.getData() != null ? (VdcActionParametersBase) commandEntity.getData().get(PARAMETERS_KEY) : null; START } END how about initialize CommandEntity#data to empty map in CommandEntity instead of all those null checks?

Target:
public static VdcActionParametersBase getParameters(CommandEntity commandEntity) { return (VdcActionParametersBase) commandEntity.getData().get(PARAMETERS_KEY); }
Source:
private static void AddEventNotificationEntry(EventNotificationEntity entity, AuditLogType auditLogType) { HashSet<AuditLogType> entry; if (!_eventNotificationTypeMap.containsKey(entity)) { _eventNotificationTypeMap.put(entity, new HashSet<AuditLogType>()); } entry = _eventNotificationTypeMap.get(entity); START entry.add(auditLogType); END } In order not to use contains and get methods, I would prefer following code: HashSet<AuditLogType> entry = _eventNotificationTypeMap.get(entity); if (entry == null) { entry = new HashSet<AuditLogType>(); _eventNotificationTypeMap.put(entity, entry); } entry.add(auditLogType);

Target:
private static void AddEventNotificationEntry(EventNotificationEntity entity, AuditLogType auditLogType) { HashSet<AuditLogType> entry = _eventNotificationTypeMap.get(entity); if (entry == null) { entry = new HashSet<AuditLogType>(); _eventNotificationTypeMap.put(entity, entry); } entry.add(auditLogType); }
Source:
public void testGetWithEntityId() { START dao = dbFacade.getUnregisteredOVFDataDao(); END OvfEntityData ovfEntityData = dao.getByEntityIdAndStorageDomain(FixturesTool.VM_RHEL5_POOL_50, FixturesTool.STORAGE_DOAMIN_NFS2_1); assertNotNull("VM should exists in the UnregisteredOVFData", ovfEntityData); } Should be done in the setup. Note this re-occurs in all your test methods

Target:
public void testGetWithEntityId() { OvfEntityData ovfEntityData = dao.getByEntityIdAndStorageDomain(FixturesTool.VM_RHEL5_POOL_50, FixturesTool.STORAGE_DOAMIN_NFS2_1); assertNotNull("VM should exists in the UnregisteredOVFData", ovfEntityData); }
Source:
public boolean testConnection() { try { getClient().execute(new OpenStackRequest<>(getClient(), HttpMethod.GET, "", null, null)); START return true; END } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e); } } why do you need it as a boolean? I don't mind, but not sure it is needed.

Target:
public void testConnection() { try { getClient().execute(new OpenStackRequest<>(getClient(), HttpMethod.GET, "", null, null)); } catch (RuntimeException e) { throw new VdcBLLException(VdcBllErrors.PROVIDER_FAILURE, e); } }
Source:
START static private List<DiskImage> generateDisksList(int size) { END List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < size; ++i) { DiskImage diskImage = new DiskImage(); diskImage.setImageId(Guid.newGuid()); disksList.add(diskImage); } return disksList; } private static

Target:
private static List<DiskImage> generateDisksList(int size) { List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < size; ++i) { DiskImage diskImage = new DiskImage(); diskImage.setImageId(Guid.newGuid()); disksList.add(diskImage); } return disksList; }
Source:
START protected void mockGetAllSnapshots(AddVmFromTemplateCommand<AddVmFromTemplateParameters> command) { END doAnswer(new Answer<List<DiskImage>>() { @Override public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); DiskImage arg = (DiskImage) args[0]; List<DiskImage> list = createDiskSnapshot(arg.getId(), 3); return list; } }).when(command).getAllImageSnapshots(any(DiskImage.class)); } should be private

Target:
private void mockGetAllSnapshots(AddVmFromTemplateCommand<AddVmFromTemplateParameters> command) { doAnswer(new Answer<List<DiskImage>>() { @Override public List<DiskImage> answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); DiskImage arg = (DiskImage) args[0]; List<DiskImage> list = createDiskSnapshot(arg.getId(), 3); return list; } }).when(command).getAllImageSnapshots(any(DiskImage.class)); }
Source:
public void testInitCanBeCalledTwice() throws Exception { MacPoolPerDc pool = new MacPoolPerDc(); pool.initialize(); Mockito.verify(dbFacadeMock).getMacPoolDao(); Mockito.verify(macPoolDaoMock).getAll(); START Mockito.verifyNoMoreInteractions(storagePoolDaoMock, vmNicDaoMock, macPoolDaoMock, dbFacadeMock); END pool.initialize(); //should not fail. } I believe that this should come after the second call, not before.. Or even better, both here and there..

Target:
public void testInitCanBeCalledTwice() throws Exception { MacPoolPerDc pool = new MacPoolPerDc(); pool.initialize(); Mockito.verify(dbFacadeMock).getMacPoolDao(); Mockito.verify(macPoolDaoMock).getAll(); pool.initialize(); Mockito.verifyNoMoreInteractions(storagePoolDaoMock, vmNicDaoMock, macPoolDaoMock, dbFacadeMock); }
Source:
protected void fillMacAddressIfMissing(VmNic iface) { START final MacPoolManagerStrategy pool = getMacPool(); END if (StringUtils.isEmpty(iface.getMacAddress()) && (pool.getAvailableMacsCount() >= 1)) { iface.setMacAddress(pool.allocateNewMac()); } } No need to extract to variable

Target:
protected void fillMacAddressIfMissing(VmNic iface) { if (StringUtils.isEmpty(iface.getMacAddress()) && (getMacPool().getAvailableMacsCount() >= 1)) { iface.setMacAddress(getMacPool().allocateNewMac()); } }
Source:
protected boolean canRunActionOnNonManagedVm() { START ValidationResult nonManagedVmValidationResult = VmHandler.canRunActionOnNonManagedVm(getVm(), getActionType()); END if (!nonManagedVmValidationResult.isValid()) { return failCanDoAction(nonManagedVmValidationResult.getMessage()); } return true; } Although a nice change, it's unrelated to this patch and should go in a separate one.

Target:
protected boolean canRunActionOnNonManagedVm() { ValidationResult nonManagedVmValidationResult = VmHandler.canRunActionOnNonManagedVm(getVm(), this.getActionType()); if (!nonManagedVmValidationResult.isValid()) { return failCanDoAction(nonManagedVmValidationResult.getMessage()); } return true; }
Source:
public void removeAll(Guid vmId) { List<VmNic> interfaces = getVmNicDao().getAllForVm(vmId); if (interfaces != null) { removeFromExternalNetworks(interfaces); START final MacPoolManagerStrategy macPool = getMacPoolManager(vmId); END for (VmNic iface : interfaces) { macPool.freeMac(iface.getMacAddress()); getVmNicDao().remove(iface.getId()); getVmNetworkStatisticsDao().remove(iface.getId()); } } } No need to extract to variable.

Target:
public void removeAll(Guid vmId) { List<VmNic> interfaces = getVmNicDao().getAllForVm(vmId); if (interfaces != null) { removeFromExternalNetworks(interfaces); for (VmNic iface : interfaces) { macPool.freeMac(iface.getMacAddress()); getVmNicDao().remove(iface.getId()); getVmNetworkStatisticsDao().remove(iface.getId()); } } }
Source:
public Guid getVmtGuid() { START return vmtGuid; END } Although a nice change, it's unrelated to this patch and should go in a separate one.

Target:
public Guid getVmtGuid() { return this.vmtGuid; }
Source:
START public void setVmtGuid(Guid value) { END vmtGuid = value; } Although a nice change, it's unrelated to this patch and should go in a separate one.

Target:
public void setVmtGuid(Guid value) { this.vmtGuid = value; }
Source:
public Object getData(String key, boolean refresh) { return getData(ThreadLocalParamsContainer.getHttpSessionId(), key, refresh); START } END put all getData() at same place?

Target:
public final Object getData(String key, boolean refresh) { return getData(ThreadLocalParamsContainer.getHttpSessionId(), key, refresh); }
Source:
private void refresh(SessionInfo sessionInfo) { Date now = new Date(); Date softLimit = (Date) sessionInfo.contentOfSession.get(SOFT_LIMIT_PARAMETER_NAME); if (softLimit == null) { softLimit = now; START } END int softLimitValue = Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval); if (softLimitValue > 0) { sessionInfo.contentOfSession.put(SOFT_LIMIT_PARAMETER_NAME, DateUtils.addMinutes(now, softLimitValue)); } } on the 10th time... why do you need to get the soft limit at refresh?!?!?

Target:
private void refresh(SessionInfo sessionInfo) { Date now = new Date(); int softLimitValue = Config.<Integer> getValue(ConfigValues.UserSessionTimeOutInterval); if (softLimitValue > 0) { sessionInfo.contentOfSession.put(SOFT_LIMIT_PARAMETER_NAME, DateUtils.addMinutes(now, softLimitValue)); } }
Source:
private SessionInfo getSessionInfo(String sessionId) { SessionInfo sessionInfo = null; for (SessionInfo currentSessionInfo : sessionInfoMap.values()) { if (currentSessionInfo.sessionId.equals(sessionId)) { sessionInfo = currentSessionInfo; break; } } START return sessionInfo; END } why the key cannot be session id?

Target:
private SessionInfo getSessionInfo(String sessionId) { return sessionInfoMap.get(sessionId); }
Source:
public final void removeSession(String sessionId) { Iterator<Entry<String, SessionInfo>> iterator = sessionInfoMap.entrySet().iterator(); while (iterator.hasNext()) { if (iterator.next().getKey().equals(sessionId)) { iterator.remove(); break; START } END } } I still don't understand why the key cannot be the session id

Target:
public final void removeSession(String sessionId) { sessionInfoMap.remove(sessionId); }
Source:
protected void addCanDoActionMessageVariable(String varName, Object varValue) { START String message = String.format("$%s %s", varName, varValue); END getReturnValue().getCanDoActionMessages().add(message); } feel free to inline this. No need for String message temp variable.

Target:
protected void addCanDoActionMessageVariable(String varName, Object varValue) { getReturnValue().getCanDoActionMessages().add(String.format("$%s %s", varName, varValue)); }
Source:
private boolean verifyDisksIfNeeded() { boolean verified = true; if (!getParameters().isImportAsNewEntity() && !isImagesAlreadyOnTarget()) { verified = checkIfDisksExist(imageList); } START return verified; END } ok, so if we keep this method, can you please remove the 'verified' variable? it is not really needed, and then people will add more logic into this method and we'll end-up with complicated methods like the old canDoAction methods..

Target:
private boolean verifyDisksIfNeeded() { if (!getParameters().isImportAsNewEntity() && !isImagesAlreadyOnTarget()) { return checkIfDisksExist(imageList); } return true; }
Source:
public LoggerHandler() { update(null, null); START ExtensionsManager.getInstance().addObserver(this); END } switch order to avoid race?

Target:
public LoggerHandler() { ExtensionsManager.getInstance().addObserver(this); update(null, null); }
Source:
public void publish(LogRecord record) { initRefreshThread(); ExtMap publishInputMap = new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH); ExtMap publishOutputMap = new ExtMap(); for (ExtensionProxy extension : getExtensions()) { try { extension.invoke( START publishInputMap.mput(Logger.InvokeKeys.LOG_RECORD, record), END publishOutputMap); } catch(Exception ex) } } please put record above as well.

Target:
public void publish(LogRecord record) { initRefreshThread(); ExtMap publishInputMap = new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH) .mput(Logger.InvokeKeys.LOG_RECORD, record); ExtMap publishOutputMap = new ExtMap(); for (ExtensionProxy extension : getExtensions()) { try { extension.invoke( publishInputMap, publishOutputMap); } catch(Exception ex) } }
Source:
START public ValidationResult isReadOnlyPropertyCompatibleWithLunInterface() { END if (Boolean.TRUE.equals(disk.getReadOnly()) && disk.getDiskInterface() == DiskInterface.VirtIO_SCSI && disk.getDiskStorageType() == DiskStorageType.LUN) { return new ValidationResult( VdcBllMessages.ACTION_TYPE_FAILED_VIRT_IO_SCSI_INTERFACE_FOR_LUN_DISKS_DOES_NOT_SUPPORT_READ_ONLY_ATTR); } return ValidationResult.VALID; } any reason not to combine this method with isReadOnlyPropertyCompatibleWithInterface ?

Target:
public ValidationResult isReadOnlyPropertyCompatibleWithLunInterface() { if (Boolean.TRUE.equals(disk.getReadOnly()) && disk.getDiskInterface() == DiskInterface.VirtIO_SCSI) { return new ValidationResult( VdcBllMessages.ACTION_TYPE_FAILED_VIRT_IO_SCSI_INTERFACE_FOR_LUN_DISKS_DOES_NOT_SUPPORT_READ_ONLY_ATTR); } return ValidationResult.VALID; }
Source:
public GlusterVolumeProfileParameters(Guid clusterId, Guid volumeId) { START super(clusterId, volumeId); END this.nfs = false; } should be : this( clusterId, volumenId, false);

Target:
public GlusterVolumeProfileParameters(Guid clusterId, Guid volumeId) { this(clusterId, volumeId, false); }
Source:
public void testConvertSecondsToMinutes() { long seconds = 1800L; Pair<Long, TimeUnit> expectedResults = TimeConverter.autoConvert(seconds, TimeUnit.SECONDS); assertEquals(expectedResults.getFirst().longValue() , 30L); START assertEquals(expectedResults.getSecond(), TimeUnit.MINUTES); END } Reorder expected and actual as per this patch - http://gerrit.ovirt.org/#/c/27775/

Target:
public void testConvertSecondsToMinutes() { long seconds = 1800L; Pair<Long, TimeUnit> expectedResults = TimeConverter.autoConvert(seconds, TimeUnit.SECONDS); assertEquals(30L, expectedResults.getFirst().longValue()); assertEquals(TimeUnit.MINUTES, expectedResults.getSecond()); }
Source:
public void showNfsProfileStats(GlusterVolumeProfileInfo entity) { List<GlusterVolumeProfileStats> nfsProfileDetails = entity.getNfsProfileDetails(); getNfsServers().setItems(nfsProfileDetails); START getNfsServers().setSelectedItem(nfsProfileDetails.get(0)); END } you may want to check the size of the list

Target:
public void showNfsProfileStats(GlusterVolumeProfileInfo entity) { if(entity != null) { List<GlusterVolumeProfileStats> nfsProfileDetails = entity.getNfsProfileDetails(); getNfsServers().setItems(nfsProfileDetails); if(nfsProfileDetails.size() > 0) { getNfsServers().setSelectedItem(nfsProfileDetails.get(0)); } } }
Source:
public Guid getVmTemplateId() { if (isImagesAlreadyOnTarget()) { return getParameters().getContainerId(); START } else { END return super.getVmTemplateId(); } } can remove the 'else' clause...

Target:
public Guid getVmTemplateId() { if (isImagesAlreadyOnTarget()) { return getParameters().getContainerId(); } return super.getVmTemplateId(); }
Source:
private List<ExternalDiscoveredHost> runDiscoveredHostListMethod(HttpMethod httpMethod) { try{ runHttpMethod(httpClient, httpMethod); ForemanDiscoveredHostWrapper fdw = objectMapper.readValue(httpMethod.getResponseBody(), ForemanDiscoveredHostWrapper.class); return mapDiscoveredHosts(Arrays.asList(fdw.getResults())); START } catch (JsonParseException e) { END handleException(e); } catch (JsonMappingException e) { handleException(e); } catch (IOException e) { handleException(e); } return null; } I think here it is the same as doing only catch (IOException e) { handleException(e); } because the other two are IOExceptions two and you handle all the same. please apply to other blocks as well

Target:
private List<ExternalDiscoveredHost> runDiscoveredHostListMethod(HttpMethod httpMethod) { try{ runHttpMethod(httpClient, httpMethod); ForemanDiscoveredHostWrapper fdw = objectMapper.readValue(httpMethod.getResponseBody(), ForemanDiscoveredHostWrapper.class); return mapDiscoveredHosts(Arrays.asList(fdw.getResults())); } catch (IOException e) { handleException(e); } return null; }
Source:
private void addSELinuxModes(VersionCaps version, SELinuxMode[] values) { if (VersionUtils.greaterOrEqual(version, VERSION_3_5)) { version.setSelinuxModes(new SELinuxModes()); for (SELinuxMode mode: values) { START version.getSelinuxModes().getSELinuxModes().add(mode.toString().toLowerCase()); END } } } This should be as it used to be, no need to convert to lower case as that should already be part of the "value()" implementation of SELinuxMode.

Target:
private void addSELinuxModes(VersionCaps version, SELinuxMode[] values) { if (VersionUtils.greaterOrEqual(version, VERSION_3_5)) { version.setSelinuxModes(new SELinuxModes()); for (SELinuxMode mode: values) { version.getSelinuxModes().getSELinuxModes().add(mode.value()); } } }
Source:
private void copyDiskDevicesFromTemplate() { START List<VmDevice> disks = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(getVmTemplateId(), VmDeviceGeneralType.DISK); END VmDeviceUtils.copyVmDevices( vmDisksSource.getId(), getVmId(), getVm(), getVm().getStaticData(), true, disks, getSrcDeviceIdToTargetDeviceIdMapping(), false, false, false, false, false ); } please use vmDisksSource here as well

Target:
private void copyDiskDevicesFromTemplate() { List<VmDevice> disks = DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(vmDisksSource.getId(), VmDeviceGeneralType.DISK); VmDeviceUtils.copyVmDevices( vmDisksSource.getId(), getVmId(), getVm(), getVm().getStaticData(), true, disks, getSrcDeviceIdToTargetDeviceIdMapping(), false, false, false, false, false ); }
Source:
private void updatePosixProperties(IStorageModel storageModel) { PosixStorageModel posixModel = (PosixStorageModel) storageModel; connection.setVfsType(posixModel.getVfsType().getEntity().toString()); if (posixModel.getMountOptions().getEntity() != null) { START connection.setMountOptions(posixModel.getMountOptions().getEntity()); END } } This change, while it may be true, is unrealted to NFS Mount Options. Please publish it in a separate fix.

Target:
private void updatePosixProperties(IStorageModel storageModel) { PosixStorageModel posixModel = (PosixStorageModel) storageModel; connection.setVfsType(posixModel.getVfsType().getEntity().toString()); if (posixModel.getMountOptions().getEntity() != null) { connection.setMountOptions(posixModel.getMountOptions().getEntity().toString()); } }
Source:
public void testKDCLocator() { KDCLocator locator = new KDCLocator(); String[] recordsList = { "0 100 88 example.com.", "0 100 88 comp1.example.com", "1 100 88 comp1.example.com." }; DnsSRVResult result = locator.getKdc(recordsList, "example.com"); int numOfEntries = result.getNumOfValidAddresses(); START Assert.assertEquals(3, numOfEntries); END } omit Assert class notation ?

Target:
public void testKDCLocator() { KDCLocator locator = new KDCLocator(); String[] recordsList = { "0 100 88 example.com.", "0 100 88 comp1.example.com", "1 100 88 comp1.example.com." }; DnsSRVResult result = locator.getKdc(recordsList, "example.com"); int numOfEntries = result.getNumOfValidAddresses(); assertEquals(3, numOfEntries); }
Source:
public void useDefaultMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(0)); START Assert.assertEquals(0, validate.size()); END } following the change above, i'd expect this one to look as: assertTrue(validate.isEmpty())

Target:
public void useDefaultMTU() { Set<ConstraintViolation<MtuContainer>> validate = validate(new MtuContainer(0)); assertTrue(validate.isEmpty()); }
Source:
public void testCompareTo() { Guid guid1 = new Guid("5b411bc1-c220-4421-9abd-cfa484aecb6e"); Guid guid2 = new Guid("5b411bc1-c220-4421-9abd-cfa484aecb6f"); assertTrue(guid1.compareTo(guid2) < 0); START Assert.assertEquals(0, guid1.compareTo(guid1)); END assertTrue(guid2.compareTo(guid1) > 0); } please omit class notation.

Target:
public void testCompareTo() { Guid guid1 = new Guid("5b411bc1-c220-4421-9abd-cfa484aecb6e"); Guid guid2 = new Guid("5b411bc1-c220-4421-9abd-cfa484aecb6f"); assertTrue(guid1.compareTo(guid2) < 0); assertEquals(0, guid1.compareTo(guid1)); assertTrue(guid2.compareTo(guid1) > 0); }
Source:
public synchronized String load(Properties configuration) { START return loadImpl(configuration, null); END } won't it better to sync the loadImpl?

Target:
public String load(Properties configuration) { return loadImpl(configuration, null); }
Source:
public void setMainTabSelectedItem(VDS selectedItem) { // TODO(vszocs) possible performance optimization: don't create HostInterfaceForm upon each selection hostInterfaceForm = new HostInterfaceForm(getDetailModel()); contentPanel.remove(contentPanel.getWidgetCount() - 1); contentPanel.add(hostInterfaceForm); START contentPanel.getParent().getElement().getStyle().setOverflowX(Overflow.AUTO); END } This should work if you put it in the constructor after initWidget(), shouldn't it? It shouldn't be invoked upon selection of a main tab item.

Target:
public void setMainTabSelectedItem(VDS selectedItem) { // TODO(vszocs) possible performance optimization: don't create HostInterfaceForm upon each selection hostInterfaceForm = new HostInterfaceForm(getDetailModel()); contentPanel.remove(contentPanel.getWidgetCount() - 1); contentPanel.add(hostInterfaceForm); if (contentPanel.getParent() != null) { contentPanel.getParent().getElement().getStyle().setOverflowX(Overflow.AUTO); } }
Source:
protected void executeCommand() { // add user session setActionReturnValue(getCurrentUser()); getReturnValue().setLoginResult(LoginResult.Autheticated); getReturnValue().setSessionId(engineSessionId); // Permissions for this user might been changed since last login so // update his isAdmin flag accordingly updateUserData(); ApplicationMode appMode = ApplicationMode.from(Config.<Integer> getValue(ConfigValues.ApplicationMode)); START SessionDataContainer.getInstance().setData("app_mode", appMode); END setSucceeded(true); } What is the point of putting the application mode in the session? Anywhere we would read that information can't we simply read the configuration?

Target:
protected void executeCommand() { setActionReturnValue(getCurrentUser()); getReturnValue().setLoginResult(LoginResult.Autheticated); getReturnValue().setSessionId(engineSessionId); // Permissions for this user might been changed since last login so // update his isAdmin flag accordingly updateUserData(); setSucceeded(true); }
Source:
public VdcActionParametersBase(String engineSessionId) { shouldbelogged = true; transctionOption = TransactionScopeOption.Required; setTaskGroupSuccess(true); setParentCommand(VdcActionType.Unknown); executionReason = CommandExecutionReason.REGULAR_FLOW; compensationEnabled = false; parentCommand = VdcActionType.Unknown; commandType = VdcActionType.Unknown; imagesParameters = new ArrayList<VdcActionParametersBase>(); START sessionid = engineSessionId; END } Why not simply make the constructor like this: public VdcActionParametersBase(String engineSessionId) { this(); sessionId = engineSessionId; } No code duplication and much shorter.

Target:
public VdcActionParametersBase(String engineSessionId) { this(); sessionid = engineSessionId; }
Source:
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { // If there are no authentication profiles supporting negotiation then we don't do anything, as there is no // authentication to perform: findNegotiatingProfiles(req); if (!profiles.isEmpty()) { // Perform the authentication: doAuth((HttpServletRequest) req, (HttpServletResponse) rsp, chain); } START chain.doFilter(req, rsp); END } else is missing here... every time you perform doAuth you also process the request into the webapp, this should not happen as long as you are nego. just add else here.

Target:
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException { // If there are no authentication profiles supporting negotiation then we don't do anything, as there is no // authentication to perform: findNegotiatingProfiles(req); if (!profiles.isEmpty()) { // Perform the authentication: doAuth((HttpServletRequest) req, (HttpServletResponse) rsp, chain); } else { chain.doFilter(req, rsp); } }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; START HttpSession session = req.getSession(false); END if ((req.getHeader("Authorization") != null)) { // No need to pass credentials again - if passed, login should be called if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); } why do you get the session here? move into condition where you actually use them.

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if ((req.getHeader("Authorization") != null)) { // No need to pass credentials again - if passed, login should be called HttpSession session = req.getSession(false); if (session != null) { session.invalidate(); session = null; } } chain.doFilter(request, response); }
Source:
START public BalanceResource getSubResource(String id) { END return inject(new BackendBalanceResource(id, getPolicyUnit(id))); } getSubResource --> getBalanceSubResource, for consistency

Target:
public BalanceResource getSubResource(String id) { return inject(new BackendBalanceResource(id)); }
Source:
protected boolean isCustomMtu() { START return MtuSelector.customMtu.equals(getMtuSelector().getSelectedItem()); END } Note that enums can be used with ==, but as you prefer.

Target:
protected boolean isCustomMtu() { return MtuSelector.customMtu == getMtuSelector().getSelectedItem(); }
Source:
protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); result = getBroker().glusterVolumeRebalanceStop(volumeName); GlusterVolumeTaskStatusEntity entity = result.getStatusDetails(); entity.setStatusTime(new Date()); entity.setStopTime(new Date()); START proceedProxyReturnValue(); END setReturnValue(entity); } why did you move this line? basically proceedProxyReturnValue should be called before using the result, because in case of error it might be null or not as expected, and NPE will hide the real error message from vdsm

Target:
protected void executeVdsBrokerCommand() { String volumeName = getParameters().getVolumeName(); result = getBroker().glusterVolumeRebalanceStop(volumeName); proceedProxyReturnValue(); GlusterVolumeTaskStatusEntity entity = result.getStatusDetails(); entity.setStatusTime(new Date()); entity.setStopTime(new Date()); setReturnValue(entity); }
Source:
public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); START int sizeAfterSave = dao.getAll().size(); END dao.saveOrUpdate(existingUser); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); } Shouldn't this be executed after dao.saveOrUpdate()?

Target:
public void testSaveOrUpdateExisting() { int sizeBeforeSave = dao.getAll().size(); existingUser.setFirstName("changedname"); existingUser.setLastName("changedsurname"); dao.saveOrUpdate(existingUser); int sizeAfterSave = dao.getAll().size(); DbUser result = dao.get(existingUser.getId()); assertEquals(existingUser, result); assertEquals(0, sizeAfterSave - sizeBeforeSave); }
Source:
public boolean equals(Object obj) { if (obj == null) { return false; } START super.equals(obj); END BrickProfileDetails brickDetails = (BrickProfileDetails) obj; if (brickDetails.getBrickId() == null) { return false; } if (!(ObjectUtils.objectsEqual(getBrickId(), brickDetails.getBrickId()))) { return false; } return true; } you're not using the return value shouldn't it be... if (!super.equals(obj)) { return false }

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if(!super.equals(obj)) { return false; } BrickProfileDetails brickDetails = (BrickProfileDetails) obj; if (brickDetails.getBrickId() == null) { return false; } if (!(ObjectUtils.objectsEqual(getBrickId(), brickDetails.getBrickId()))) { return false; } return true; }
Source:
public ValidationResult isInProcess() { StoragePoolIsoMap domainIsoMap = storageDomain.getStoragePoolIsoMapData(); if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, START String.format("$status %1$s", StorageDomainStatus.Locked)); END } return ValidationResult.VALID; } the status in the message is now wrong (as you check more statuses), let's put the domain status.

Target:
public ValidationResult isInProcess() { StoragePoolIsoMap domainIsoMap = storageDomain.getStoragePoolIsoMapData(); if (domainIsoMap.getStatus() != null && domainIsoMap.getStatus().isStorageDomainInProcess()) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$status %1$s", domainIsoMap.getStatus())); } return ValidationResult.VALID; }
Source:
protected void addStoragePoolToDb() { START final StoragePool storagePool = getStoragePool(); END storagePool.setId(Guid.newGuid()); storagePool.setStatus(StoragePoolStatus.Uninitialized); Guid requestedMacPoolId = storagePool.getMacPoolId(); Guid macPoolIdToUse = requestedMacPoolId == null ? getMacPoolDao().getDefaultPool().getId() : requestedMacPoolId; storagePool.setMacPoolId(macPoolIdToUse); getStoragePoolDAO().save(storagePool); } No need to extract to variable

Target:
protected void addStoragePoolToDb() { getStoragePool().setId(Guid.newGuid()); getStoragePool().setStatus(StoragePoolStatus.Uninitialized); Guid requestedMacPoolId = getStoragePool().getMacPoolId(); Guid macPoolIdToUse = requestedMacPoolId == null ? getMacPoolDao().getDefaultPool().getId() : requestedMacPoolId; getStoragePool().setMacPoolId(macPoolIdToUse); getStoragePoolDAO().save(getStoragePool()); }
Source:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : source != null ? (Collection<ProfileEntry>) source : new START ArrayList<ProfileEntry>()) END { results.add(profileEntry.getProfile()); } return results; } }; } Backend does not return null, why do we need a null check here for source?

Target:
private static void convertAAAProfilesResult(AsyncQuery aQuery) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery _asyncQuery) { List<String> results = new ArrayList<String>(); for (ProfileEntry profileEntry : (Collection<ProfileEntry>) source) { results.add(profileEntry.getProfile()); } return results; } }; }
Source:
private String extractAuthorizationProvider(ProfileEntry profileEntry) { START return profileEntry == null ? "" : profileEntry.getAuthz(); END } if it is null how come we search or even return ""?

Target:
private String extractAuthorizationProvider(ProfileEntry profileEntry) { return profileEntry.getAuthz(); }
Source:
public DiskProfile getProfile() { if (profile == null) { if (getParameters().getProfile() != null) { profile = getParameters().getProfile(); } START else if (getParameters().getProfileId() != null) { END profile = getProfileDao().get(getParameters().getProfileId()); } else { log.error("couldn't find disk profile"); } } return profile; } please move the else a line up

Target:
public DiskProfile getProfile() { if (profile == null) { if (getParameters().getProfile() != null) { profile = getParameters().getProfile(); } else if (getParameters().getProfileId() != null) { profile = getProfileDao().get(getParameters().getProfileId()); } } return profile; }
Source:
public boolean equalValues(QosBase other) { // no extra values START return true; END } true for every other QOS, even if they are not from the same type?

Target:
public boolean equalValues(QosBase other) { // no extra values, should be called for the derivative classes. return false; }
Source:
public static String getUniqueHostName(VDS host) { START return host.getHostName() + "-" + new String(DigestUtils.md5Hex(host.getId().toByteArray())).substring(0, 6); END } if md5Hex returns string, why do you need new String? but if you use new String on byte array... you should use explicit encoding.

Target:
public static String getUniqueHostName(VDS host) { return host.getHostName() + "-" + DigestUtils.md5Hex(host.getId().toByteArray()).substring(0, 6); }