auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testToolCreation(){ ApiClient webClient = getWebClient("admin@admin.com"); HostedApi api = new HostedApi(webClient); DockstoreTool hostedTool = api.createHostedTool("awesomeTool", "cwl", "quay.io", "coolNamespace"); Assert.assertNotNull("tool was not created properly", hostedTool); Assert.assertEquals("One user should belong to this tool, yourself",1, hostedTool.getUsers().size()); hostedTool.getUsers().forEach(user -> { Assert.assertNotNull("createHostedTool() endpoint should have user profiles", user.getUserProfiles()); user.setUserProfiles(null); }); assertTrue("tool was not created with a valid id", hostedTool.getId() != 0); ContainersApi oldApi = new ContainersApi(webClient); DockstoreTool container = oldApi.getContainer(hostedTool.getId()); hostedTool.setAliases(null); container.setAliases(null); Assert.assertEquals(container, hostedTool); Assert.assertEquals(1, container.getUsers().size()); container.getUsers().forEach(user -> { Assert.assertNull("getContainer() endpoint should not have user profiles", user.getUserProfiles()); }); }

Target:
public void testToolCreation(){ ApiClient webClient = getWebClient(ADMIN_USERNAME); HostedApi api = new HostedApi(webClient); DockstoreTool hostedTool = api.createHostedTool("awesomeTool", "cwl", "quay.io", "coolNamespace"); Assert.assertNotNull("tool was not created properly", hostedTool); Assert.assertEquals("One user should belong to this tool, yourself",1, hostedTool.getUsers().size()); hostedTool.getUsers().forEach(user -> { Assert.assertNotNull("createHostedTool() endpoint should have user profiles", user.getUserProfiles()); user.setUserProfiles(null); }); assertTrue("tool was not created with a valid id", hostedTool.getId() != 0); ContainersApi oldApi = new ContainersApi(webClient); DockstoreTool container = oldApi.getContainer(hostedTool.getId()); hostedTool.setAliases(null); container.setAliases(null); Assert.assertEquals(container, hostedTool); Assert.assertEquals(1, container.getUsers().size()); container.getUsers().forEach(user -> { Assert.assertNull("getContainer() endpoint should not have user profiles", user.getUserProfiles()); }); }
Source:
void layoutShell() { Display display = txtQuickAccess.getDisplay(); Rectangle tempBounds = txtQuickAccess.getBounds(); Rectangle compBounds = display.map(txtQuickAccess, null, tempBounds); int preferredWidth = dialogWidth == -1 ? (int) (txtQuickAccess.getShell().getBounds().width * 0.6) : dialogWidth; int width = Math.max(preferredWidth, compBounds.width); int height = dialogHeight == -1 ? (int) (txtQuickAccess.getShell().getBounds().height * 0.9) : dialogHeight; Rectangle shellBounds = txtQuickAccess.getShell().getBounds(); if (compBounds.x + width > shellBounds.x + shellBounds.width){ compBounds.x = Math.max(shellBounds.x, (compBounds.x + compBounds.width - width)); } shell.setBounds(getConstrainedShellBounds(display, new Rectangle(compBounds.x, compBounds.y + compBounds.height, width, height))); shell.layout(); }

Target:
void layoutShell() { Display display = txtQuickAccess.getDisplay(); Rectangle tempBounds = txtQuickAccess.getBounds(); Rectangle compBounds = display.map(txtQuickAccess, null, tempBounds); Rectangle shellBounds = txtQuickAccess.getShell().getBounds(); int preferredWidth = dialogWidth == -1 ? Math.min(300, (int) (shellBounds.width * 0.6)) : dialogWidth; int width = Math.max(preferredWidth, compBounds.width); int height = dialogHeight == -1 ? Math.min(200, (int) (shellBounds.height * 0.9)) : dialogHeight; if (compBounds.x + width > shellBounds.x + shellBounds.width){ compBounds.x = Math.max(shellBounds.x, (compBounds.x + compBounds.width - width)); } shell.setBounds(getConstrainedShellBounds(display, new Rectangle(compBounds.x, compBounds.y + compBounds.height, width, height))); shell.layout(); }
Source:
private int repositoryPathChecksumComparator(RepositoryPath p1, RepositoryPath p2) { Boolean isChecksumP1; Boolean isChecksumP2; isChecksumP1 = ThrowingFunction.unchecked(RepositoryFiles::isChecksum).apply(p1); isChecksumP2 = ThrowingFunction.unchecked(RepositoryFiles::isChecksum).apply(p2); if (isChecksumP1 && isChecksumP2) { return p1.compareTo(p2); } return isChecksumP1 ? 1 : -1; }

Target:
private int repositoryPathChecksumComparator(RepositoryPath p1, RepositoryPath p2) throws IOException { Boolean isChecksumP1; Boolean isChecksumP2; isChecksumP1 = RepositoryFiles.isChecksum(p1); isChecksumP2 = RepositoryFiles.isChecksum(p1); if (isChecksumP1 && isChecksumP2) { return p1.compareTo(p2); } return isChecksumP1 ? 1 : -1; }
Source:
private void wrapEntryForPutIfNeeded(InvocationContext ctx, AbstractDataWriteCommand command) throws Throwable { if (shouldWrap(command.getKey(), ctx, command)) { entryFactory.wrapEntryForPut(ctx, command.getKey(), null, false, command, command.hasFlag(Flag.IGNORE_RETURN_VALUES) && !command.isConditional()); } }

Target:
private void wrapEntryForPutIfNeeded(InvocationContext ctx, AbstractDataWriteCommand command) throws Throwable { if (shouldWrap(command.getKey(), ctx, command)) { boolean skipRead = command.hasFlag(Flag.IGNORE_RETURN_VALUES) && !command.isConditional(); entryFactory.wrapEntryForWriting(ctx, command.getKey(), EntryFactory.Wrap.WRAP_ALL, skipRead, false); } }
Source:
public boolean checkMutualAncestors(Person person, Campaign campaign) { return checkMutualAncestors(person.getGenealogy(), campaign, campaign.getCampaignOptions().checkMutualAncestorsDepth()); }

Target:
public boolean checkMutualAncestors(Person person, Campaign campaign) { if (getOrigin().equals(person.getId())) { return true; } final int depth = campaign.getCampaignOptions().checkMutualAncestorsDepth(); if (depth == 0) { return false; } Set<UUID> originAncestors = getAncestors(depth, campaign); Set<UUID> checkAncestors = person.getGenealogy().getAncestors(depth, campaign); for (UUID id : checkAncestors) { if (originAncestors.contains(id)) { return true; } } return false; }
Source:
public ConfigResolveOptions appendResolver(ConfigResolver value) { if (value == null) { throw new NullPointerException("null resolver passed to appendResolver"); } else if (value == this.resolver) { return this; } else { return new ConfigResolveOptions(useSystemEnvironment, allowUnresolved, this.resolver.withFallback(value)); } }

Target:
public ConfigResolveOptions appendResolver(ConfigResolver value) { if (value == null) { throw new ConfigException.BugOrBroken("null resolver passed to appendResolver"); } else if (value == this.resolver) { return this; } else { return new ConfigResolveOptions(useSystemEnvironment, allowUnresolved, this.resolver.withFallback(value)); } }
Source:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); userLocalMemoryContext.close(); revocableLocalMemoryContext.close(); systemLocalMemoryContext.close(); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }

Target:
public void close() { try (Closer closer = Closer.create()) { closer.register(userAggregateMemoryContext::close); closer.register(revocableAggregateMemoryContext::close); closer.register(systemAggregateMemoryContext::close); closer.register(userLocalMemoryContext::close); closer.register(revocableLocalMemoryContext::close); closer.register(systemLocalMemoryContext::close); } catch (IOException e) { throw new RuntimeException("Exception closing memory tracking context", e); } }
Source:
public <B> Eval<B> map(final F<A, B> f) { return bind(a -> now(f.f(a))); }

Target:
public final <B> Eval<B> map(final F<A, B> f) { return bind(a -> now(f.f(a))); }
Source:
public static FusionSchemaIndexProvider newInstance( PageCache pageCache, File storeDir, FileSystemAbstraction fs, LogProvider logProvider, Config config, OperationalMode operationalMode, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector ) { IndexDirectoryStructure.Factory childDirectoryStructure = subProviderDirectoryStructure( storeDir ); boolean readOnly = isReadOnly( config, operationalMode ); NativeSchemaNumberIndexProvider nativeProvider = new NativeSchemaNumberIndexProvider( pageCache, childDirectoryStructure, logProvider, recoveryCleanupWorkCollector, readOnly ); LuceneSchemaIndexProvider luceneProvider = LuceneSchemaIndexProviderFactory.create( fs, childDirectoryStructure, logProvider, config, operationalMode ); boolean useNativeIndex = config.get( GraphDatabaseSettings.enable_native_schema_index ); int priority = useNativeIndex ? PRIORITY : 0; return new FusionSchemaIndexProvider( directoriesByProvider( storeDir ), nativeProvider, luceneProvider, new NativeSelector(), DESCRIPTOR, priority ); }

Target:
public static FusionSchemaIndexProvider newInstance( PageCache pageCache, File storeDir, FileSystemAbstraction fs, LogProvider logProvider, Config config, OperationalMode operationalMode, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector ) { IndexDirectoryStructure.Factory childDirectoryStructure = subProviderDirectoryStructure( storeDir ); boolean readOnly = isReadOnly( config, operationalMode ); NativeSchemaNumberIndexProvider nativeProvider = new NativeSchemaNumberIndexProvider( pageCache, fs, childDirectoryStructure, logProvider, recoveryCleanupWorkCollector, readOnly ); LuceneSchemaIndexProvider luceneProvider = LuceneSchemaIndexProviderFactory.create( fs, childDirectoryStructure, logProvider, config, operationalMode ); boolean useNativeIndex = config.get( GraphDatabaseSettings.enable_native_schema_index ); int priority = useNativeIndex ? PRIORITY : 0; return new FusionSchemaIndexProvider( nativeProvider, luceneProvider, new NativeSelector(), DESCRIPTOR, priority, directoriesByProvider( storeDir ), fs ); }
Source:
public void removeIndex( final String indexName ) { CloseableIterator<InternalDataAdapter<?>> it = adapterStore.getAdapters(); final ArrayList<Short> markedAdapters = new ArrayList<Short>(); while (it.hasNext()) { final InternalDataAdapter<?> dataAdapter = it.next(); final AdapterToIndexMapping adapterIndexMap = indexMappingStore.getIndicesForAdapter(dataAdapter .getAdapterId()); final String[] indexNames = adapterIndexMap.getIndexNames(); for (int i = 0; i < indexNames.length; i++) { if (indexNames[i].equals(indexName)) { if (indexNames.length == 1) { throw new IllegalStateException( "Index removal failed. Adapters require at least one index."); } else { markedAdapters.add(adapterIndexMap.getAdapterId()); continue; } } } } it.close(); for (int i = 0; i < markedAdapters.size(); i++) { final short adapterId = markedAdapters.get(i); baseOperations.deleteAll( indexName, "", adapterId); statisticsStore.removeAllStatistics(adapterId); indexMappingStore.remove( adapterId, indexName); } indexStore.removeIndex(indexName); }

Target:
public void removeIndex( final String indexName ) { final ArrayList<Short> markedAdapters = new ArrayList<>(); try (CloseableIterator<InternalDataAdapter<?>> it = adapterStore.getAdapters()) { while (it.hasNext()) { final InternalDataAdapter<?> dataAdapter = it.next(); final AdapterToIndexMapping adapterIndexMap = indexMappingStore.getIndicesForAdapter(dataAdapter .getAdapterId()); final String[] indexNames = adapterIndexMap.getIndexNames(); for (int i = 0; i < indexNames.length; i++) { if (indexNames[i].equals(indexName)) { if (indexNames.length == 1) { throw new IllegalStateException( "Index removal failed. Adapters require at least one index."); } else { markedAdapters.add(adapterIndexMap.getAdapterId()); continue; } } } } } for (int i = 0; i < markedAdapters.size(); i++) { final short adapterId = markedAdapters.get(i); baseOperations.deleteAll( indexName, internalAdapterStore.getTypeName(adapterId), adapterId); statisticsStore.removeAllStatistics(adapterId); indexMappingStore.remove( adapterId, indexName); } indexStore.removeIndex(indexName); }
Source:
public DataTablesResponseDto<RunDto> dataTableByPlatform(@PathVariable("platform") String platform, HttpServletRequest request, HttpServletResponse response, UriComponentsBuilder uriBuilder) throws IOException { PlatformType platformType = PlatformType.valueOf(platform); if (platformType == null) { throw new RestException("Invalid platform type."); } return jQueryBackend.get(request, response, uriBuilder, PaginationFilter.platformType(platformType)); }

Target:
public DataTablesResponseDto<RunDto> dataTableByPlatform(@PathVariable("platform") String platform, HttpServletRequest request, HttpServletResponse response, UriComponentsBuilder uriBuilder) throws IOException { PlatformType platformType = PlatformType.valueOf(platform); if (platformType == null) { throw new RestException("Invalid platform type.", Status.BAD_REQUEST); } return jQueryBackend.get(request, response, uriBuilder, PaginationFilter.platformType(platformType)); }
Source:
public OutputWriter createOutputWriter() { if (file.exists() && overwriteFile) { final String pathname = file.getPath(); final boolean delete = file.delete(); if (delete) { file = new File(pathname); } else { throw new IllegalStateException("The previous file could not be deleted"); } } String[] headers = new String[columns.length]; for (int i = 0; i < headers.length; i++) { headers[i] = columns[i].getName(); } return ExcelOutputWriterFactory.getWriter(file.getPath(), sheetName, columns); }

Target:
public OutputWriter createOutputWriter() { if (file.exists() && overwriteFileIfExists) { final String pathname = file.getPath(); final boolean delete = file.delete(); if (delete) { file = new File(pathname); } else { throw new IllegalStateException("The existing file could not be deleted"); } } String[] headers = new String[columns.length]; for (int i = 0; i < headers.length; i++) { headers[i] = columns[i].getName(); } return ExcelOutputWriterFactory.getWriter(file.getPath(), sheetName, columns); }
Source:
private static String formatWindowSpecification(WindowSpecification node, Optional<List<Expression>> parameters) { List<String> parts = new ArrayList<>(); if (node.getExistingName().isPresent()) { parts.add(formatIdentifier(node.getExistingName().get()) + " "); } if (!node.getPartitionBy().isEmpty()) { parts.add("PARTITION BY " + joinExpressions(node.getPartitionBy(), parameters)); } if (!node.getOrderBy().isEmpty()) { parts.add("ORDER BY " + formatSortItems(node.getOrderBy(), parameters)); } if (node.getFrame().isPresent()) { parts.add(formatWindowFrame(node.getFrame().get(), parameters)); } return Joiner.on(' ').join(parts); }

Target:
private static String formatWindowSpecification(WindowSpecification node, Optional<List<Expression>> parameters) { List<String> parts = new ArrayList<>(); if (node.getExistingName().isPresent()) { parts.add(formatIdentifier(node.getExistingName().get().getValue()) + " "); } if (!node.getPartitionBy().isEmpty()) { parts.add("PARTITION BY " + joinExpressions(node.getPartitionBy(), parameters)); } if (!node.getOrderBy().isEmpty()) { parts.add("ORDER BY " + formatSortItems(node.getOrderBy(), parameters)); } if (node.getFrame().isPresent()) { parts.add(formatWindowFrame(node.getFrame().get(), parameters)); } return Joiner.on(' ').join(parts); }
Source:
public static com.openshift.restclient.model.IProject getProject(IResource resource) { IProject project = null; if (resource instanceof IProject) { project = (IProject) resource; } else if (resource != null) { project = resource.getProject(); } return project; }

Target:
public static IProject getProject(IResource resource) { IProject project = null; if (resource instanceof IProject) { project = (IProject) resource; } else if (resource != null) { project = resource.getProject(); } return project; }
Source:
private Collection<PluginFQN> parsePluginFQNs(String... plugins) throws InfrastructureException { List<PluginFQN> collectedFQNs = new ArrayList<>(); for (String plugin : plugins) { URI repo = null; String idVersionString; final int idVersionTagDelimiter = plugin.lastIndexOf("/"); idVersionString = plugin.substring(idVersionTagDelimiter + 1); if (idVersionTagDelimiter > -1) { try { repo = new URI(plugin.substring(0, idVersionTagDelimiter)); } catch (URISyntaxException e) { throw new InternalInfrastructureException( "Plugin registry URL is incorrect. Problematic plugin entry:" + plugin); } } String[] idVersion = idVersionString.split(":"); if (idVersion.length != 2 || idVersion[0].isEmpty() || idVersion[1].isEmpty()) { throw new InfrastructureException( "Plugin format is illegal. Problematic plugin entry:" + plugin); } if (collectedFQNs .stream() .anyMatch(p -> p.getId().equals(idVersion[0]) && p.getVersion().equals(idVersion[1]))) { throw new InfrastructureException( format( "Invalid Che tooling plugins configuration: plugin %s is duplicated", idVersion[0] + ":" + idVersion[1])); } collectedFQNs.add(new PluginFQN(repo, idVersion[0], idVersion[1])); } return collectedFQNs; }

Target:
private Collection<PluginFQN> parsePluginFQNs(String... plugins) throws InfrastructureException { List<PluginFQN> collectedFQNs = new ArrayList<>(); for (String plugin : plugins) { URI repo = null; String idVersionString; final int idVersionTagDelimiter = plugin.lastIndexOf("/"); idVersionString = plugin.substring(idVersionTagDelimiter + 1); if (idVersionTagDelimiter > -1) { try { repo = new URI(plugin.substring(0, idVersionTagDelimiter)); } catch (URISyntaxException e) { throw new InfrastructureException( "Plugin registry URL is incorrect. Problematic plugin entry:" + plugin); } } String[] idVersion = idVersionString.split(":"); if (idVersion.length != 2 || idVersion[0].isEmpty() || idVersion[1].isEmpty()) { throw new InfrastructureException( "Plugin format is illegal. Problematic plugin entry:" + plugin); } if (collectedFQNs .stream() .anyMatch(p -> p.getId().equals(idVersion[0]) && p.getVersion().equals(idVersion[1]))) { throw new InfrastructureException( format( "Invalid Che tooling plugins configuration: plugin %s is duplicated", idVersion[0] + ":" + idVersion[1])); } collectedFQNs.add(new PluginFQN(repo, idVersion[0], idVersion[1])); } return collectedFQNs; }
Source:
private static void addBondDeviceToHost(VDS vds, VdsNetworkInterface iface, Object[] interfaces) { vds.getInterfaces().add(iface); if (interfaces != null) { for (Object name : interfaces) { for (VdsNetworkInterface tempInterface : vds.getInterfaces()) { if (tempInterface.getName().equals(name.toString())) { tempInterface.setBondName(iface.getName()); } } } } }

Target:
private static void addBondDeviceToHost(VDS vds, VdsNetworkInterface iface, Object[] interfaces) { vds.getInterfaces().add(iface); if (interfaces != null) { for (Object name : interfaces) { for (VdsNetworkInterface tempInterface : vds.getInterfaces()) { if (tempInterface.getName().equals(name.toString())) { tempInterface.setBondName(iface.getName()); break; } } } } }
Source:
private Exceptions() { throw new AssertionError("No instances."); }

Target:
private Exceptions() { throw new IllegalStateException("No instances!"); }
Source:
public boolean isMatch(TreeWalkerAuditEvent event) { final int line = event.getLine(); boolean match = false; if (line >= firstLine && line <= lastLine) { final Matcher tagMatcher = tagCheckRegexp.matcher(event.getSourceName()); if (tagMatcher.find()) { if (tagMessageRegexp == null) { match = true; } else { final Matcher messageMatcher = tagMessageRegexp.matcher(event.getMessage()); match = messageMatcher.find(); } } else if (event.getModuleId() != null) { final Matcher idMatcher = tagCheckRegexp.matcher(event.getModuleId()); match = idMatcher.find(); } } return match; }

Target:
public boolean isMatch(TreeWalkerAuditEvent event) { return isInScopeOfSuppression(event) && (isCheckMatch(event) || isIdMatch(event)) && isMessageMatch(event); }
Source:
public Upstream<T> apply(Upstream<? extends T> upstream) throws Exception { return down -> { long start; if (circuitBreaker.tryAcquirePermission()) { start = System.nanoTime(); upstream.connect(new Downstream<T>() { @Override public void success(T value) { long durationInNanos = System.nanoTime() - start; circuitBreaker.onSuccess(durationInNanos); down.success(value); } @Override public void error(Throwable throwable) { long durationInNanos = System.nanoTime() - start; circuitBreaker.onError(durationInNanos, throwable); handleRecovery(down, throwable); } @Override public void complete() { down.complete(); } }); } else { Throwable t = new CallNotPermittedException(circuitBreaker); handleRecovery(down, t); } }; }

Target:
public Upstream<T> apply(Upstream<? extends T> upstream) throws Exception { return down -> { long start; if (circuitBreaker.tryAcquirePermission()) { start = System.nanoTime(); upstream.connect(new Downstream<T>() { @Override public void success(T value) { long durationInNanos = System.nanoTime() - start; circuitBreaker.onSuccess(durationInNanos); down.success(value); } @Override public void error(Throwable throwable) { long durationInNanos = System.nanoTime() - start; circuitBreaker.onError(durationInNanos, throwable); handleRecovery(down, throwable); } @Override public void complete() { circuitBreaker.releasePermission(); down.complete(); } }); } else { Throwable t = new CallNotPermittedException(circuitBreaker); handleRecovery(down, t); } }; }
Source:
public void setupExecutor() { if (m_executor.get()==null) { ListeningExecutorService es = CoreUtils.getListeningExecutorService( "ExportDataSource gen " + m_generation + " table " + m_tableName + " partition " + m_partitionId, 1); synchronized(m_executorLock) { if (m_queuedActions.size()>0) { for (RunnableWithES queuedR : m_queuedActions) { queuedR.setExecutorService(es); es.submit(queuedR); } m_queuedActions.clear(); } } if (!m_executor.compareAndSet(null, es)) { es.shutdown(); } } }

Target:
public void setupExecutor() { if (m_executor!=null) { return; } synchronized(m_executorLock) { if (m_executor==null) { ListeningExecutorService es = CoreUtils.getListeningExecutorService( "ExportDataSource gen " + m_generation + " table " + m_tableName + " partition " + m_partitionId, 1); if (m_queuedActions.size()>0) { for (RunnableWithES queuedR : m_queuedActions) { queuedR.setExecutorService(es); es.submit(queuedR); } m_queuedActions.clear(); } m_executor = es; } } }
Source:
private void writeList(DataOutputStream out, String[] list) throws IOException { if (list == null) { out.writeInt(0); } else { out.writeInt(list.length); for (String list1 : list) { writeStringOrNull(list1, out); } } }

Target:
private void writeList(DataOutputStream out, String[] list) throws IOException { if (list == null) { out.writeInt(0); } else { out.writeInt(list.length); for (String s : list) { writeStringOrNull(s, out); } } }
Source:
private void applyMcastAddition(MacLocation ml) { log.debug("Adding MCAST remote MAC to the VTEP: " + ml); try { List<McastMac> mcasts = vtepDataClient.listMcastMacsRemote(); for (McastMac mc : mcasts) { if (mc.mac.equals(ml.mac().toString())) { log.debug("MCAST remote MAC already in vtep"); return; } } } catch (VtepNotConnectedException e) { log.error("VTEP is not connected", e); return; } Status st = vtepDataClient.addMcastMacRemote(ml.logicalSwitchName(), ml.mac(), ml.vxlanTunnelEndpoint()); if (!st.isSuccess() ) { if (st.getCode().equals(StatusCode.CONFLICT)) { log.info("Conflict writing {}, not expected", ml); } else { throw new VxLanPeerSyncException("OVSDB error: " + st.getCode() + ", " + st.getDescription(), ml, st.getCode()); } } }

Target:
private void applyMcastAddition(MacLocation ml) { log.debug("Adding MCAST remote MAC to the VTEP: " + ml); List<McastMac> mcasts = null; try { mcasts = vtepDataClient.listMcastMacsRemote(); } catch (VtepNotConnectedException e) { log.error("VTEP is not connected", e); return; } for (McastMac mc : mcasts) { if (mc.mac.equals(ml.mac().toString())) { log.debug("MCAST remote MAC already in vtep"); return; } } Status st = vtepDataClient.addMcastMacRemote(ml.logicalSwitchName(), ml.mac(), ml.vxlanTunnelEndpoint()); if (!st.isSuccess() ) { if (st.getCode().equals(StatusCode.CONFLICT)) { log.info("Conflict writing {}, not expected", ml); } else { throw new VxLanPeerSyncException("OVSDB error: " + st.getCode() + ", " + st.getDescription(), ml, st.getCode()); } } }
Source:
public Message<?> toMessage(Object payload, MessageHeaders headers) { Assert.isInstanceOf(byte[].class, payload); try { Message<?> decoded = (Message<?>) this.codec.decode((byte[]) payload, messageClass); AbstractIntegrationMessageBuilder<?> builder = MutableMessageBuilder.fromMessage(decoded); if (headers != null) { builder.copyHeaders(headers); } return builder.build(); } catch (IOException e) { throw new MessagingException("Failed to decode", e); } }

Target:
public Message<?> toMessage(Object payload, MessageHeaders headers) { Assert.isInstanceOf(byte[].class, payload); try { Message<?> decoded = (Message<?>) this.codec.decode((byte[]) payload, messageClass); if (headers != null) { AbstractIntegrationMessageBuilder<?> builder = getMessageBuilderFactory().fromMessage(decoded); builder.copyHeaders(headers); return builder.build(); } else { return decoded; } } catch (IOException e) { throw new MessagingException("Failed to decode", e); } }
Source:
public static String convertToJson(Object value) { if (mapper.canSerialize(value.getClass())) { try { return mapper.writeValueAsString(value); } catch (IOException e) { logger.warn("Error while serializing " + value + " to JSON", e); return null; } } else { throw new IllegalArgumentException("Value of type " + value.getClass().getName() + " can not be serialized to JSON."); } }

Target:
public static String convertToJson(Object value) { Assert.notNull(value, "The object to convert must not be null."); if (mapper.canSerialize(value.getClass())) { try { return mapper.writeValueAsString(value); } catch (IOException e) { logger.warn("Error while serializing " + value + " to JSON", e); return null; } } else { throw new IllegalArgumentException("Value of type " + value.getClass().getName() + " can not be serialized to JSON."); } }
Source:
public static Migrator createVersionOneToVersionTwoMigrator(Context context, File databasePath, Migrator.Callback callback) { if (!databasePath.exists()) { return new Migrator() { @Override public void migrate() { } }; } SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(databasePath.getAbsolutePath(), null, 0); DatabaseWrapper database = new DatabaseWrapper(sqLiteDatabase); MigrationExtractor migrationExtractor = new MigrationExtractor(database); RoomDownloadsPersistence downloadsPersistence = RoomDownloadsPersistence.newInstance(context); InternalFilePersistence internalFilePersistence = new InternalFilePersistence(); internalFilePersistence.initialiseWith(context); return new VersionOneToVersionTwoMigrator(migrationExtractor, downloadsPersistence, internalFilePersistence, database, callback); }

Target:
public static Migrator createVersionOneToVersionTwoMigrator(Context context, File databasePath, Migrator.Callback callback) { if (!databasePath.exists()) { return Migrator.NO_OP; } SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(databasePath.getAbsolutePath(), null, 0); SqlDatabaseWrapper database = new SqlDatabaseWrapper(sqLiteDatabase); MigrationExtractor migrationExtractor = new MigrationExtractor(database); RoomDownloadsPersistence downloadsPersistence = RoomDownloadsPersistence.newInstance(context); InternalFilePersistence internalFilePersistence = new InternalFilePersistence(); internalFilePersistence.initialiseWith(context); return new VersionOneToVersionTwoMigrator(migrationExtractor, downloadsPersistence, internalFilePersistence, database, callback); }
Source:
public void shouldNotifyEventWhenCreateAnnotation() { try (CapturingEventListener listener = new CapturingEventListener(COMMENT_ADDED)) { Annotation annotation = createAnnotationAndAddSubscription("CommentAdded"); DocumentModel annotationDocumentModel = session.getDocument(new IdRef(annotation.getId())); DocumentModel annotationParentDocumentModel = session.getDocument( new IdRef((String) annotationDocumentModel.getPropertyValue(COMMENT_PARENT_ID))); transactionalFeature.nextTransaction(); Event expectedEvent = listener.streamCapturedEvents() .findFirst() .orElseThrow(() -> new AssertionError("Event wasn't fired")); checkDocumentEventContext(expectedEvent, annotationDocumentModel, annotationParentDocumentModel, annotatedDocumentModel); } }

Target:
public void shouldNotifyEventWhenCreateAnnotation() { try (CapturingEventListener listener = new CapturingEventListener(COMMENT_ADDED)) { Annotation annotation = createAnnotationAndAddSubscription(COMMENT_ADDED_NOTIFICATION); transactionalFeature.nextTransaction(); DocumentModel annotationDocumentModel = session.getDocument(new IdRef(annotation.getId())); DocumentModel annotationParentDocumentModel = session.getDocument( new IdRef((String) annotationDocumentModel.getPropertyValue(COMMENT_PARENT_ID))); Event expectedEvent = listener.streamCapturedEvents() .findFirst() .orElseThrow(() -> new AssertionError("Event wasn't fired")); checkDocumentEventContext(expectedEvent, annotationDocumentModel, annotationParentDocumentModel, annotatedDocumentModel); } }
Source:
public void testProcessScheduleOn1ColoWhileOtherColoIsDown() throws Exception { try { UA2Bundle.submitProcess(true); Util.shutDownService(cluster2.getProcessHelper()); Util.assertSucceeded(prism.getProcessHelper() .submitAndSchedule(URLS.SUBMIT_AND_SCHEDULE_URL, UA2Bundle.getProcessData())); AssertUtil.checkStatus(cluster1OC, ENTITY_TYPE.PROCESS, UA2Bundle, Job.Status.RUNNING); AssertUtil.checkNotStatus(cluster1OC, ENTITY_TYPE.PROCESS, UA1Bundle, Job.Status.RUNNING); } catch (Exception e) { e.printStackTrace(); throw new TestNGException(e.getMessage()); } finally { Util.restartService(cluster2.getProcessHelper()); } }

Target:
public void testProcessScheduleOn1ColoWhileOtherColoIsDown() throws Exception { try { bundles[1].submitProcess(true); Util.shutDownService(cluster2.getProcessHelper()); Util.assertSucceeded(prism.getProcessHelper() .submitAndSchedule(URLS.SUBMIT_AND_SCHEDULE_URL, bundles[1].getProcessData())); AssertUtil.checkStatus(cluster1OC, ENTITY_TYPE.PROCESS, bundles[1], Job.Status.RUNNING); AssertUtil.checkNotStatus(cluster1OC, ENTITY_TYPE.PROCESS, bundles[0], Job.Status.RUNNING); } catch (Exception e) { e.printStackTrace(); throw new TestNGException(e.getMessage()); } finally { Util.restartService(cluster2.getProcessHelper()); } }
Source:
public void lunsMismatchDeviceSize() { Guid pvID = Guid.newGuid(); Guid lunID = Guid.newGuid(); LUNs lunFromVG = new LUNs(); lunFromVG.setLUN_id(lunID.toString()); lunFromVG.setphysical_volume_id(pvID.toString()); lunFromVG.setDeviceSize(20); LUNs lunFromDB = new LUNs(); lunFromDB.setLUN_id(lunID.toString()); lunFromDB.setphysical_volume_id(pvID.toString()); lunFromDB.setDeviceSize(10); List<LUNs> lunsFromVgInfo = Collections.singletonList(lunFromVG); List<LUNs> lunsFromDb = Collections.singletonList(lunFromDB); boolean isMismatch = command.isLunsInfoMismatch(lunsFromVgInfo, lunsFromDb); assertTrue(isMismatch); }

Target:
public void lunsMismatchDeviceSize() { Guid pvID = Guid.newGuid(); Guid lunID = Guid.newGuid(); LUNs lunFromVG = new LUNs(); lunFromVG.setLUN_id(lunID.toString()); lunFromVG.setphysical_volume_id(pvID.toString()); lunFromVG.setDeviceSize(20); LUNs lunFromDB = new LUNs(); lunFromDB.setLUN_id(lunID.toString()); lunFromDB.setphysical_volume_id(pvID.toString()); lunFromDB.setDeviceSize(10); List<LUNs> lunsFromVgInfo = Collections.singletonList(lunFromVG); List<LUNs> lunsFromDb = Collections.singletonList(lunFromDB); assertTrue(command.isLunsInfoMismatch(lunsFromVgInfo, lunsFromDb)); }
Source:
public boolean move(String path, String target) { path = Paths.valid(path); target = Paths.valid(target); File file = Paths.toFile(baseDirectory, path); File dest = Paths.toFile(baseDirectory, target); if (!file.exists() && !dest.exists()) { return true; } if( !file.exists() ){ throw new IllegalStateException("Unable to find " + path + " to move to " + target); } try { dest.getParentFile().mkdirs(); return Files.move(file, dest); } catch (IOException e) { throw new IllegalStateException("Unable to move " + path + " to " + target, e); } }

Target:
public boolean move(String path, String target) { path = Paths.valid(path); target = Paths.valid(target); File file = Paths.toFile(baseDirectory, path); File dest = Paths.toFile(baseDirectory, target); if (!file.exists() && !dest.exists()) { return true; } try { dest.getParentFile().mkdirs(); return Files.move(file, dest); } catch (IOException e) { throw new IllegalStateException("Unable to move " + path + " to " + target, e); } }
Source:
protected void setUp() throws Exception { super.setUp(); ((MockSystemReader) SystemReader.getInstance()).setProperty( Constants.GIT_CEILING_DIRECTORIES_KEY, ResourcesPlugin .getWorkspace().getRoot().getLocation().toFile() .getAbsoluteFile().toString()); project = new TestProject(true); if (false) checkNotNested(); gitDir = new File(project.getProject().getWorkspace().getRoot() .getRawLocation().toFile(), ".git"); rmrf(gitDir); }

Target:
protected void setUp() throws Exception { super.setUp(); ((MockSystemReader) SystemReader.getInstance()).setProperty( Constants.GIT_CEILING_DIRECTORIES_KEY, ResourcesPlugin .getWorkspace().getRoot().getLocation().toFile() .getAbsoluteFile().toString()); project = new TestProject(true); checkNotNested(); gitDir = new File(project.getProject().getWorkspace().getRoot() .getRawLocation().toFile(), ".git"); rmrf(gitDir); }
Source:
private byte[] createNoteContent(CodeReviewCommit commit) throws UnsupportedEncodingException { try { ReviewNoteHeaderFormatter formatter = new ReviewNoteHeaderFormatter(); formatter.appendChangeId(commit.change.getId()); ResultSet<PatchSetApproval> approvals = schema.patchSetApprovals().byPatchSet(commit.patchsetId); PatchSetApproval submit = null; for (PatchSetApproval a : approvals) { if (ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { submit = a; } else { formatter.appendApproval( schema.approvalCategories().get(a.getCategoryId()), a.getValue(), schema.accounts().get(a.getAccountId())); } } formatter.appendBranch(schema.projects().get(commit.change.getProject()), commit.change.getDest()); formatter.appendSubmittedBy(schema.accounts().get(submit.getAccountId())); formatter.appendSubmittedOn(submit.getGranted()); return formatter.toString().getBytes("UTF-8"); } catch (OrmException e) { throw new RuntimeException(e); } }

Target:
private ObjectId createNoteContent(CodeReviewCommit commit) throws CodeReviewNoteCreationException, IOException { try { ReviewNoteHeaderFormatter formatter = new ReviewNoteHeaderFormatter(author.getTimeZone()); final List<String> idList = commit.getFooterLines(CHANGE_ID); if (idList.isEmpty()) formatter.appendChangeId(commit.change.getKey()); ResultSet<PatchSetApproval> approvals = schema.patchSetApprovals().byPatchSet(commit.patchsetId); PatchSetApproval submit = null; for (PatchSetApproval a : approvals) { if (ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { submit = a; } else { formatter.appendApproval( approvalTypes.getApprovalType(a.getCategoryId()).getCategory(), a.getValue(), accountCache.get(a.getAccountId()).getAccount()); } } formatter.appendBranch(commit.change.getProject().get(), commit.change.getDest()); formatter.appendSubmittedBy(accountCache.get(submit.getAccountId()).getAccount()); formatter.appendSubmittedOn(submit.getGranted()); return inserter.insert(Constants.OBJ_BLOB, formatter.toString().getBytes("UTF-8")); } catch (OrmException e) { throw new CodeReviewNoteCreationException(commit, e); } }
Source:
protected final static void setUp(String transport) { application = new SingleNodeApplication(); System.out.println(transport); application.run("--transport", transport); context = (AbstractApplicationContext) application.getContainerContext(); streamDefinitionRepository = context.getBean(StreamDefinitionRepository.class); streamRepository = context.getBean(StreamRepository.class); streamDeployer = application.getAdminContext().getBean(StreamDeployer.class); AbstractMessageChannel deployChannel = application.getAdminContext().getBean("deployChannel", AbstractMessageChannel.class); AbstractMessageChannel undeployChannel = application.getAdminContext().getBean("undeployChannel", AbstractMessageChannel.class); deployChannel.addInterceptor(new WireTap(tapChannel)); undeployChannel.addInterceptor(new WireTap(tapChannel)); context.addApplicationListener(moduleEventListener); }

Target:
protected final static void setUp(String transport) { application = new SingleNodeApplication(); application.run("--transport", transport); context = (AbstractApplicationContext) application.getContainerContext(); streamDefinitionRepository = context.getBean(StreamDefinitionRepository.class); streamRepository = context.getBean(StreamRepository.class); streamDeployer = application.getAdminContext().getBean(StreamDeployer.class); AbstractMessageChannel deployChannel = application.getAdminContext().getBean("deployChannel", AbstractMessageChannel.class); AbstractMessageChannel undeployChannel = application.getAdminContext().getBean("undeployChannel", AbstractMessageChannel.class); deployChannel.addInterceptor(new WireTap(tapChannel)); undeployChannel.addInterceptor(new WireTap(tapChannel)); context.addApplicationListener(moduleEventListener); }
Source:
protected DiskImage getImageInfoFromVdsm(final DiskImage targetImage) { try { VDSReturnValue ret = runVdsCommand( VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(targetImage.getStoragePoolId(), targetImage.getStorageIds().get(0), targetImage.getId(), targetImage.getImageId())); return (DiskImage) ret.getReturnValue(); } catch (EngineException e) { log.error("Failed to get info of volume '{0}' using GetImageInfo", targetImage.getImageId(), e); return null; } }

Target:
protected DiskImage getImageInfoFromVdsm(final DiskImage targetImage) { try { VDSReturnValue ret = runVdsCommand( VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(targetImage.getStoragePoolId(), targetImage.getStorageIds().get(0), targetImage.getId(), targetImage.getImageId())); return (DiskImage) ret.getReturnValue(); } catch (EngineException e) { log.warn("Failed to get info of volume '{0}' using GetImageInfo", targetImage.getImageId(), e); return null; } }
Source:
public void doAfterCompose(final T comp) throws Exception { if (comp.getPage() == null) { ((ComponentCtrl) comp).addCallback(ComponentCtrl.AFTER_PAGE_ATTACHED, new Callback() { public void call(Object data) { try { doAfterCompose(comp); } catch (Exception e) { throw UiException.Aide.wrap(e, e.getMessage()); } } }); return; } _binder.initAnnotatedBindings(); new AbstractAnnotatedMethodInvoker<AfterCompose>(AfterCompose.class, _afterComposeMethodCache) { protected boolean shouldLookupSuperclass(AfterCompose annotation) { return annotation.superclass(); } }.invokeMethod(_binder, getViewModelInitArgs(evalx, comp)); BinderKeeper keeper = BinderKeeper.getInstance(comp); if (keeper.isRootBinder(_binder)) { keeper.loadComponentForAllBinders(); } comp.setAuService(this); final AbstractAnnotatedMethodInvoker<HistoryPopState> historyPopStateInvoker = new AbstractAnnotatedMethodInvoker<HistoryPopState>(HistoryPopState.class, _historyPopStateMethodCache) { protected boolean shouldLookupSuperclass(HistoryPopState annotation) { return false; } }; if (historyPopStateInvoker.hasAnnotatedMethod(_binder)) { Page page = comp.getPage(); if (page != null) { page.addEventListener(Events.ON_HISTORY_POP_STATE, new EventListener<HistoryPopStateEvent>() { public void onEvent(HistoryPopStateEvent event) throws Exception { historyPopStateInvoker.invokeMethod(getBinder(), null, event, true); } }); } } }

Target:
public void doAfterCompose(final T comp) throws Exception { if (comp.getPage() == null) { ((ComponentCtrl) comp).addCallback(ComponentCtrl.AFTER_PAGE_ATTACHED, new Callback() { public void call(Object data) { try { doAfterCompose(comp); } catch (Exception e) { throw UiException.Aide.wrap(e); } } }); return; } _binder.initAnnotatedBindings(); new AbstractAnnotatedMethodInvoker<AfterCompose>(AfterCompose.class, _afterComposeMethodCache) { protected boolean shouldLookupSuperclass(AfterCompose annotation) { return annotation.superclass(); } }.invokeMethod(_binder, getViewModelInitArgs(evalx, comp)); BinderKeeper keeper = BinderKeeper.getInstance(comp); if (keeper.isRootBinder(_binder)) { keeper.loadComponentForAllBinders(); } comp.setAuService(this); final AbstractAnnotatedMethodInvoker<HistoryPopState> historyPopStateInvoker = new AbstractAnnotatedMethodInvoker<HistoryPopState>(HistoryPopState.class, _historyPopStateMethodCache) { protected boolean shouldLookupSuperclass(HistoryPopState annotation) { return false; } }; if (historyPopStateInvoker.hasAnnotatedMethod(_binder)) { Page page = comp.getPage(); if (page != null) { page.addEventListener(Events.ON_HISTORY_POP_STATE, new EventListener<HistoryPopStateEvent>() { public void onEvent(HistoryPopStateEvent event) throws Exception { historyPopStateInvoker.invokeMethod(getBinder(), null, event, true); } }); } } }
Source:
private static boolean isLayout(TagNode node) { String role = node.getAttribute("ROLE"); return role != null && ("PRESENTATION".equalsIgnoreCase(role) || "NONE".equalsIgnoreCase(role)); }

Target:
private static boolean isLayout(TagNode node) { String role = node.getAttribute("ROLE"); return "PRESENTATION".equalsIgnoreCase(role) || "NONE".equalsIgnoreCase(role); }
Source:
public static Properties loadProperties(InputStream resource) { try ( Reader is = new InputStreamReader(resource, Charset.forName("UTF-8")); ) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException ioe) { throw new RuntimeException(ioe); } }

Target:
private static Properties loadProperties(InputStream resource) { try ( Reader is = new InputStreamReader(resource, Charset.forName("UTF-8")); ) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException ioe) { throw new RuntimeException(ioe); } }
Source:
public void add(AddParams params) throws GitException { AddCommand addCommand = getGit().add().setUpdate(params.isUpdate()); List<String> filePatterns = params.getFilePattern(); if (filePatterns.isEmpty()) { filePatterns = AddRequest.DEFAULT_PATTERN; } filePatterns.forEach(addCommand::addFilepattern); try { addCommand.call(); Set<String> deletedFiles = getGit().status().call().getMissing(); if (!deletedFiles.isEmpty()) { RmCommand rmCommand = getGit().rm(); if (filePatterns.contains(".")) { deletedFiles.forEach(rmCommand::addFilepattern); } else { filePatterns.forEach(filePattern -> deletedFiles.stream() .filter(deletedFile -> deletedFile.startsWith(filePattern)) .forEach(rmCommand::addFilepattern)); } rmCommand.call(); } } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } }

Target:
public void add(AddParams params) throws GitException { AddCommand addCommand = getGit().add().setUpdate(params.isUpdate()); List<String> filePatterns = params.getFilePattern(); if (filePatterns.isEmpty()) { filePatterns = AddRequest.DEFAULT_PATTERN; } filePatterns.forEach(addCommand::addFilepattern); try { addCommand.call(); addDeletedFilesToIndex(filePatterns); } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } }
Source:
public static void loadBundledModules(ServletContext servletContext) { final org.slf4j.Logger log = LoggerFactory.getLogger(Listener.class); String path = servletContext.getRealPath(""); path += File.separator + "WEB-INF" + File.separator + "bundledModules"; File folder = new File(path); if (!folder.exists()) { log.warn("Bundled module folder doesn't exist: " + folder.getAbsolutePath()); return; } if (!folder.isDirectory()) { log.warn("Bundled module folder isn't really a directory: " + folder.getAbsolutePath()); return; } if (folder.listFiles() != null) { for (File f : Objects.requireNonNull(folder.listFiles())) { if (!f.getName().startsWith(".")) { try { Module mod = ModuleFactory.loadModule(f); log.debug("Loaded bundled module: " + mod + " successfully"); } catch (Exception e) { log.warn("Error while trying to load bundled module " + f.getName() + "", e); } } } } }

Target:
public static void loadBundledModules(ServletContext servletContext) { final org.slf4j.Logger log = LoggerFactory.getLogger(Listener.class); String path = servletContext.getRealPath(""); path += File.separator + "WEB-INF" + File.separator + "bundledModules"; File folder = new File(path); if (!folder.exists()) { log.warn("Bundled module folder doesn't exist: " + folder.getAbsolutePath()); return; } if (!folder.isDirectory()) { log.warn("Bundled module folder isn't really a directory: " + folder.getAbsolutePath()); return; } if (folder.listFiles() != null) { for (File f : folder.listFiles()) { if (!f.getName().startsWith(".")) { try { Module mod = ModuleFactory.loadModule(f); log.debug("Loaded bundled module: " + mod + " successfully"); } catch (Exception e) { log.warn("Error while trying to load bundled module " + f.getName() + "", e); } } } } }
Source:
public Hardware apply(VMHardware from) { final HardwareBuilder builder = new HardwareBuilder() .name(from.name) .id(from.name) .processors(ImmutableList.of(new Processor(from.numberOfCores, 2))) .ram(from.memoryInMB) .location(from.globallyAvailable ? null : FluentIterable.from(locations.get()) .firstMatch(LocationPredicates.idEquals(from.location)) .orNull()); if (from.resourceDiskSizeInMB != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.resourceDiskSizeInMB)) .type(Volume.Type.LOCAL) .build()); } if (from.osDiskSizeInMB != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.osDiskSizeInMB)) .type(Volume.Type.LOCAL) .build()); } ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("maxDataDiskCount", String.valueOf(from.maxDataDiskCount)); builder.userMetadata(metadata.build()); return builder.build(); }

Target:
public Hardware apply(VMHardware from) { final HardwareBuilder builder = new HardwareBuilder() .name(from.name) .id(from.name) .processors(ImmutableList.of(new Processor(from.numberOfCores, 2))) .ram(from.memoryInMB) .location(from.globallyAvailable ? null : FluentIterable.from(locations.get()) .firstMatch(LocationPredicates.idEquals(from.location)) .get()); if (from.resourceDiskSizeInMB != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.resourceDiskSizeInMB)) .type(Volume.Type.LOCAL) .build()); } if (from.osDiskSizeInMB != null) { builder.volume(new VolumeBuilder() .size(Float.valueOf(from.osDiskSizeInMB)) .type(Volume.Type.LOCAL) .build()); } ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder(); metadata.put("maxDataDiskCount", String.valueOf(from.maxDataDiskCount)); builder.userMetadata(metadata.build()); return builder.build(); }