auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void onUpdateMsg(final AvroElasticMemoryMessage msg) { try (final TraceScope onUpdateMsgScope = Trace.startSpan(ON_UPDATE_MSG, HTraceUtils.fromAvro(msg.getTraceInfo()))) { final String operationId = msg.getOperationId().toString(); final UpdateResult updateResult; final Update update = pendingUpdates.remove(operationId); if (update == null) { LOG.log(Level.WARNING, "The update with id {0} seems already handled.", operationId); return; } switch (update.getType()) { case ADD: final Add add = (Add) update; add.apply(memoryStore); updateResult = UpdateResult.RECEIVER_UPDATED; break; case REMOVE: final Remove remove = (Remove) update; remove.apply(memoryStore); updateResult = UpdateResult.SUCCESS; break; default: throw new RuntimeException("Undefined Message type of Update: " + update); } sender.get().sendUpdateAckMsg(operationId, updateResult, TraceInfo.fromSpan(onUpdateMsgScope.getSpan())); } }

Target:
private void onUpdateMsg(final AvroElasticMemoryMessage msg) { try (final TraceScope onUpdateMsgScope = Trace.startSpan(ON_UPDATE_MSG, HTraceUtils.fromAvro(msg.getTraceInfo()))) { final String operationId = msg.getOperationId().toString(); final UpdateResult updateResult; final Update update = pendingUpdates.remove(operationId); if (update == null) { LOG.log(Level.WARNING, "The update with id {0} seems already handled.", operationId); return; } switch (update.getType()) { case ADD: update.apply(memoryStore); updateResult = UpdateResult.RECEIVER_UPDATED; break; case REMOVE: update.apply(memoryStore); movingRanges.removeAll(update.getRanges()); updateResult = UpdateResult.SENDER_UPDATED; break; default: throw new RuntimeException("Undefined Message type of Update: " + update); } sender.get().sendUpdateAckMsg(operationId, updateResult, TraceInfo.fromSpan(onUpdateMsgScope.getSpan())); } }
Source:
public boolean hasNext() { init(); if (jp.isClosed()) { return false; } if (jp.getCurrentToken() == JsonToken.END_ARRAY) { CloseQuietly.close(jp); return false; } return true; }

Target:
public boolean hasNext() { if (jp.isClosed()) { return false; } if (jp.getCurrentToken() == JsonToken.END_ARRAY) { CloseQuietly.close(jp); return false; } return true; }
Source:
public Response toResponse(ServiceException exception) { log.info("Error handling request {}", exception.getErrorId(), exception); int status = exception.getStatus(); Response.ResponseBuilder builder = Response.status(status); try { SerializableError error = exception.getError(); builder.type(MediaType.APPLICATION_JSON); String json = MAPPER.writeValueAsString(error); builder.entity(json); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", exception.getErrorId(), e); builder = Response.status(status); builder.type(MediaType.TEXT_PLAIN); builder.entity("Refer to the server logs with this errorId: " + exception.getErrorId()); } return builder.build(); }

Target:
public Response toResponse(ServiceException exception) { log.error("Error handling request {}", exception.getErrorId(), exception); try { SerializableError error = exception.getError(); String json = MAPPER.writeValueAsString(error); return Response.status(exception.getStatus()) .type(MediaType.APPLICATION_JSON) .entity(json) .build(); } catch (RuntimeException | JsonProcessingException e) { log.warn("Unable to translate exception to json for request {}", exception.getErrorId(), e); return Response.status(exception.getStatus()) .type(MediaType.TEXT_PLAIN) .entity("Refer to the server logs with this errorId: " + exception.getErrorId()) .build(); } }
Source:
public void setPodTemplateName(String podTemplateName) { this.podTemplateName = podTemplateName; if (!StringUtils.isEmpty(podTemplateName)) { String cloudName = getCloud(); if (StringUtils.isEmpty(cloudName)) { cloudName = "kubernetes"; } Cloud cloud = Jenkins.getInstance().getCloud(cloudName); if (cloud instanceof KubernetesCloud) { KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; List<PodTemplate> templates = kubernetesCloud.getTemplates(); PodTemplate template = null; for (PodTemplate t : templates) { String name = t.getName(); if (podTemplateName.equals(name)) { template = t; break; } } if (template != null) { setPodTemplate(template); } } } }

Target:
public void setPodTemplateName(String podTemplateName) { this.podTemplateName = Util.fixEmpty(podTemplateName); if (podTemplateName != null) { String cloudName = getCloud(); if (StringUtils.isEmpty(cloudName)) { cloudName = KubernetesCloud.DEFAULT_CLOUD_NAME; } Cloud cloud = Jenkins.getInstance().getCloud(cloudName); if (cloud instanceof KubernetesCloud) { KubernetesCloud kubernetesCloud = (KubernetesCloud) cloud; List<PodTemplate> templates = kubernetesCloud.getTemplates(); PodTemplate template = null; for (PodTemplate t : templates) { String name = t.getName(); if (podTemplateName.equals(name)) { template = t; break; } } if (template != null) { setPodTemplate(template); } else { LOGGER.warning("Could not find a PodTemplate called " + podTemplateName + " in the cloud " + cloudName + " so cannot default the PodTemplate"); } } } }
Source:
protected Object[] queryIndividualResourcesToExport(IAdaptable rootResource) { ResourceSelectionDialog dialog = new ResourceSelectionDialog( getContainer().getShell(), rootResource, IDEWorkbenchMessages.WizardExportPage_selectResourcesTitle); dialog.setInitialSelections(selectedResources); dialog.open(); return dialog.getResult(); }

Target:
protected Object[] queryIndividualResourcesToExport(IAdaptable rootResource) { ResourceSelectionDialog dialog = new ResourceSelectionDialog( getContainer().getShell(), rootResource, IDEWorkbenchMessages.WizardExportPage_selectResourcesTitle); dialog.setInitialElementSelections(selectedResources); dialog.open(); return dialog.getResult(); }
Source:
public DeleteRepresentationAction(Collection<DRepresentation> representations) { super("Delete", AbstractUIPlugin.imageDescriptorFromPlugin(SiriusEditPlugin.ID, "/icons/full/others/delete.gif")); this.selectedRepresentations = Collections2.filter(representations, new Predicate<DRepresentation>() { @Override public boolean apply(DRepresentation input) { EObject container = input.eContainer(); if (container instanceof DRepresentationContainer) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority != null && !permissionAuthority.canCreateIn(container)) { return false; } } return true; } }); if (this.selectedRepresentations.isEmpty()) { this.setEnabled(false); } }

Target:
public DeleteRepresentationAction(Collection<DRepresentation> representations) { super("Delete", AbstractUIPlugin.imageDescriptorFromPlugin(SiriusEditPlugin.ID, "/icons/full/others/delete.gif")); this.selectedRepresentations = Collections2.filter(representations, new Predicate<DRepresentation>() { @Override public boolean apply(DRepresentation input) { EObject container = input.eContainer(); if (container instanceof DRepresentationContainer) { IPermissionAuthority permissionAuthority = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(container); if (permissionAuthority != null && !permissionAuthority.canDeleteInstance(container)) { return false; } } return true; } }); if (this.selectedRepresentations.isEmpty()) { this.setEnabled(false); } }
Source:
public static void main(String[] args) { for(int i =0; i<5; i++) { rowMergerPerf(createResponses(1)); } for (int i = 1; i <= 101; i += 10) { System.out.println("==================="); System.out.println("using " + i + " Cells"); rowMergerPerf(createResponses(i)); } }

Target:
public static void main(String[] args) { for (int i = 0; i < 5; i++) { rowMergerPerf(createResponses(1)); } for (int i = 5; i <= 100; i += 10) { System.out.println("==================="); System.out.println("using " + i + " Cells"); rowMergerPerf(createResponses(i)); } }
Source:
private List<Machine> getMachines() { List<Machine> machines = new ArrayList<>(); Workspace workspace = appContext.getWorkspace(); if (workspace == null || workspace.getRuntime() == null) { return machines; } for (Machine currentMachine : workspace.getRuntime().getMachines()) { if (currentMachine instanceof MachineDto) { Machine machine = entityFactory.createMachine((MachineDto)currentMachine); machines.add(machine); } } return machines; }

Target:
private List<Machine> getMachines() { Workspace workspace = appContext.getWorkspace(); if (workspace == null || workspace.getRuntime() == null) { return emptyList(); } List<? extends Machine> runtimeMachines = workspace.getRuntime().getMachines(); List<Machine> machines = new ArrayList<>(runtimeMachines.size()); for (Machine currentMachine : runtimeMachines) { if (currentMachine instanceof MachineDto) { Machine machine = entityFactory.createMachine((MachineDto)currentMachine); machines.add(machine); } } return machines; }
Source:
private void ensureWritableBytes(int minWritableBytes) { assert slice.length() <= maxBufferSize; int neededBufferSize = bufferPosition + minWritableBytes; if (neededBufferSize <= slice.length()) { return; } if (slice.length() == maxBufferSize) { flushBufferToOutputStream(); return; } int newBufferSize = min(max(slice.length() * 2, minWritableBytes), maxBufferSize); if (neededBufferSize <= newBufferSize) { byte[] previousBuffer = buffer; buffer = new byte[newBufferSize]; slice = wrappedBuffer(buffer); System.arraycopy(previousBuffer, 0, buffer, 0, bufferPosition); } else { flushBufferToOutputStream(); buffer = new byte[newBufferSize]; slice = wrappedBuffer(buffer); assert bufferPosition == 0; assert minWritableBytes <= slice.length(); } }

Target:
private void ensureWritableBytes(int minWritableBytes) { checkArgument(minWritableBytes <= maxBufferSize, "Min writable bytes must not exceed max buffer size"); int neededBufferSize = bufferPosition + minWritableBytes; if (neededBufferSize <= slice.length()) { return; } if (slice.length() >= maxBufferSize) { flushBufferToOutputStream(); return; } int newBufferSize = min(max(slice.length() * 2, minWritableBytes), maxBufferSize); if (neededBufferSize <= newBufferSize) { byte[] previousBuffer = buffer; buffer = new byte[newBufferSize]; slice = wrappedBuffer(buffer); System.arraycopy(previousBuffer, 0, buffer, 0, bufferPosition); } else { flushBufferToOutputStream(); buffer = new byte[newBufferSize]; slice = wrappedBuffer(buffer); } }
Source:
public Map<String, String> parse(String input) { final Map<String, Object> inner = delegate.parse(input); final String k = Preconditions.checkNotNull( inner.get(key), "Key column [%s] missing data in line [%s]", key, input ).toString(); final Object val = inner.get(value); if (val == null) { return null; } return ImmutableMap.of(k, val.toString()); }

Target:
public Map<String, String> parse(String input) { final Map<String, Object> inner = delegate.parse(input); final String k = Preconditions.checkNotNull( inner.get(key), "Key column [%s] missing data in line [%s]", key, input ).toString(); final Object val = inner.get(value); if (val == null) { return ImmutableMap.of(); } return ImmutableMap.of(k, val.toString()); }
Source:
public void setUp() { this.client = DatabaseClientFactory.newClient( "localhost", 8011, new DatabaseClientFactory.DigestAuthContext("rest-admin", "x") ); }

Target:
public void setUp() { this.client = DatabaseClientFactory.newClient( "localhost", 8012, new DatabaseClientFactory.DigestAuthContext("rest-admin", "x") ); }
Source:
protected void setupTypeNameAndVersion(final FBNetworkElement model, Figure container) { container.add(middle, BorderLayout.CENTER); middle.setCornerDimensions(new Dimension()); GridLayout middleLayout = new GridLayout(1, true); middleLayout.marginHeight = 2; middleLayout.verticalSpacing = 1; middle.setLayoutManager(middleLayout); LibraryElement type = model.getType(); String typeName = (null != type) ? type.getName() : Messages.FBFigure_TYPE_NOT_SET; typeLabel = new UnderlineAlphaLabel(typeName != null ? typeName : Messages.FBFigure_NOT_DEFINED_Text); typeLabel.setTextAlignment(PositionConstants.CENTER); typeLabel.setOpaque(false); middle.add(typeLabel); middle.setConstraint(typeLabel, new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); setupMouseListener(editPart); }

Target:
protected void setupTypeNameAndVersion(final FBNetworkElement model, Figure container) { container.add(middle, BorderLayout.CENTER); middle.setCornerDimensions(new Dimension()); GridLayout middleLayout = new GridLayout(1, true); middleLayout.marginHeight = 2; middleLayout.verticalSpacing = 1; middle.setLayoutManager(middleLayout); LibraryElement type = model.getType(); String typeName = (null != type) ? type.getName() : Messages.FBFigure_TYPE_NOT_SET; typeLabel = new UnderlineAlphaLabel(null != typeName ? typeName : Messages.FBFigure_NOT_DEFINED_Text); typeLabel.setTextAlignment(PositionConstants.CENTER); typeLabel.setOpaque(false); middle.add(typeLabel); middle.setConstraint(typeLabel, new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); setupMouseListener(editPart); }
Source:
public MafEntry(String entry) { String fields = entry.split("\\s+"); if (fields.length != 7) throw new RuntimeException(entry); if (! fields[0].equals("s")) throw new RuntimeException(entry); src = fields[1]; start0 = Integer.parseInt(fields[2]); size = Integer.parseInt(fields[3]); strand = fields[4].equals("+"); if (! strand && !fields[4].equals("-") ) throw new RuntimeException(entry); srcSize = Integer.parseInt(fields[5]); text = fields[6]; }

Target:
public MafEntry(String entry) { String fields = entry.split("\\s+"); if (fields.length != 7) throw new RuntimeException("Unexpected MAF line: "+entry); if (! fields[0].equals("s")) throw new RuntimeException("Unexpected MAF line: "+entry); src = fields[1]; start0 = Integer.parseInt(fields[2]); size = Integer.parseInt(fields[3]); strand = fields[4].equals("+"); if (! strand && !fields[4].equals("-") ) throw new RuntimeException("Unexpected MAF line: "+entry); srcSize = Integer.parseInt(fields[5]); text = fields[6]; }
Source:
default String getFileName(){ return new File(getUrl().getPath()).getName(); }

Target:
default String getFileName() { String path = getUrl().getPath(); int end = path.lastIndexOf('/'); if (end < 0) { return path; } else { return path.substring(end + 1); } }
Source:
public void testGetAnalysisModules() { Map<String, IAnalysisModule> modules = TmfAnalysisManager.getAnalysisModules(); assertTrue(modules.size() >= 3); IAnalysisModule module = modules.get("org.eclipse.linuxtools.tmf.core.tests.analysis.test2"); assertTrue(module.isAutomatic()); module = modules.get("org.eclipse.linuxtools.tmf.core.tests.analysis.test"); assertFalse(module.isAutomatic()); }

Target:
public void testGetAnalysisModules() { Map<String, IAnalysisModule> modules = TmfAnalysisManager.getAnalysisModules(); assertTrue(modules.size() >= 3); IAnalysisModule module = modules.get(MODULE_PARAM_DEFAULT); assertTrue(module.isAutomatic()); module = modules.get(MODULE_PARAM); assertFalse(module.isAutomatic()); }
Source:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { this.startOutput(); for (Result result : results) { for (String resultString : resultParser(result)) { if (isDebugEnabled()) System.out.println(resultString); this.sendOutput(resultString); } } this.finishOutput(); }

Target:
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { this.startOutput(); for (Result result : results) { for (String resultString : resultParser(result)) { if (isDebugEnabled()) log.debug("TCollectorUDP Message: {}", resultString); this.sendOutput(resultString); } } this.finishOutput(); }
Source:
public static int portFromTaskId(String taskId) { String[] parts = taskId.trim().split("-"); if (parts.length < 3) { throw new IllegalArgumentException("TaskID " + taskId.trim() + " is invalid. " + "Number of dash-delimited components (" + parts.length + ") is less than expected. " + "Expected format is HOSTNAME-PORT-TIMESTAMP"); } String portString = parts[parts.length - 2]; int port; try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { LOG.error("Failed to parse string (" + portString + ") that was supposed to contain a port."); throw e; } if (port < 0 || port > 0xFFFF) { throw new IllegalArgumentException(port + " is not a valid port number"); } return port; }

Target:
public static int portFromTaskId(String taskId) { String[] parts = taskId.trim().split("-"); if (parts.length < 3) { throw new IllegalArgumentException(String.format("TaskID %s is invalid. " + "Number of dash-delimited components (%d) is less than expected. " + "Expected format is HOSTNAME-PORT-TIMESTAMP", taskId.trim(), parts.length)); } String portString = parts[parts.length - 2]; int port; try { port = Integer.parseInt(portString); } catch (NumberFormatException e) { LOG.error(String.format("Failed to parse string (%s) that was supposed to contain a port.", portString)); throw e; } if (port < 0 || port > 0xFFFF) { throw new IllegalArgumentException(String.format("%d is not a valid port number.", port)); } return port; }
Source:
public boolean launchConfigurationChanged(ILaunchConfiguration configuration) throws CoreException { if (ownsLaunchConfiguration(configuration)) { if (configuration.isWorkingCopy()) return true; launchConfigurationRemoved(configuration); return addLaunchConfiguration(configuration); } else if (ownedConfigs.contains(configuration)) { ILaunchBarManager manager = getManager(); manager.launchConfigurationRemoved(configuration); manager.launchConfigurationAdded(configuration); return true; } else { return false; } }

Target:
public boolean launchConfigurationChanged(ILaunchConfiguration configuration) throws CoreException { if (ownsLaunchConfiguration(configuration)) { launchConfigurationRemoved(configuration); return addLaunchConfiguration(configuration); } else if (ownedConfigs.contains(configuration)) { ILaunchBarManager manager = getManager(); manager.launchConfigurationRemoved(configuration); manager.launchConfigurationAdded(configuration); return true; } else { return false; } }
Source:
private byte[] getRenderedBlob() { try { writeDictionary(); } catch (IOException e) { throw new RuntimeException(e); } try { dictionaryDos.close(); metricDos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] dictionaryBytes = dictionaryBaos.toByteArray(); byte[] metricsBytes = metricBaos.toByteArray(); int completeSize = SIZE_VERSION + SIZE_DICTIONARY_BLOB + dictionaryBytes.length + metricsBytes.length; ByteArrayOutputStream baos = new ByteArrayOutputStream(completeSize); DataOutputStream dos = new DataOutputStream(baos); try { dos.write((BINARY_FORMAT_VERSION >>> BITS_IN_BYTE) & BYTE_MASK); dos.write(BINARY_FORMAT_VERSION & BYTE_MASK); dos.writeInt(dictionaryBytes.length); dos.write(dictionaryBytes); dos.write(metricsBytes); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); }

Target:
private byte[] getRenderedBlob() { try { writeDictionary(); dictionaryDos.close(); metricDos.close(); } catch (IOException e) { throw new RuntimeException(e); } byte[] dictionaryBytes = dictionaryBaos.toByteArray(); byte[] metricsBytes = metricBaos.toByteArray(); int completeSize = SIZE_VERSION + SIZE_DICTIONARY_BLOB + dictionaryBytes.length + metricsBytes.length; ByteArrayOutputStream baos = new ByteArrayOutputStream(completeSize); DataOutputStream dos = new DataOutputStream(baos); try { dos.write((BINARY_FORMAT_VERSION >>> BITS_IN_BYTE) & BYTE_MASK); dos.write(BINARY_FORMAT_VERSION & BYTE_MASK); dos.writeInt(dictionaryBytes.length); dos.write(dictionaryBytes); dos.write(metricsBytes); dos.close(); } catch (IOException e) { throw new RuntimeException(e); } return baos.toByteArray(); }
Source:
public AdsBaseObject verifySlotAttribute(String slotName, String attribute, String value) { String slotParam = getSlotAttribute(slotName, attribute); Assertion.assertStringContains(slotParam, value); PageObjectLogging .log("verifySlotAttribute", slotName + " has following ['" + attribute + "'] attribute: " + slotParam, true); return this; }

Target:
public AdsBaseObject verifySlotAttribute(String slotName, String attribute, String value) { String slotParam = getSlotAttribute(slotName, attribute); Assertion.assertStringContains(slotParam, value); PageObjectLogging .log("verifySlotAttribute", String.format("%s has following [%s] attribute: %s", slotName, attribute, slotParam), true); return this; }
Source:
protected List<Page> getResultForQueryAndCache(final CriteriaQuery<Page> criteriaQuery) { TypedQuery<Page> q = em.createQuery(criteriaQuery); q.setHint(QueryHints.HINT_CACHEABLE, true); q.setHint(QueryHints.HINT_CACHE_REGION, "query.Cms"); try { return q.getResultList(); } catch (NoResultException | EntityNotFoundException e) { return new ArrayList<>(); } }

Target:
protected List<Page> getResultForQueryAndCache(final CriteriaQuery<Page> criteriaQuery) { TypedQuery<Page> q = em.createQuery(criteriaQuery); q.setHint(QueryHints.HINT_CACHEABLE, true); q.setHint(QueryHints.HINT_CACHE_REGION, "query.Cms"); try { return q.getResultList(); } catch (NoResultException | EntityNotFoundException e) { return Collections.emptyList(); } }
Source:
private void attemptAddRoutes() { LOGGER.trace( "Attempting to add routes for content directory monitor watching {}", monitoredDirectory); try { RouteBuilder routeBuilder = createRouteBuilder(); verifyContentCamelComponentIsAvailable("content"); verifyContentCamelComponentIsAvailable("catalog"); camelContext.addRoutes(routeBuilder); setRouteCollection(routeBuilder); } catch (Exception e) { LOGGER.info("Unable to configure Camel route.", e); INGEST_LOGGER.warn("Unable to configure Camel route.", e); } finally { if (LOGGER.isDebugEnabled()) { dumpCamelContext("after attemptAddRoutes()"); } } }

Target:
private void attemptAddRoutes() { LOGGER.trace( "Attempting to add routes for content directory monitor watching {}", monitoredDirectory); try { RouteBuilder routeBuilder = createRouteBuilder(); verifyCamelComponentIsAvailable("content"); verifyCamelComponentIsAvailable("catalog"); camelContext.addRoutes(routeBuilder); setRouteCollection(routeBuilder); } catch (Exception e) { LOGGER.info("Unable to configure Camel route.", e); INGEST_LOGGER.warn("Unable to configure Camel route.", e); } finally { if (LOGGER.isDebugEnabled()) { dumpCamelContext("after attemptAddRoutes()"); } } }
Source:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { if (turnFlags == EMPTY_FLAGS) { return; } BiFunction<Long, Long, Long> overwriteFunc = (oldFlags, newFlags) -> { return newFlags; }; setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, overwriteFunc); }

Target:
public void addTurnInfo(int fromEdge, int viaNode, int toEdge, long turnFlags) { setAndMergeTurnInfo(fromEdge, viaNode, toEdge, turnFlags, false, false); }
Source:
public void preferenceChange(PreferenceChangeEvent event) { if (LOG_LEVEL_KEY.equals(event.getKey())) { loggingLevel = Level.toLevel((String)event.getNewValue()); LOGGER.setLevel(loggingLevel); } else if (LOG_FILENAME_KEY.equals(event.getKey())) { path = (String)event.getNewValue(); } else if (LOG_BACKUP_COUNT_KEY.equals(event.getKey())) { RollingFileAppender appender = (RollingFileAppender)LOGGER.getAppender(EMFC_APPENDER_NAME); if (appender != null) { appender.setMaxBackupIndex(Integer.parseInt((String)event.getNewValue())); } } else if (LOG_FILE_MAX_SIZE_KEY.equals(event.getKey())) { RollingFileAppender appender = (RollingFileAppender)LOGGER.getAppender(EMFC_APPENDER_NAME); if (appender != null) { appender.setMaximumFileSize(Integer.parseInt((String)event.getNewValue()) * MEGABYTE); } } if (loggingLevel != null && !Level.OFF.equals(loggingLevel) && path != null) { initFile(); } }

Target:
public void preferenceChange(PreferenceChangeEvent event) { IEclipsePreferences prefs = instanceScope.getNode(EMFCompareRCPPlugin.PLUGIN_ID); path = prefs.get(LOG_FILENAME_KEY, ""); if (LOG_LEVEL_KEY.equals(event.getKey())) { loggingLevel = Level.toLevel((String)event.getNewValue()); LOGGER.setLevel(loggingLevel); } else if (LOG_FILENAME_KEY.equals(event.getKey())) { path = (String)event.getNewValue(); } else if (LOG_BACKUP_COUNT_KEY.equals(event.getKey())) { RollingFileAppender appender = (RollingFileAppender)LOGGER.getAppender(EMFC_APPENDER_NAME); if (appender != null) { appender.setMaxBackupIndex(Integer.parseInt((String)event.getNewValue())); } } else if (LOG_FILE_MAX_SIZE_KEY.equals(event.getKey())) { RollingFileAppender appender = (RollingFileAppender)LOGGER.getAppender(EMFC_APPENDER_NAME); if (appender != null) { appender.setMaximumFileSize(Integer.parseInt((String)event.getNewValue()) * MEGABYTE); } } if (loggingLevel != null && !Level.OFF.equals(loggingLevel) && path != null && path.length() > 0) { initFile(); } }
Source:
private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), principalName, true, true); if (principalRecord == null) { throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); } return new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); }

Target:
private DbUser getDbUserForPrincipalName(String principalName, String authzName) { ExtMap principalRecord = AuthzUtils.fetchPrincipalRecord( EngineExtensionsManager.getInstance().getExtensionByName(authzName), principalName, false, false); if (principalRecord == null) { throw new RuntimeException(String.format("Unable to find principal %s in domain '%s'", principalName, authzName)); } return new DbUser(DirectoryUtils.mapPrincipalRecordToDirectoryUser(authzName, principalRecord)); }
Source:
public void testInvertSortKey() { assertEquals("ffffffffffffffff", ChangeUtil.invertSortKey( "0000000000000000").toLowerCase()); assertEquals("0000000000000001", ChangeUtil .invertSortKey("FFFFFFFFFFFFFFFE")); assertEquals("0001600000000000", ChangeUtil .invertSortKey("FFFE9FFFFFFFFFFF")); assertEquals("/", ChangeUtil.invertSortKey("z")); assertEquals("z", ChangeUtil.invertSortKey("/").toLowerCase()); }

Target:
public void testInvertSortKey() { assertEquals("ffffffffffffffff", ChangeUtil.invertSortKey( "0000000000000000").toLowerCase()); assertEquals("0000000000000001", ChangeUtil .invertSortKey("FFFFFFFFFFFFFFFE")); assertEquals("0001600000000000", ChangeUtil .invertSortKey("FFFE9FFFFFFFFFFF")); assertEquals("/", ChangeUtil.invertSortKey("z")); assertEquals("z", ChangeUtil.invertSortKey("/")); }
Source:
public List<storage_pool> getAllByStatus(StoragePoolStatus status) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("status", status.getValue()); ParameterizedRowMapper<storage_pool> mapper = new ParameterizedRowMapper<storage_pool>() { @Override public storage_pool mapRow(ResultSet rs, int rowNum) throws SQLException { storage_pool entity = new storage_pool(); entity.setdescription(rs.getString("description")); entity.setId(Guid.createGuidFromString(rs.getString("id"))); entity.setname(rs.getString("name")); entity.setstorage_pool_type(StorageType.forValue(rs .getInt("storage_pool_type"))); entity.setstatus(StoragePoolStatus.forValue(rs.getInt("status"))); entity.setmaster_domain_version(rs .getInt("master_domain_version")); entity.setspm_vds_id(NGuid.createGuidFromString(rs .getString("spm_vds_id"))); entity.setcompatibility_version(new Version(rs .getString("compatibility_version"))); entity.setQuotaEnforcementType(QuotaEnforcementTypeEnum.forValue(rs.getInt("quota_enforcement_type"))); entity.setStoragePoolFormatType(getStorageFormatTypeForPool(rs)); return entity; } }; return getCallsHandler().executeReadList("GetAllByStatus", mapper, parameterSource); }

Target:
public List<storage_pool> getAllByStatus(StoragePoolStatus status) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource().addValue("status", status.getValue()); return getCallsHandler().executeReadList("GetAllByStatus", mapper, parameterSource); }
Source:
public void testBundledImageStyleCustomizationWithError() { try { openErrorLogViewByAPI(); SWTBot errorLogBot = bot.viewByTitle("Error Log").bot(); String error1 = "Extension Id 'sample.design.donut2' denote a stroke attribute but none attribute value is specified."; assertNotNull("Error \'" + error1 + "\' should be detected.", errorLogBot.tree().getTreeItem(error1)); String error2 = "Extension Id 'sample.design.donut2' denote a stop-color attribute but none attribute value is specified."; assertNotNull("Error \'" + error1 + "\' should be detected.", errorLogBot.tree().getTreeItem(error2)); } finally { SWTBotView errorView = bot.viewByTitle("Error Log"); if (errorView.isActive()) { errorView.close(); } bot.viewByTitle(PROPERTIES).setFocus(); } }

Target:
public void testBundledImageStyleCustomizationWithError() { try { openErrorLogViewByAPI(); SWTBot errorLogBot = bot.viewByTitle("Error Log").bot(); String error1 = "The org.eclipse.sirius.diagram.bundledImageShape extension of id 'sample.design.donut2' should have the colorAttribute attribute with a value."; assertNotNull("Error \'" + error1 + "\' should be detected.", errorLogBot.tree().getTreeItem(error1)); String error2 = "The org.eclipse.sirius.diagram.bundledImageShape extension of id 'sample.design.donut2' should have the borderColorAttribute attribute with a value."; assertNotNull("Error \'" + error1 + "\' should be detected.", errorLogBot.tree().getTreeItem(error2)); } finally { SWTBotView errorView = bot.viewByTitle("Error Log"); if (errorView.isActive()) { errorView.close(); } bot.viewByTitle(PROPERTIES).setFocus(); } }
Source:
public int hashCode() { return Objects.hash(replicaSet); }

Target:
public int hashCode() { return replicaSet.hashCode(); }
Source:
public AsyncJSON(Factory factory) { this.factory = factory; this.stringBuilder = new Utf8StringBuilder(32); this.numberBuilder = new NumberBuilder(); }

Target:
public AsyncJSON(Factory factory) { this.factory = factory; }
Source:
public byte[] toBytes() { ByteBuffer idBuf = ByteBuffer.allocate(sizeInBytes()); idBuf.putShort(version); byte flag; switch (version) { case BLOB_ID_V1: break; case BLOB_ID_V2: case BLOB_ID_V3: flag = (byte) (type.ordinal() & BLOB_ID_TYPE_MASK); idBuf.put(flag); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; case BLOB_ID_V4: flag = (byte) (type.ordinal() & BLOB_ID_TYPE_MASK); flag |= isEncrypted ? IS_ENCRYPTED_MASK : 0; idBuf.put(flag); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; case BLOB_ID_V5: flag = (byte) (type.ordinal() & BLOB_ID_TYPE_MASK); flag |= isEncrypted ? IS_ENCRYPTED_MASK : 0; if (blobDataType != null) { flag |= (blobDataType.ordinal() << BLOB_DATA_TYPE_SHIFT); } idBuf.put(flag); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } idBuf.put(partitionId.getBytes()); idBuf.putInt(uuid.getBytes().length); idBuf.put(uuid.getBytes()); return idBuf.array(); }

Target:
public byte[] toBytes() { ByteBuffer idBuf = ByteBuffer.allocate(sizeInBytes()); idBuf.putShort(version); byte flag; switch (version) { case BLOB_ID_V1: break; case BLOB_ID_V2: case BLOB_ID_V3: flag = (byte) (type.ordinal() & BLOB_ID_TYPE_MASK); idBuf.put(flag); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; case BLOB_ID_V4: flag = (byte) (type.ordinal() & BLOB_ID_TYPE_MASK); flag |= isEncrypted ? IS_ENCRYPTED_MASK : 0; idBuf.put(flag); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; case BLOB_ID_V5: flag = (byte) (type.ordinal() & BLOB_ID_TYPE_MASK); flag |= isEncrypted ? IS_ENCRYPTED_MASK : 0; flag |= (blobDataType.ordinal() << BLOB_DATA_TYPE_SHIFT); idBuf.put(flag); idBuf.put(datacenterId); idBuf.putShort(accountId); idBuf.putShort(containerId); break; default: throw new IllegalArgumentException("blobId version=" + version + " not supported"); } idBuf.put(partitionId.getBytes()); idBuf.putInt(uuid.getBytes().length); idBuf.put(uuid.getBytes()); return idBuf.array(); }
Source:
public Response updateConnection( DatabaseConnection connection ) throws ConnectionServiceException { new UtilHtmlSanitizer().sanitizeConnectionParameters( connection ); try { applySavedPassword( connection ); boolean success = connectionService.updateConnection( connection ); if ( success ) { return Response.ok().build(); } else { return Response.notModified().build(); } } catch ( Throwable t ) { t.printStackTrace(); return Response.serverError().build(); } }

Target:
public Response updateConnection( DatabaseConnection connection ) throws ConnectionServiceException { sanitizer.sanitizeConnectionParameters( connection ); try { applySavedPassword( connection ); boolean success = connectionService.updateConnection( connection ); if ( success ) { return Response.ok().build(); } else { return Response.notModified().build(); } } catch ( Throwable t ) { t.printStackTrace(); return Response.serverError().build(); } }
Source:
public void execute(String resultsCache) throws CacheException { if (resultsCache == null || resultsCache.isEmpty()) { throw new IllegalArgumentException("Results cache can not be " + resultsCache); } Cache<Object, Object> rCache = cache.getCacheManager().getCache(resultsCache); if (rCache == null) { throw new IllegalArgumentException("Result cache " + resultsCache + " is not defined on this node"); } executeHelper(resultsCache); }

Target:
public void execute(String resultsCache) throws CacheException { if (resultsCache == null || resultsCache.isEmpty()) { throw new IllegalArgumentException("Results cache can not be " + resultsCache); } executeHelper(resultsCache); }
Source:
public static FluidStack createFluidStack(String name, int amount) { Fluid fluid = getFirstFluid(name.toLowerCase()); return fluid == null ? null : new FluidStack(fluid, amount); }

Target:
public static FluidStack createFluidStack(String name, int amount) { Fluid fluid = getFirstFluid(name.toLowerCase(Locale.ENGLISH)); return fluid == null ? null : new FluidStack(fluid, amount); }
Source:
public ConcurrentMap<String, Pair<Long, Long>> getRetainedRegionRWRequestsCnt() { return this.retainedRegionRWRequestsCnt; }

Target:
protected ConcurrentMap<String, Pair<Long, Long>> getRetainedRegionRWRequestsCnt() { return this.retainedRegionRWRequestsCnt; }
Source:
static int doMain(String[] args) { ServerConfiguration conf; try { conf = parseCommandLine(args); } catch (IllegalArgumentException iae) { return ExitCode.INVALID_CONF; } LifecycleComponent server; try { server = buildBookieServer(new BookieConfiguration(conf)); } catch (Exception e) { log.error("Failed to build bookie server", e); return ExitCode.SERVER_EXCEPTION; } try { ComponentStarter.startComponent(server).get(); } catch (InterruptedException ie) { log.info("Bookie server is interrupted. Exiting ..."); } catch (ExecutionException ee) { log.error("Error in bookie shutdown", ee); return ExitCode.SERVER_EXCEPTION; } return ExitCode.OK; }

Target:
static int doMain(String[] args) { ServerConfiguration conf; try { conf = parseCommandLine(args); } catch (IllegalArgumentException iae) { return ExitCode.INVALID_CONF; } LifecycleComponent server; try { server = buildBookieServer(new BookieConfiguration(conf)); } catch (Exception e) { log.error("Failed to build bookie server", e); return ExitCode.SERVER_EXCEPTION; } try { ComponentStarter.startComponent(server).get(); } catch (InterruptedException ie) { log.info("Bookie server is interrupted. Exiting ..."); } catch (ExecutionException ee) { log.error("Error in bookie shutdown", ee.getCause()); return ExitCode.SERVER_EXCEPTION; } return ExitCode.OK; }
Source:
public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { ClientConfiguration clientConf = new ClientConfiguration(conf); clientConf.setDiskWeightBasedPlacementEnabled(true); try (BookKeeper bk = new BookKeeper(clientConf)) { Map<BookieSocketAddress, BookieInfo> map = bk.getBookieInfo(); if (map.size() == 0) { System.out.println("Failed to retrieve bookie information from any of the bookies"); bk.close(); return true; } System.out.println("Free disk space info:"); long totalFree = 0, total = 0; Map<String, BookieInfoReader.BookieInfo> dedupedMap = map.entrySet() .stream() .map(e -> { BookieInfoReader.BookieInfo bInfo = e.getValue(); BookieSocketAddress bookieId = e.getKey(); System.out.println(CommandHelpers.getBookieSocketAddrStringRepresentation(bookieId) + ":\tFree: " + bInfo.getFreeDiskSpace() + getReadable(bInfo.getFreeDiskSpace()) + "\tTotal: " + bInfo.getTotalDiskSpace() + getReadable(bInfo.getTotalDiskSpace())); return e; }) .collect( Collectors.toMap( entry -> entry.getKey().getHostName(), entry -> entry.getValue(), (key1, key2) -> key2 )); for (BookieInfoReader.BookieInfo bookieInfo : dedupedMap.values()) { totalFree += bookieInfo.getFreeDiskSpace(); total += bookieInfo.getTotalDiskSpace(); } System.out.println("Total free disk space in the cluster:\t" + totalFree + getReadable(totalFree)); System.out.println("Total disk capacity in the cluster:\t" + total + getReadable(total)); bk.close(); return true; } catch (IOException | InterruptedException | BKException e) { e.printStackTrace(); } return true; }

Target:
public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { ClientConfiguration clientConf = new ClientConfiguration(conf); clientConf.setDiskWeightBasedPlacementEnabled(true); try (BookKeeper bk = new BookKeeper(clientConf)) { Map<BookieSocketAddress, BookieInfo> map = bk.getBookieInfo(); if (map.size() == 0) { System.out.println("Failed to retrieve bookie information from any of the bookies"); bk.close(); return true; } System.out.println("Free disk space info:"); long totalFree = 0, total = 0; for (Map.Entry<BookieSocketAddress, BookieInfo> e : map.entrySet()) { BookieInfo bInfo = e.getValue(); BookieSocketAddress bookieId = e.getKey(); System.out.println(CommandHelpers.getBookieSocketAddrStringRepresentation(bookieId) + ":\tFree: " + bInfo.getFreeDiskSpace() + getReadable(bInfo.getFreeDiskSpace()) + "\tTotal: " + bInfo.getTotalDiskSpace() + getReadable(bInfo.getTotalDiskSpace())); } Map<String, BookieInfo> dedupedMap = map.entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey().getHostName(), entry -> entry.getValue(), (key1, key2) -> key2 )); for (BookieInfo bookieInfo : dedupedMap.values()) { totalFree += bookieInfo.getFreeDiskSpace(); total += bookieInfo.getTotalDiskSpace(); } System.out.println("Total free disk space in the cluster:\t" + totalFree + getReadable(totalFree)); System.out.println("Total disk capacity in the cluster:\t" + total + getReadable(total)); bk.close(); return true; } catch (IOException | InterruptedException | BKException e) { e.printStackTrace(); } return true; }
Source:
private boolean checkQueryAccess(OperationContext ctx,QueryExpression query) { if(query!=null) { CompositeMetadata md=ctx.getTopLevelEntityMetadata(); FieldAccessRoleEvaluator eval=new FieldAccessRoleEvaluator(md,ctx.getCallerRoles()); List<FieldInfo> fields=query.getQueryFields(); LOGGER.debug("Checking access for query fields {}",fields); for(FieldInfo field:fields) { LOGGER.debug("Access checking field {}",field.getAbsFieldName()); if(eval.hasAccess(field.getAbsFieldName(),FieldAccessRoleEvaluator.Operation.find)) { LOGGER.debug("Field is readable",field.getAbsFieldName()); } else { LOGGER.debug("Field is not readable",field.getAbsFieldName()); ctx.addError(Error.get(CrudConstants.ERR_NO_ACCESS, field.getAbsFieldName().toString())); ctx.setStatus(OperationStatus.ERROR); return false; } } } return true; }

Target:
private boolean checkQueryAccess(OperationContext ctx,QueryExpression query) { boolean ret=true; if(query!=null) { CompositeMetadata md=ctx.getTopLevelEntityMetadata(); FieldAccessRoleEvaluator eval=new FieldAccessRoleEvaluator(md,ctx.getCallerRoles()); List<FieldInfo> fields=query.getQueryFields(); LOGGER.debug("Checking access for query fields {}",fields); for(FieldInfo field:fields) { LOGGER.debug("Access checking field {}",field.getAbsFieldName()); if(eval.hasAccess(field.getAbsFieldName(),FieldAccessRoleEvaluator.Operation.find)) { LOGGER.debug("Field is readable",field.getAbsFieldName()); } else { LOGGER.debug("Field is not readable",field.getAbsFieldName()); ctx.addError(Error.get(CrudConstants.ERR_NO_ACCESS, field.getAbsFieldName().toString())); ctx.setStatus(OperationStatus.ERROR); ret=false; } } } return ret; }
Source:
private void calculateTotalAgentsInHostgroups() { int agentsToExpect = 0; for (Entity entity : getChildren()) { if (entity instanceof AmbariHostGroup) { agentsToExpect += entity.getConfig(AmbariHostGroup.INITIAL_SIZE); } } setAttribute(EXPECTED_AGENTS, agentsToExpect); }

Target:
private void calculateTotalAgentsInHostgroups() { int agentsToExpect = 0; for (AmbariHostGroup hostGroup : getHostGroups()) { agentsToExpect += hostGroup.getConfig(AmbariHostGroup.INITIAL_SIZE); } setAttribute(EXPECTED_AGENTS, agentsToExpect); }
Source:
public void onBlockHighlight(DrawBlockHighlightEvent event) { Item equipped = event.player.getCurrentEquippedItem() != null ? event.player.getCurrentEquippedItem().getItem() : null; int x = event.target.blockX; int y = event.target.blockY; int z = event.target.blockZ; if ((event.target.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) && (event.player.worldObj.getBlock(x, y, z) instanceof BlockPipe) && (equipped != null) && ((event.player.getCurrentEquippedItem().getItem() instanceof IPipeWrench && ((IPipeWrench) equipped).canWrench(event.player, x, y, z)))) { RayTracer.retraceBlock(event.player.worldObj, event.player, x, y, z); } }

Target:
public void onBlockHighlight(DrawBlockHighlightEvent event) { Item equipped = event.player.getCurrentEquippedItem() != null ? event.player.getCurrentEquippedItem().getItem() : null; int x = event.target.blockX; int y = event.target.blockY; int z = event.target.blockZ; if ((event.target.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) && (event.player.worldObj.getBlock(x, y, z) instanceof BlockPipe) && (equipped != null) && ((equipped instanceof IPipeWrench && ((IPipeWrench) equipped).canWrench(event.player, x, y, z)))) { RayTracer.retraceBlock(event.player.worldObj, event.player, x, y, z); } }
Source:
public Object changePassword(String payload) throws JSONException { NuxeoPrincipal currentUser = (NuxeoPrincipal) getContext().getCoreSession().getPrincipal(); JSONObject payloadJson = new JSONObject(payload); String oldPassword = payloadJson.getString("oldPassword"); String newPassword = payloadJson.getString("newPassword"); UserManager userManager = Framework.getService(UserManager.class); if (userManager.checkUsernamePassword(currentUser.getName(), oldPassword)) { currentUser.setPassword(newPassword); UpdateUserUnrestricted updateUserUnrestricted = new UpdateUserUnrestricted(ctx.getCoreSession(), currentUser.getModel()); updateUserUnrestricted.runUnrestricted(); return currentUser; } else { return Response.status(Status.UNAUTHORIZED).build(); } }

Target:
public Object changePassword(String payload) throws JSONException { NuxeoPrincipal currentUser = (NuxeoPrincipal) getContext().getCoreSession().getPrincipal(); JSONObject payloadJson = new JSONObject(payload); String oldPassword = payloadJson.getString("oldPassword"); String newPassword = payloadJson.getString("newPassword"); UserManager userManager = Framework.getService(UserManager.class); if (userManager.checkUsernamePassword(currentUser.getName(), oldPassword)) { currentUser.setPassword(newPassword); Framework.doPrivileged(() -> userManager.updateUser(currentUser.getModel())); return currentUser; } else { return Response.status(Status.UNAUTHORIZED).build(); } }
Source:
public GatewayResponse<BaseCaptureResponse> capture(ChargeEntity chargeEntity) { return getPaymentProviderFor(chargeEntity) .getCaptureHandler() .capture(CaptureGatewayRequest.valueOf(chargeEntity)); }

Target:
private GatewayResponse<BaseCaptureResponse> capture(ChargeEntity chargeEntity) { return getPaymentProviderFor(chargeEntity) .getCaptureHandler() .capture(CaptureGatewayRequest.valueOf(chargeEntity)); }
Source:
private boolean restoreVolumeToSnapshot(Guid upServerId, GlusterVolumeEntity volume, String snapshotName) { if (volume != null) { try (EngineLock lock = acquireEngineLock(volume.getId(), LockingGroup.GLUSTER)) { VDSReturnValue retVal = runVdsCommand(VDSCommandType.RestoreGlusterVolumeSnapshot, new GlusterVolumeSnapshotActionVDSParameters(upServerId, volume.getName(), snapshotName)); if (!retVal.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_RESTORE_FAILED, retVal.getVdsError() .getMessage()); setSucceeded(false); return false; } else { getGlusterVolumeSnapshotDao().removeByName(volume.getId(), snapshotName); VDS upServer = getClusterUtils().getRandomUpServer(volume.getClusterId()); VDSReturnValue volDetailsRetVal = runVdsCommand(VDSCommandType.GetGlusterVolumeInfo, new GlusterVolumeInfoVDSParameters(upServer.getId(), volume.getClusterId(), volume.getName())); GlusterVolumeEntity fetchedVolume = ((Map<Guid, GlusterVolumeEntity>) volDetailsRetVal.getReturnValue()).get(volume.getId()); List<GlusterBrickEntity> fetchedBricks = fetchedVolume.getBricks(); if (fetchedBricks != null) { getGlusterBrickDao().removeAllInBatch(volume.getBricks()); for (GlusterBrickEntity fetchdBrick : fetchedVolume.getBricks()) { if (fetchdBrick.getServerId() != null) { fetchdBrick.setStatus(GlusterStatus.UP); getGlusterBrickDao().save(fetchdBrick); } } } } } } return true; }

Target:
private boolean restoreVolumeToSnapshot(Guid upServerId, GlusterVolumeEntity volume, String snapshotName) { if (volume != null) { try (EngineLock lock = acquireEngineLock(volume.getId(), LockingGroup.GLUSTER)) { VDSReturnValue retVal = runVdsCommand(VDSCommandType.RestoreGlusterVolumeSnapshot, new GlusterVolumeSnapshotActionVDSParameters(upServerId, volume.getName(), snapshotName)); if (!retVal.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_RESTORE_FAILED, retVal.getVdsError() .getMessage()); setSucceeded(false); return false; } else { getGlusterVolumeSnapshotDao().removeByName(volume.getId(), snapshotName); VDS upServer = getClusterUtils().getRandomUpServer(volume.getClusterId()); VDSReturnValue volDetailsRetVal = runVdsCommand(VDSCommandType.GetGlusterVolumeInfo, new GlusterVolumeInfoVDSParameters(upServer.getId(), volume.getClusterId(), volume.getName())); GlusterVolumeEntity fetchedVolume = ((Map<Guid, GlusterVolumeEntity>) volDetailsRetVal.getReturnValue()).get(volume.getId()); List<GlusterBrickEntity> fetchedBricks = fetchedVolume.getBricks(); if (fetchedBricks != null) { getGlusterBrickDao().removeAllInBatch(volume.getBricks()); for (GlusterBrickEntity fetchdBrick : fetchedVolume.getBricks()) { if (fetchdBrick.getServerId() != null) { fetchdBrick.setStatus(GlusterStatus.UP); getGlusterBrickDao().save(fetchdBrick); } else { log.warn("Invalid server details for brick " + fetchdBrick.getName() + ". Not adding now."); } } } } } } return true; }
Source:
public String get(Enum<?> key) { try { if(key == null){ return null; } String enumName = key.getDeclaringClass().toString(); enumName = enumName.substring(enumName.lastIndexOf(".")+1,enumName.length()); String translatedEnum = enums.getString(enumName + "___" + key.toString()); return translatedEnum; } catch (MissingResourceException e) { logger.info("Missing Enum resource: " + e.getLocalizedMessage()); return key.name(); } }

Target:
public String get(Enum<?> key) { if(key == null) { throw new IllegalArgumentException(); } try { String enumName = key.getDeclaringClass().toString(); enumName = enumName.substring(enumName.lastIndexOf(".")+1,enumName.length()); String translatedEnum = enums.getString(enumName + "___" + key.toString()); return translatedEnum; } catch (MissingResourceException e) { logger.info("Missing Enum resource: " + e.getLocalizedMessage()); return key.name(); } }