auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testAlterSchema() throws Exception { String topic = "test"; Schema avroSchema = AvroData.fromCopycatSchema(createSchema()); HiveExec hiveExec = new HiveExec(conf, connectorConfig); runHive(hiveExec, "DROP TABLE " + topic); hiveExec.createAvroTable(topic, avroSchema); Schema newAvroSchema = AvroData.fromCopycatSchema(createNewSchema()); hiveExec.alterScheam(topic, newAvroSchema); String description = runHive(hiveExec, "DESCRIBE " + topic); String[] colTypes = {"boolean", "int", "bigint", "float", "double", "string"}; String[] lines = description.split("\n"); for (int i = 0; i < colTypes.length; ++i) { String[] parts = lines[i].replace(" ", "").split("\t"); assertEquals(colTypes[i], parts[1]); } }

Target:
public void testAlterSchema() throws Exception { prepareData(TOPIC, PARTITION); Schema avroSchema = avroData.fromCopycatSchema(createSchema()); HiveExec hiveExec = new HiveExec(conf, connectorConfig); runHive(hiveExec, "DROP TABLE " + TOPIC); hiveExec.createAvroTable(TOPIC, avroSchema); hiveExec.addPartition(TOPIC, PARTITION); hiveExec.setPartitionLoc(TOPIC, PARTITION); Schema newAvroSchema = avroData.fromCopycatSchema(createNewSchema()); hiveExec.alterSchema(TOPIC, newAvroSchema); String description = runHive(hiveExec, "DESCRIBE " + TOPIC); String[] colTypes = {"boolean", "int", "bigint", "float", "double", "string"}; String[] lines = description.split("\n"); for (int i = 0; i < colTypes.length; ++i) { String[] parts = parseOutput(lines[i]); assertEquals(colTypes[i], parts[1]); } String[] expectedResult = {"true", "12", "12", "12.2", "12.2", "abc", "12"}; String result = runHive(hiveExec, "SELECT * from " + TOPIC); String[] rows = result.split("\n"); assertEquals(7, rows.length); for (String row: rows) { String[] parts = parseOutput(row); for (int j = 0; j < expectedResult.length; ++j) { assertEquals(expectedResult[j], parts[j]); } } }
Source:
public static void writeUpdateMessagesToFile(String text) { PrintWriter writer = null; File destFile = new File(OpenmrsUtil.getApplicationDataDirectory(), DatabaseUpdater.DATABASE_UPDATES_LOG_FILE); try { String lineSeparator = System.getProperty("line.separator"); Date date = Calendar.getInstance().getTime(); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile, true), StandardCharsets.UTF_8))); writer.write("********** START OF DATABASE UPDATE LOGS AS AT " + date + " **********"); writer.write(lineSeparator); writer.write(lineSeparator); writer.write(text); writer.write(lineSeparator); writer.write(lineSeparator); writer.write("*********** END OF DATABASE UPDATE LOGS AS AT " + date + " ***********"); writer.write(lineSeparator); writer.write(lineSeparator); if (writer.checkError()) { log.warn("An Error occured while writing warnings to the database update log file'"); } writer.close(); } catch (FileNotFoundException e) { log.warn("Failed to find the database update log file", e); } catch (IOException e) { log.warn("Failed to write to the database update log file", e); } finally { IOUtils.closeQuietly(writer); } }

Target:
public static void writeUpdateMessagesToFile(String text) { OutputStreamWriter streamWriter = null; PrintWriter writer = null; File destFile = new File(OpenmrsUtil.getApplicationDataDirectory(), DatabaseUpdater.DATABASE_UPDATES_LOG_FILE); try { String lineSeparator = System.getProperty("line.separator"); Date date = Calendar.getInstance().getTime(); streamWriter = new OutputStreamWriter(new FileOutputStream(destFile, true), StandardCharsets.UTF_8); writer = new PrintWriter(new BufferedWriter(streamWriter)); writer.write("********** START OF DATABASE UPDATE LOGS AS AT " + date + " **********"); writer.write(lineSeparator); writer.write(lineSeparator); writer.write(text); writer.write(lineSeparator); writer.write(lineSeparator); writer.write("*********** END OF DATABASE UPDATE LOGS AS AT " + date + " ***********"); writer.write(lineSeparator); writer.write(lineSeparator); if (writer.checkError()) { log.warn("An Error occured while writing warnings to the database update log file'"); } writer.close(); } catch (FileNotFoundException e) { log.warn("Failed to find the database update log file", e); } catch (IOException e) { log.warn("Failed to write to the database update log file", e); } finally { IOUtils.closeQuietly(streamWriter); IOUtils.closeQuietly(writer); } }
Source:
public boolean handleHeaderCell(final GridWidget gridWidget, final Point2D relativeLocation, final int uiHeaderRowIndex, final int uiHeaderColumnIndex, final AbstractNodeMouseEvent event) { final double cx = relativeLocation.getX(); final BaseGridRendererHelper rendererHelper = gridWidget.getRendererHelper(); final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(cx); final GridColumn<?> column = ci.getColumn(); if (column == null) { return false; } if (!EditableHeaderUtilities.hasEditableHeader(column)) { return false; } if (!EditableHeaderUtilities.isEditableHeader(column, uiHeaderRowIndex)) { return false; } final Point2D gridWidgetComputedLocation = gridWidget.getComputedLocation(); final BaseGridRendererHelper.RenderingInformation ri = rendererHelper.getRenderingInformation(); final EditableHeaderMetaData headerMetaData = (EditableHeaderMetaData) column.getHeaderMetaData().get(uiHeaderRowIndex); final GridBodyCellEditContext context = EditableHeaderUtilities.makeRenderContext(gridWidget, ri, ci, relativeLocation.add(gridWidgetComputedLocation), uiHeaderRowIndex); final GridData gridData = gridWidget.getModel(); if (gridData.getSelectedHeaderCells().size() == 1) { if (Objects.equals(headerMetaData.getSupportedEditAction(), GridCellEditAction.getSupportedEditAction(event))) { headerMetaData.edit(context); return true; } } return false; }

Target:
public boolean handleHeaderCell(final GridWidget gridWidget, final Point2D relativeLocation, final int uiHeaderRowIndex, final int uiHeaderColumnIndex, final AbstractNodeMouseEvent event) { final double cx = relativeLocation.getX(); final BaseGridRendererHelper rendererHelper = gridWidget.getRendererHelper(); final BaseGridRendererHelper.ColumnInformation ci = rendererHelper.getColumnInformation(cx); final GridColumn<?> column = ci.getColumn(); if (column == null) { return false; } if (!EditableHeaderUtilities.hasEditableHeader(column)) { return false; } if (!EditableHeaderUtilities.isEditableHeader(column, uiHeaderRowIndex)) { return false; } final Point2D gridWidgetComputedLocation = gridWidget.getComputedLocation(); final BaseGridRendererHelper.RenderingInformation ri = rendererHelper.getRenderingInformation(); final EditableHeaderMetaData headerMetaData = (EditableHeaderMetaData) column.getHeaderMetaData().get(uiHeaderRowIndex); final GridBodyCellEditContext context = EditableHeaderUtilities.makeRenderContext(gridWidget, ri, ci, relativeLocation.add(gridWidgetComputedLocation), uiHeaderRowIndex); if (isHeaderSelectionValid(gridWidget)) { if (Objects.equals(headerMetaData.getSupportedEditAction(), GridCellEditAction.getSupportedEditAction(event))) { headerMetaData.edit(context); return true; } } return false; }
Source:
public void waitTextNotPresentIntoLeftEditor(String expText) { webDriverWaitFactory .get() .until( (ExpectedCondition<Boolean>) webDriver -> !(getTextFromLeftEditorCompare().contains(expText))); }

Target:
public void waitTextNotPresentIntoLeftEditor(String expText) { seleniumWebDriverHelper.waitTextIsNotPresented(leftCompareEditor, expText); }
Source:
protected void checkArgType(ObjectInspector[] arguments, int i, PrimitiveCategory type) throws UDFArgumentTypeException{ PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arguments[i]).getPrimitiveCategory(); if (primitiveCategory != type) { throw new UDFArgumentTypeException(0, "A " + type.getClass().getSimpleName() + " argument was expected for " + getFuncName() + " but an argument of type " + arguments[i].getTypeName() + " was given." ); } }

Target:
protected void checkArgType(ObjectInspector[] arguments, int i, PrimitiveCategory type) throws UDFArgumentTypeException{ checkArgType(arguments[i], i, type); }
Source:
public void close() throws Exception { if (!closed.get()) { closed.set(true); socket.close(); executorService.shutdown(); } }

Target:
public void close() throws Exception { if (closed.compareAndSet(false, true)) { socket.close(); executorService.shutdown(); } }
Source:
private void markChildComponentsAsUnsafeWhereApplicable(Component component) { Component initialComponent = component.getParentComponent(); if (component.getParentComponent().getParentComponent() != null) { initialComponent = component.getParentComponent().getParentComponent(); } for (ComponentStatusChange statusChange : initialComponent.getStatusChanges()) { boolean dontMarkComponentAsUnsafeForThisStatusChange = statusChange.getStatusChangeReason().getType() .equals(ComponentStatusChangeReasonType.TEST_RESULTS_CONTAINS_PLASMA) && !component.getComponentType().getContainsPlasma(); if (!dontMarkComponentAsUnsafeForThisStatusChange) { markComponentAsUnsafe(component, ComponentStatusChangeReasonType.UNSAFE_PARENT); return; } } }

Target:
private void markChildComponentsAsUnsafeWhereApplicable(Component component) { Component initialComponent = component.getParentComponent(); while (initialComponent.getParentComponent() != null) { initialComponent = initialComponent.getParentComponent(); } boolean markComponentAsUnsafe = false; if (initialComponent.getStatusChanges() != null) { for (ComponentStatusChange statusChange : initialComponent.getStatusChanges()) { if (statusChange.getIsDeleted()) { continue; } if (!component.getComponentType().getContainsPlasma() && statusChange.getStatusChangeReason().getCategory() == ComponentStatusChangeReasonCategory.UNSAFE && statusChange.getStatusChangeReason().getType() == ComponentStatusChangeReasonType.TEST_RESULTS_CONTAINS_PLASMA) { continue; } if (statusChange.getStatusChangeReason().getCategory() == ComponentStatusChangeReasonCategory.UNSAFE) { markComponentAsUnsafe = true; break; } } } if (markComponentAsUnsafe) { markComponentAsUnsafe(component, ComponentStatusChangeReasonType.UNSAFE_PARENT); } }
Source:
public void createNewRAVESettings() throws InterruptedException { homePage.openAdmin(); adminPage.manageModules(); modulesPage.openEbodacSettings(); Long startTime = Long.valueOf(System.currentTimeMillis()); while (System.currentTimeMillis() - startTime.longValue() < START_TIME_LONG_VALUE) { try { ebodacSettingsPage.enableRAVE(); ebodacSettingsPage.setHostName(); ebodacSettingsPage.setPort(); ebodacSettingsPage.setRemoteFolder(); ebodacSettingsPage.setUsername(); ebodacSettingsPage.setPassword(); ebodacSettingsPage.setEmail(); } catch (Exception e) { Log.info("createNewRAVESettings exception"); } } ebodacSettingsPage.saveValues(); }

Target:
public void createNewRAVESettings() throws InterruptedException { homePage.openAdmin(); adminPage.manageModules(); modulesPage.openEbodacSettings(); Long startTime = Long.valueOf(System.currentTimeMillis()); while (System.currentTimeMillis() - startTime.longValue() < START_TIME_LONG_VALUE) { try { ebodacSettingsPage.enableRAVE(); ebodacSettingsPage.setHostName(); ebodacSettingsPage.setPort(); ebodacSettingsPage.setRemoteFolder(); ebodacSettingsPage.setUsername(); ebodacSettingsPage.setPassword(); ebodacSettingsPage.setEmail(); } catch (Exception e) { LOGGER.info("CreateNewRAVESettings exception"); } } ebodacSettingsPage.saveValues(); }
Source:
public void testApply(DimensionSpec dimensionSpec, Map<String, String> map) { for (Map.Entry<String, String> entry : map.entrySet()) { Assert.assertEquals(StringUtils.emptyToNullNonDruidDataString(entry.getValue()), dimensionSpec.getExtractionFn().apply(entry.getKey())); } }

Target:
public void testApply(DimensionSpec dimensionSpec, Map<String, String> map) { for (Map.Entry<String, String> entry : map.entrySet()) { Assert.assertEquals( NullHandling.emptyToNullIfNeeded(entry.getValue()), dimensionSpec.getExtractionFn().apply(entry.getKey()) ); } }
Source:
public static GeoIndexerType getGeoIndexerType(final Configuration conf) { String confType[] = conf.getStrings(GEO_INDEXER_TYPE); if (confType==null){ return null; } try { return GeoIndexerType.valueOf(GeoIndexerType.class, confType[0]); } catch (IllegalArgumentException e) { throw new Error("Configuration contains an unknown GeoIndexerType, found: \""+GEO_INDEXER_TYPE+"\"="+confType[0]); } }

Target:
public static GeoIndexerType getGeoIndexerType(final Configuration conf) { String confType[] = conf.getStrings(GEO_INDEXER_TYPE, GeoIndexerType.UNSPECIFIED.name()); try { return GeoIndexerType.valueOf(GeoIndexerType.class, confType[0]); } catch (IllegalArgumentException e) { throw new Error("Configuration contains an unknown GeoIndexerType, found: \""+GEO_INDEXER_TYPE+"\"="+confType[0]); } }
Source:
public static ResourceMapping[] getResourceMappings( @NonNull IResource resource, ResourceMappingContext context) { final IModelProviderDescriptor[] modelDescriptors = ModelProvider .getModelProviderDescriptors(); final Set<ResourceMapping> mappings = new LinkedHashSet<ResourceMapping>(); for (IModelProviderDescriptor candidate : modelDescriptors) { if (candidate.getId().startsWith("org.eclipse.egit")) { continue; } try { final IResource[] resources = candidate .getMatchingResources(new IResource[] { resource, }); if (resources.length > 0) { final ModelProvider model = candidate.getModelProvider(); final ResourceMapping[] modelMappings = model.getMappings( resource, context, new NullProgressMonitor()); for (ResourceMapping mapping : modelMappings) mappings.add(mapping); } } catch (CoreException e) { Activator.logError(e.getMessage(), e); } } return mappings.toArray(new ResourceMapping[mappings.size()]); }

Target:
public static ResourceMapping[] getResourceMappings( @NonNull IResource resource, ResourceMappingContext context) { final IModelProviderDescriptor[] modelDescriptors = ModelProvider .getModelProviderDescriptors(); final Set<ResourceMapping> mappings = new LinkedHashSet<ResourceMapping>(); for (IModelProviderDescriptor candidate : modelDescriptors) { try { final IResource[] resources = candidate .getMatchingResources(new IResource[] { resource, }); if (resources.length > 0) { final ModelProvider model = candidate.getModelProvider(); IgnoreInGitSynchronizations adapter = model .getAdapter(IgnoreInGitSynchronizations.class); if (adapter != null) { continue; } final ResourceMapping[] modelMappings = model.getMappings( resource, context, new NullProgressMonitor()); for (ResourceMapping mapping : modelMappings) mappings.add(mapping); } } catch (CoreException e) { Activator.logError(e.getMessage(), e); } } return mappings.toArray(new ResourceMapping[mappings.size()]); }
Source:
public void markRollbackOnly() { if ( getStatus() != TransactionStatus.ROLLED_BACK ) { if ( log.isDebugEnabled() ) { log.debug( "JDBC transaction marked for rollback-only (exception provided for stack trace)", new Exception( "exception just for purpose of providing stack trace" ) ); } rollbackOnly = true; } }

Target:
public void markRollbackOnly() { if ( getStatus() != TransactionStatus.ROLLED_BACK && getStatus() != TransactionStatus.NOT_ACTIVE ) { if ( log.isDebugEnabled() ) { log.debug( "JDBC transaction marked for rollback-only (exception provided for stack trace)", new Exception( "exception just for purpose of providing stack trace" ) ); } rollbackOnly = true; } }
Source:
protected void onCreate(Bundle b) { super.onCreate(b); String user = ""; String email = ""; String newSessionId = ""; Intent i = new Intent(); i.setAction("com.insecure.action.UserConnected"); i.putExtra("username", user); i.putExtra("email", email); i.putExtra("session", newSessionId); sendBroadcast(i); sendBroadcast(i, null); sendBroadcastAsUser(i, null); sendBroadcastAsUser(i,null,null); sendOrderedBroadcast(i,null); sendOrderedBroadcast(i,null,null,null,0,null,null); sendOrderedBroadcastAsUser(i,null,null,null,null,0,null,null); LocalBroadcastManager.getInstance(this).sendBroadcast(i); }

Target:
protected void onCreate(Bundle b) { super.onCreate(b); String user = ""; String email = ""; String newSessionId = ""; Intent i = new Intent(); i.setAction("com.insecure.action.UserConnected"); i.putExtra("username", user); i.putExtra("email", email); i.putExtra("session", newSessionId); sendBroadcast(i); sendBroadcast(i, null); sendBroadcastAsUser(i, null); sendBroadcastAsUser(i,null,null); sendOrderedBroadcast(i,null); sendOrderedBroadcast(i,null,null,null,0,null,null); sendOrderedBroadcastAsUser(i,null,null,null,null,0,null,null); LocalBroadcastManager.getInstance(this).sendBroadcast(i); CustomLocalBroadcastManager.getInstance(this).sendBroadcast(i); }
Source:
protected ContentMergeViewer(int style, ResourceBundle bundle, CompareConfiguration cc) { if (Policy.debugContentMergeViewer) { logTrace("constructed (fLeftLabel == null)"); logStackTrace(); } fStyles= style & ~(SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT); fBundle= bundle; fAncestorVisible= Utilities.getBoolean(cc, ICompareUIConstants.PROP_ANCESTOR_VISIBLE, fAncestorVisible); fConfirmSave= Utilities.getBoolean(cc, CompareEditor.CONFIRM_SAVE_PROPERTY, fConfirmSave); defaultContentProvider = new MergeViewerContentProvider(cc); leftToRight = cc.getProperty(ComparePreferencePage.LAYOUT).equals(ICompareUIConstants.PREF_VALUE_LEFT_TO_RIGHT); updateContentProvider(); fCompareInputChangeListener= new ICompareInputChangeListener() { public void compareInputChanged(ICompareInput input) { if (input == getInput()) { handleCompareInputChange(); } } }; if (cc == null) fCompareConfiguration = new CompareConfiguration(); else fCompareConfiguration= cc; fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { ContentMergeViewer.this.handlePropertyChangeEvent(event); } }; fCompareConfiguration.addPropertyChangeListener(fPropertyChangeListener); fIsLeftDirty = false; fIsRightDirty = false; }

Target:
protected ContentMergeViewer(int style, ResourceBundle bundle, CompareConfiguration cc) { if (Policy.debugContentMergeViewer) { logTrace("constructed (fLeftLabel == null)"); logStackTrace(); } fStyles= style & ~(SWT.LEFT_TO_RIGHT | SWT.RIGHT_TO_LEFT); fBundle= bundle; fAncestorVisible= Utilities.getBoolean(cc, ICompareUIConstants.PROP_ANCESTOR_VISIBLE, fAncestorVisible); fConfirmSave= Utilities.getBoolean(cc, CompareEditor.CONFIRM_SAVE_PROPERTY, fConfirmSave); defaultContentProvider = new MergeViewerContentProvider(cc); leftToRight = ICompareUIConstants.PREF_VALUE_LEFT_TO_RIGHT .equals(cc.getProperty(ComparePreferencePage.LAYOUT)); updateContentProvider(); fCompareInputChangeListener= new ICompareInputChangeListener() { @Override public void compareInputChanged(ICompareInput input) { if (input == getInput()) { handleCompareInputChange(); } } }; if (cc == null) fCompareConfiguration = new CompareConfiguration(); else fCompareConfiguration= cc; fPropertyChangeListener= new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { ContentMergeViewer.this.handlePropertyChangeEvent(event); } }; fCompareConfiguration.addPropertyChangeListener(fPropertyChangeListener); fIsLeftDirty = false; fIsRightDirty = false; }
Source:
public JournalContext createJournalContext() throws UnavailableException { return mJournal.createJournalContext(mMasterContext.stateChangeLock()); }

Target:
public JournalContext createJournalContext() throws UnavailableException { return new StateChangeJournalContext(mJournal.createJournalContext(), mMasterContext.stateChangeLock()); }
Source:
public ClusterBasedJobCoordinator(Config coordinatorSystemConfig) { this.metrics = new MetricsRegistryMap(); jobModelManager = buildJobModelManager(coordinatorSystemConfig, this.metrics); config = jobModelManager.jobModel().getConfig(); hasDurableStores = new StorageConfig(config).hasDurableStores(); state = new SamzaApplicationState(jobModelManager); this.partitionMonitor = getPartitionCountMonitor(config); clusterManagerConfig = new ClusterManagerConfig(config); isJmxEnabled = clusterManagerConfig.getJmxEnabled(); jobCoordinatorSleepInterval = clusterManagerConfig.getJobCoordinatorSleepInterval(); containerProcessManager = new ContainerProcessManager(config, state, this.metrics); }

Target:
public ClusterBasedJobCoordinator(Config coordinatorSystemConfig) { metrics = new MetricsRegistryMap(); jobModelManager = buildJobModelManager(coordinatorSystemConfig, metrics); config = jobModelManager.jobModel().getConfig(); hasDurableStores = new StorageConfig(config).hasDurableStores(); state = new SamzaApplicationState(jobModelManager); partitionMonitor = getPartitionCountMonitor(config); clusterManagerConfig = new ClusterManagerConfig(config); isJmxEnabled = clusterManagerConfig.getJmxEnabled(); jobCoordinatorSleepInterval = clusterManagerConfig.getJobCoordinatorSleepInterval(); containerProcessManager = new ContainerProcessManager(config, state, metrics); }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); permissionList.add(new PermissionSubject(getParameters().getSourceDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); if (getClusterId() != null) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CREATE_VM)); } if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); for (Guid storageId : imageToDestinationDomainMap.values()) { permissionList.add(new PermissionSubject(storageId, VdcObjectType.Storage, getActionType().getActionGroup())); } permissionList.add(new PermissionSubject(getParameters().getSourceDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; }
Source:
public static PropertyPath from(String source, TypeInformation<?> type) { Assert.hasText(source, "Source must not be null or empty!"); Assert.notNull(type, "TypeInformation must not be null or empty!"); List<String> iteratorSource = new ArrayList<>(); Matcher matcher = isQuoted(source) ? SPLITTER_FOR_QUOTED.matcher(source.replace("\\Q", "").replace("\\E", "")) : SPLITTER.matcher("_" + source); while (matcher.find()) { iteratorSource.add(matcher.group(1)); } Iterator<String> parts = iteratorSource.iterator(); PropertyPath result = null; Stack<PropertyPath> current = new Stack<>(); while (parts.hasNext()) { if (result == null) { result = create(parts.next(), type, current); current.push(result); } else { current.push(create(parts.next(), current)); } } if (result == null) { throw new IllegalStateException( String.format("Expected parsing to yield a PropertyPath from %s but got null!", source)); } return result; }

Target:
public static PropertyPath from(String source, TypeInformation<?> type) { Assert.hasText(source, "Source must not be null or empty!"); Assert.notNull(type, "TypeInformation must not be null or empty!"); return CACHE.computeIfAbsent(Key.of(type, source), it -> { List<String> iteratorSource = new ArrayList<>(); Matcher matcher = isQuoted(it.path) ? SPLITTER_FOR_QUOTED.matcher(it.path.replace("\\Q", "").replace("\\E", "")) : SPLITTER.matcher("_" + it.path); while (matcher.find()) { iteratorSource.add(matcher.group(1)); } Iterator<String> parts = iteratorSource.iterator(); PropertyPath result = null; Stack<PropertyPath> current = new Stack<>(); while (parts.hasNext()) { if (result == null) { result = create(parts.next(), it.type, current); current.push(result); } else { current.push(create(parts.next(), current)); } } if (result == null) { throw new IllegalStateException( String.format("Expected parsing to yield a PropertyPath from %s but got null!", source)); } return result; }); }
Source:
public static boolean isInteractive(String strategyId) { if (strategyId == null) { return false; } IExtensionRegistry extRegistry = Platform.getExtensionRegistry(); IConfigurationElement[] extensions = extRegistry.getConfigurationElementsFor(EXTENSION_POINT_ID); if (extensions != null) { for (IConfigurationElement extension : extensions) { if (strategyId.equals(readAttribute(extension, "id"))) { return Boolean.parseBoolean(readAttribute(extension, "interactive")); } } } return false; }

Target:
public static boolean isInteractive(String strategyId) { if (strategyId == null) { return false; } IExtensionRegistry extRegistry = Platform.getExtensionRegistry(); IConfigurationElement[] extensions = extRegistry.getConfigurationElementsFor(EXTENSION_POINT_ID); if (extensions != null) { for (IConfigurationElement extension : extensions) { if (strategyId.equals(readAttribute(extension, "id"))) { return Boolean.parseBoolean(readAttribute(extension, "interactive")); } } } IDEWorkbenchPlugin.log("No editor strategy found for " + strategyId); return false; }
Source:
public int hashCode() { final int prime = 37; int result = 17; for (int i = 0; i < numElements; i++) { result = result * prime + dvd[i].hashCode(); } return result; }

Target:
public int hashCode() { final int prime = 37; int result = 17; for (int i = 0; i < numElements; i++) { if (dvd[i] != null) result = result * prime + dvd[i].hashCode(); } return result; }
Source:
private byte[] receivedClientKeyExchange(final PSKClientKeyExchange message) throws HandshakeException { clientKeyExchange = message; String identity = message.getIdentity(); byte[] psk = pskStore.getKey(getIndicatedServerNames(), identity); String virtualHost = null; if (getIndicatedServerNames() == null) { LOGGER.debug("client uses PSK identity [{}]", getPeerAddress(), identity); } else { ServerName serverName = getIndicatedServerNames().getServerName(NameType.HOST_NAME); if (serverName == null) { LOGGER.debug("client provided invalid SNI extension which doesn't include a hostname", getPeerAddress()); } else { virtualHost = new String(serverName.getName(), ServerName.CHARSET); LOGGER.debug("client uses PSK identity for server [{}]", getPeerAddress(), identity, virtualHost); } } if (psk == null) { throw new HandshakeException( String.format("cannot authenticate client, identity [%s] is unknown for server [%s]", identity, virtualHost), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNKNOWN_PSK_IDENTITY, session.getPeer())); } else { session.setPeerIdentity(new PreSharedKeyIdentity(virtualHost, identity)); return generatePremasterSecretFromPSK(psk); } }

Target:
private byte[] receivedClientKeyExchange(final PSKClientKeyExchange message) throws HandshakeException { clientKeyExchange = message; String identity = message.getIdentity(); byte[] psk = pskStore.getKey(indicatedServerNames, identity); String virtualHost = null; if (indicatedServerNames == null) { LOGGER.debug("client uses PSK identity [{}]", getPeerAddress(), identity); } else { ServerName serverName = indicatedServerNames.getServerName(NameType.HOST_NAME); if (serverName == null) { LOGGER.debug("client provided invalid SNI extension which doesn't include a hostname", getPeerAddress()); } else { virtualHost = new String(serverName.getName(), ServerName.CHARSET); LOGGER.debug("client uses PSK identity for server [{}]", getPeerAddress(), identity, virtualHost); } } if (psk == null) { throw new HandshakeException( String.format("cannot authenticate client, identity [%s] is unknown for server [%s]", identity, virtualHost), new AlertMessage(AlertLevel.FATAL, AlertDescription.UNKNOWN_PSK_IDENTITY, session.getPeer())); } else { session.setPeerIdentity(new PreSharedKeyIdentity(virtualHost, identity)); return generatePremasterSecretFromPSK(psk); } }
Source:
public static void invalidateThumbnail(PublishedInfo layer) { Date d = new Date(new Date().getTime()-1000); if (Metadata.modified(layer) != null && d.before(Metadata.modified(layer))) { return; } Metadata.map(layer).remove(Metadata.THUMBNAIL); }

Target:
public static void invalidateThumbnail(PublishedInfo layer) { Metadata.map(layer).remove(Metadata.THUMBNAIL); }
Source:
private CommentDetail allComments() throws OrmException, NoSuchChangeException { ReviewDb db = schemaFactory.open(); final CommentDetail r = new CommentDetail(psa, psb); try { patchSet = db.patchSets().get(patchSetId); if (patchSet == null) { throw new NoSuchChangeException(changeId); } projectKey = change.getProject(); aId = psa != null ? toObjectId(db, psa) : null; bId = toObjectId(db, psb); final String pn = patchKey.get(); for (PatchLineComment p : db.patchComments().published(changeId, pn)) { r.include(p); } if (control.getCurrentUser() instanceof IdentifiedUser) { for (PatchLineComment p : db.patchComments().draft(changeId, pn, ((IdentifiedUser) control.getCurrentUser()).getAccountId())) { r.include(p); } } } finally { db.close(); } return r; }

Target:
private CommentDetail allComments() throws OrmException, NoSuchChangeException { ReviewDb db = schemaFactory.open(); try { final CommentDetail r = new CommentDetail(psa, psb); patchSet = db.patchSets().get(patchSetId); if (patchSet == null) { throw new NoSuchChangeException(changeId); } projectKey = change.getProject(); aId = psa != null ? toObjectId(db, psa) : null; bId = toObjectId(db, psb); final String pn = patchKey.get(); for (PatchLineComment p : db.patchComments().published(changeId, pn)) { r.include(p); } if (control.getCurrentUser() instanceof IdentifiedUser) { for (PatchLineComment p : db.patchComments().draft(changeId, pn, ((IdentifiedUser) control.getCurrentUser()).getAccountId())) { r.include(p); } } return r; } finally { db.close(); } }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); try { BSONConverter.validateSchema(Schema.parseJson(config.schema)); pipelineConfigurer.getStageConfigurer().setOutputSchema(Schema.parseJson(config.schema)); } catch (IOException e) { throw new IllegalArgumentException("Invalid schema", e); } }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); try { BSONConverter.validateSchema(Schema.parseJson(config.schema)); pipelineConfigurer.getStageConfigurer().setOutputSchema(Schema.parseJson(config.schema)); } catch (IOException e) { throw new IllegalArgumentException("Invalid output schema : " + e.getMessage(), e); } }
Source:
private void performGeoprocessing(final FeatureCollectionTable featureCollectionTable) { final ListenableFuture<GeoprocessingParameters> parameterFuture = mGeoprocessingTask.createDefaultParametersAsync(); parameterFuture.addDoneListener(new Runnable() { @Override public void run() { try { GeoprocessingParameters parameters = parameterFuture.get(); parameters.setProcessSpatialReference(featureCollectionTable.getSpatialReference()); parameters.setOutputSpatialReference(featureCollectionTable.getSpatialReference()); parameters.getInputs().put("Input_Observation_Point", new GeoprocessingFeatures(featureCollectionTable)); mGeoprocessingJob = mGeoprocessingTask.createJob(parameters); mGeoprocessingJob.start(); mGeoprocessingJob.addJobDoneListener(new Runnable() { @Override public void run() { GeoprocessingResult geoprocessingResult = mGeoprocessingJob.getResult(); GeoprocessingFeatures resultFeatures = (GeoprocessingFeatures) geoprocessingResult.getOutputs() .get("Viewshed_Result"); FeatureSet featureSet = resultFeatures.getFeatures(); for (Feature feature : featureSet) { Graphic graphic = new Graphic(feature.getGeometry()); mResultGraphicsOverlay.getGraphics().add(graphic); } } }); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }); }

Target:
private void performGeoprocessing(final FeatureCollectionTable featureCollectionTable) { final ListenableFuture<GeoprocessingParameters> parameterFuture = mGeoprocessingTask.createDefaultParametersAsync(); parameterFuture.addDoneListener(new Runnable() { @Override public void run() { try { GeoprocessingParameters parameters = parameterFuture.get(); parameters.setProcessSpatialReference(featureCollectionTable.getSpatialReference()); parameters.setOutputSpatialReference(featureCollectionTable.getSpatialReference()); parameters.getInputs().put("Input_Observation_Point", new GeoprocessingFeatures(featureCollectionTable)); mGeoprocessingJob = mGeoprocessingTask.createJob(parameters); mGeoprocessingJob.start(); mGeoprocessingJob.addJobDoneListener(new Runnable() { @Override public void run() { if (mGeoprocessingJob.getStatus() == Job.Status.SUCCEEDED) { GeoprocessingResult geoprocessingResult = mGeoprocessingJob.getResult(); GeoprocessingFeatures resultFeatures = (GeoprocessingFeatures) geoprocessingResult.getOutputs() .get("Viewshed_Result"); FeatureSet featureSet = resultFeatures.getFeatures(); for (Feature feature : featureSet) { Graphic graphic = new Graphic(feature.getGeometry()); mResultGraphicsOverlay.getGraphics().add(graphic); } } else { Toast.makeText(getApplicationContext(), "Geoprocessing result failed!", Toast.LENGTH_LONG).show(); } } }); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } }); }
Source:
public void iterationDone( Model model, int iteration) { int currentIteration = iteration + 1; long elapsed = System.currentTimeMillis() - start; long remaining = (iterationCount - currentIteration) * elapsed / currentIteration; long minutes = remaining / ( 1000 * 60 ); Date date = new Date( start + elapsed + remaining ); log.info( "Remaining time : " + minutes + "mn - End expected : " + date.toString() ); }

Target:
public void iterationDone( Model model, int iteration) { long currentIteration = iterationCounter.incrementAndGet(); long elapsed = System.currentTimeMillis() - start; long remaining = (iterationCount - currentIteration) * elapsed / currentIteration; long minutes = remaining / ( 1000 * 60 ); Date date = new Date( start + elapsed + remaining ); log.info( "Remaining time : " + minutes + "mn - End expected : " + date.toString() ); }
Source:
private void updateDB(Collection<PluginInfo> pluginInfos) { long now = system.now(); try (DbSession dbSession = dbClient.openSession(false)) { Map<String, PluginDto> allPreviousPluginsByKey = dbClient.pluginDao().selectAll(dbSession).stream() .collect(Collectors.toMap(PluginDto::getKee, identity())); for (PluginInfo pluginInfo : pluginInfos) { RemotePlugin remotePlugin = RemotePlugin.create(pluginInfo); String newJarMd5 = remotePlugin.file().getHash(); PluginDto previousDto = allPreviousPluginsByKey.get(pluginInfo.getKey()); if (previousDto == null) { LOG.debug("Register new plugin {}", pluginInfo.getKey()); PluginDto pluginDto = new PluginDto() .setUuid(uuidFactory.create()) .setKee(pluginInfo.getKey()) .setBasePluginKey(pluginInfo.getBasePlugin()) .setJarMd5(newJarMd5) .setCreatedAt(now) .setUpdatedAt(now); dbClient.pluginDao().insert(dbSession, pluginDto); } else if (!previousDto.getJarMd5().equals(newJarMd5)) { LOG.debug("Update plugin {}", pluginInfo.getKey()); previousDto .setBasePluginKey(pluginInfo.getBasePlugin()) .setJarMd5(newJarMd5) .setUpdatedAt(now); dbClient.pluginDao().update(dbSession, previousDto); } } dbSession.commit(); } }

Target:
private void updateDB(Collection<PluginInfo> pluginInfos) { long now = system.now(); try (DbSession dbSession = dbClient.openSession(false)) { Map<String, PluginDto> allPreviousPluginsByKey = dbClient.pluginDao().selectAll(dbSession).stream() .collect(Collectors.toMap(PluginDto::getKee, identity())); for (PluginInfo pluginInfo : pluginInfos) { RemotePlugin remotePlugin = RemotePlugin.create(pluginInfo); String newJarMd5 = remotePlugin.file().getHash(); PluginDto previousDto = allPreviousPluginsByKey.get(pluginInfo.getKey()); if (previousDto == null) { LOG.debug("Register new plugin {}", pluginInfo.getKey()); PluginDto pluginDto = new PluginDto() .setUuid(uuidFactory.create()) .setKee(pluginInfo.getKey()) .setBasePluginKey(pluginInfo.getBasePlugin()) .setHash(newJarMd5) .setCreatedAt(now) .setUpdatedAt(now); dbClient.pluginDao().insert(dbSession, pluginDto); } else if (!previousDto.getHash().equals(newJarMd5)) { LOG.debug("Update plugin {}", pluginInfo.getKey()); previousDto .setBasePluginKey(pluginInfo.getBasePlugin()) .setHash(newJarMd5) .setUpdatedAt(now); dbClient.pluginDao().update(dbSession, previousDto); } } dbSession.commit(); } }
Source:
private Constraint transferBetweenTwoFlights(ConstraintFactory constraintFactory) { return constraintFactory.from(Employee.class) .filter(e -> e.countInvalidConnections() > 0) .penalizeLong("Transfer between two flights", HardSoftLongScore.ofHard(1), Employee::countInvalidConnections); }

Target:
private Constraint transferBetweenTwoFlights(ConstraintFactory constraintFactory) { return constraintFactory.from(Employee.class) .filter(employee -> employee.countInvalidConnections() > 0) .penalizeLong("Transfer between two flights", HardSoftLongScore.ofHard(1), Employee::countInvalidConnections); }
Source:
public Parcelable onSaveInstanceState() { if (!isNavigationViewSavedStateMissing()) { return super.onSaveInstanceState(); } Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.selectedId = this.checkedId; return ss; }

Target:
public Parcelable onSaveInstanceState() { if (isNavigationViewSavedStateMissing()) { return super.onSaveInstanceState(); } Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.selectedId = this.checkedId; return ss; }
Source:
public int encodeByte(byte v, byte[] b, int o) { if (v < 0) { throw new IllegalDataException(); } Bytes.putByte(b, o, v); return Bytes.SIZEOF_BYTE; }

Target:
public int encodeByte(byte v, byte[] b, int o) { b[o] = (byte) (v ^ 0x80); return Bytes.SIZEOF_BYTE; }
Source:
public static void main(String[] args) throws CTFException { File f = new File(args[0]); if (f.isDirectory()) { CTFTrace trace = new CTFTrace(f); try (CTFTraceReader tr = new CTFTraceReader(trace)) { while (tr.hasMoreEvents()) { System.out.println(tr.getCurrentEventDef()); tr.advance(); } } } }

Target:
public static void main(String[] args) throws CTFException { File f = new File(args[0]); if (f.isDirectory()) { CTFTrace trace = new CTFTrace(f); try (CTFTraceReader tr = new CTFTraceReader(trace)) { while (tr.hasMoreEvents()) { System.out.println(tr.getCurrentEventDef()); tr.advance(); } } } else { System.err.println("%s is not a directory", args[0]); } }
Source:
protected Builder() { super(); id("azurecompute-arm") .name("Microsoft Azure Resource Manager REST API") .identityName("Azure Service Principal credential name") .credentialName("Azure Service Principal credential password") .endpointName("Resource Manager Endpoint ending in your Subscription Id") .documentation(URI.create("<LINK_0>")) .defaultProperties(AzureManagementApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>builder() .add(OAuthModule.class) .add(OkHttpCommandExecutorServiceModule.class) .add(AzureComputeHttpApiModule.class).build()); }

Target:
protected Builder() { super(); id("azurecompute-arm") .name("Microsoft Azure Resource Manager REST API") .identityName("Azure Service Principal Application Id") .credentialName("Azure Service Principal Application Password") .endpointName("Resource Manager Endpoint ending in your Subscription Id") .documentation(URI.create("<LINK_0>")) .defaultProperties(AzureManagementApiMetadata.defaultProperties()) .view(typeToken(ComputeServiceContext.class)) .defaultModules(ImmutableSet.<Class<? extends Module>>builder() .add(OAuthModule.class) .add(OkHttpCommandExecutorServiceModule.class) .add(AzureComputeHttpApiModule.class).build()); }
Source:
RSocketClient(DuplexConnection connection, Consumer<Throwable> errorConsumer, StreamIdSupplier streamIdSupplier, Duration tickPeriod, Duration ackTimeout, int missedAcks) { this.connection = connection; this.errorConsumer = errorConsumer; this.streamIdSupplier = streamIdSupplier; this.started = MonoProcessor.create(); this.senders = new IntObjectHashMap<>(256, 0.9f); this.receivers = new IntObjectHashMap<>(256, 0.9f); this.missedAckCounter = new AtomicInteger(); if (tickPeriod != Duration.ZERO) { long ackTimeoutMs = ackTimeout.toMillis(); this.keepAliveSendSub = started .thenMany(Flux.interval(tickPeriod)) .doOnSubscribe(s -> timeLastTickSentMs = System.currentTimeMillis()) .flatMap(i -> sendKeepAlive(ackTimeoutMs, missedAcks)) .doOnError(t -> { errorConsumer.accept(t); connection.close().subscribe(); }) .subscribe(); } connection .onClose() .doFinally(signalType -> cleanup()) .doOnError(errorConsumer::accept) .subscribe(); connection .receive() .doOnSubscribe(subscription -> started.onComplete()) .doOnNext(this::handleIncomingFrames) .doOnError(errorConsumer) .subscribe(); }

Target:
RSocketClient(DuplexConnection connection, Consumer<Throwable> errorConsumer, StreamIdSupplier streamIdSupplier, Duration tickPeriod, Duration ackTimeout, int missedAcks) { this.connection = connection; this.errorConsumer = errorConsumer; this.streamIdSupplier = streamIdSupplier; this.started = MonoProcessor.create(); this.senders = new IntObjectHashMap<>(256, 0.9f); this.receivers = new IntObjectHashMap<>(256, 0.9f); this.missedAckCounter = new AtomicInteger(); if (!Duration.ZERO.equals(tickPeriod)) { long ackTimeoutMs = ackTimeout.toMillis(); this.keepAliveSendSub = started .thenMany(Flux.interval(tickPeriod)) .doOnSubscribe(s -> timeLastTickSentMs = System.currentTimeMillis()) .flatMap(i -> sendKeepAlive(ackTimeoutMs, missedAcks)) .doOnError(t -> { errorConsumer.accept(t); connection.close().subscribe(); }) .subscribe(); } connection .onClose() .doFinally(signalType -> cleanup()) .doOnError(errorConsumer::accept) .subscribe(); connection .receive() .doOnSubscribe(subscription -> started.onComplete()) .doOnNext(this::handleIncomingFrames) .doOnError(errorConsumer) .subscribe(); }
Source:
public int setTabIndexes(int nextTabIndex) { nameEditor.setTabIndex(nextTabIndex++); descriptionEditor.setTabIndex(nextTabIndex++); typeEditor.setTabIndex(nextTabIndex++); datacenterEditor.setTabIndex(nextTabIndex++); urlEditor.setTabIndex(nextTabIndex++); nextTabIndex = vmwarePropertiesWidget.setTabIndexes(nextTabIndex); requiresAuthenticationEditor.setTabIndex(nextTabIndex++); usernameEditor.setTabIndex(nextTabIndex++); passwordEditor.setTabIndex(nextTabIndex++); tenantNameEditor.setTabIndex(nextTabIndex++); authUrlEditor.setTabIndex(nextTabIndex++); testButton.setTabIndex(nextTabIndex++); return nextTabIndex; }

Target:
public int setTabIndexes(int nextTabIndex) { nameEditor.setTabIndex(nextTabIndex++); descriptionEditor.setTabIndex(nextTabIndex++); typeEditor.setTabIndex(nextTabIndex++); datacenterEditor.setTabIndex(nextTabIndex++); pluginTypeEditor.setTabIndex(nextTabIndex++); urlEditor.setTabIndex(nextTabIndex++); nextTabIndex = vmwarePropertiesWidget.setTabIndexes(nextTabIndex); requiresAuthenticationEditor.setTabIndex(nextTabIndex++); usernameEditor.setTabIndex(nextTabIndex++); passwordEditor.setTabIndex(nextTabIndex++); tenantNameEditor.setTabIndex(nextTabIndex++); authUrlEditor.setTabIndex(nextTabIndex++); testButton.setTabIndex(nextTabIndex++); return nextTabIndex; }
Source:
private void scheduleHsErrCheck(LogListener logListener) { try { File installDir = getInstallDir(); if (installDir == null) { return; } Job job = new Job("Check hs_err_pid* files") { @Override protected IStatus run(IProgressMonitor monitor) { new HsErrPidLogCheck(installDir, logListener).run(); return Status.OK_STATUS; } }; job.schedule(TimeUnit.SECONDS.toMillis(30)); } catch (Exception e) { Logs.warn("hs err check failed", e); } }

Target:
private void scheduleHsErrCheck(LogListener logListener) { try { File installDir = getInstallDir().orNull(); if (installDir == null) { return; } Job job = new Job("Check hs_err_pid* files") { @Override protected IStatus run(IProgressMonitor monitor) { new HsErrPidLogCheck(installDir, logListener).run(); return Status.OK_STATUS; } }; job.schedule(TimeUnit.SECONDS.toMillis(30)); } catch (Exception e) { Logs.log(LogMessages.ERROR_HS_ERR_CHECK_FAILED, e); } }
Source:
public void configure(final MapperFactory mapperFactory) { mapperFactory .classMap(SmartMeteringDevice.class, com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice.class) .byDefault().register(); mapperFactory .classMap(com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice.class, com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice.class).byDefault().register(); }

Target:
public void configure(final MapperFactory mapperFactory) { mapperFactory .classMap(SmartMeteringDevice.class, com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice.class) .byDefault().register(); mapperFactory .classMap(com.alliander.osgp.domain.core.valueobjects.smartmetering.SmartMeteringDevice.class, com.alliander.osgp.dto.valueobjects.smartmetering.SmartMeteringDevice.class).byDefault() .register(); }
Source:
protected Guid lookupStorageDomainIdByName(String name) { if (!isFiltered()) { StorageDomain storageDomain = getEntity(org.ovirt.engine.core.common.businessentities.StorageDomain.class, VdcQueryType.GetStorageDomainByName, new NameQueryParameters(name), name); if (storageDomain != null) { return storageDomain.getId(); } return null; } else { List<org.ovirt.engine.core.common.businessentities.StorageDomain> storageDomains = getBackendCollection(org.ovirt.engine.core.common.businessentities.StorageDomain.class, VdcQueryType.GetAllStorageDomains, new VdcQueryParametersBase()); for (org.ovirt.engine.core.common.businessentities.StorageDomain storageDomain : storageDomains) { if (storageDomain.getStorageName().equals(name)) { return storageDomain.getId(); } } return null; } }

Target:
protected Guid lookupStorageDomainIdByName(String name) { if (!isFiltered()) { StorageDomain storageDomain = getEntity(org.ovirt.engine.core.common.businessentities.StorageDomain.class, VdcQueryType.GetStorageDomainByName, new NameQueryParameters(name), "Storage: name=" + name); if (storageDomain != null) { return storageDomain.getId(); } return null; } else { List<org.ovirt.engine.core.common.businessentities.StorageDomain> storageDomains = getBackendCollection(org.ovirt.engine.core.common.businessentities.StorageDomain.class, VdcQueryType.GetAllStorageDomains, new VdcQueryParametersBase()); for (org.ovirt.engine.core.common.businessentities.StorageDomain storageDomain : storageDomains) { if (storageDomain.getStorageName().equals(name)) { return storageDomain.getId(); } } return null; } }
Source:
public void testGetCallbackWhenIsNotValid() { final DataType dataType = mock(DataType.class); final Command onSuccess = mock(Command.class); final DataTypeFlashMessage flashMessage = mock(DataTypeFlashMessage.class); when(nameIsInvalidErrorMessage.getFlashMessage(dataType)).thenReturn(flashMessage); validator.getCallback(dataType, onSuccess).callback(false); verify(flashMessageEvent).fire(flashMessage); }

Target:
public void testGetCallbackWhenIsNotValid() { final DataType dataType = mock(DataType.class); final Command onSuccess = mock(Command.class); final DataTypeFlashMessage flashMessage = mock(DataTypeFlashMessage.class); when(nameIsInvalidErrorMessage.getFlashMessage(dataType)).thenReturn(flashMessage); validator.getCallback(dataType, onSuccess).callback(false); verify(flashMessageEvent).fire(flashMessage); verify(onSuccess, never()).execute(); }