auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void pickFreePort() { for (Iterator<Integer> iter = DEFAULT_HTTP_PORT_RANGE.iterator(); iter.hasNext();) { Integer port = iter.next(); if (Networking.isPortAvailable(port)) { httpPort = port; return; } } fail("someone is already listening on ports "+DEFAULT_HTTP_PORT_RANGE+"; tests assume that port is free on localhost"); }

Target:
public void pickFreePort() { for (Iterator<Integer> iter = DEFAULT_PORT_RANGE.iterator(); iter.hasNext();) { Integer port = iter.next(); if (Networking.isPortAvailable(port)) { httpPort = port; return; } } fail("someone is already listening on ports "+DEFAULT_PORT_RANGE+"; tests assume that port is free on localhost"); }
Source:
public void register(Set<Macro> macros) { for (Macro macro : macros) { final String name = macro.getName(); if (!this.macros.containsKey(name)) { this.macros.put(name, macro); } } }

Target:
public void register(Set<Macro> macros) { for (Macro macro : macros) { final String name = macro.getName(); if (this.macros.containsKey(name)) { Log.warn(MacroRegistryImpl.class, "Command macro '" + name + "' is already registered."); } else { this.macros.put(name, macro); } } }
Source:
public long saveProject(Project project) throws IOException { if (projectStore != null) { ValidationResult shortNameValidation = namingScheme.validateProjectShortName(project.getShortName()); if (!shortNameValidation.isValid()) { throw new IOException("Cannot save project - invalid shortName: " + shortNameValidation.getMessage()); } if (project.getId() == AbstractProject.UNSAVED_ID) { project.setName(generateTemporaryName()); projectStore.save(project); try { project.setName(namingScheme.generateNameFor(project)); } catch (MisoNamingException e) { throw new IOException("Cannot save Project - issue with naming scheme", e); } } LimsUtils.validateNameOrThrow(project, namingScheme); return projectStore.save(project); } else { throw new IOException("No projectStore available. Check that it has been declared in the Spring config."); } }

Target:
public long saveProject(Project project) throws IOException { if (projectStore != null) { ValidationResult shortNameValidation = namingScheme.validateProjectShortName(project.getShortName()); if (!shortNameValidation.isValid()) { throw new IOException("Cannot save project - invalid shortName: " + shortNameValidation.getMessage()); } if (project.getId() == AbstractProject.UNSAVED_ID) { project.setName(generateTemporaryName()); projectStore.save(project); try { project.setName(namingScheme.generateNameFor(project)); } catch (MisoNamingException e) { throw new IOException("Cannot save Project - issue with naming scheme", e); } LimsUtils.validateNameOrThrow(project, namingScheme); } else { Project original = projectStore.get(project.getId()); original.setAlias(project.getAlias()); original.setDescription(project.getDescription()); original.setIssueKeys(project.getIssueKeys()); original.setLastUpdated(project.getLastUpdated()); original.setProgress(project.getProgress()); original.setReferenceGenome(referenceGenomeDao.getReferenceGenome(project.getReferenceGenome().getId())); original.setShortName(project.getShortName()); for (ProjectOverview po : project.getOverviews()) { if (po.getId() == ProjectOverview.UNSAVED_ID) { original.getOverviews().add(po); } } project = original; } return projectStore.save(project); } else { throw new IOException("No projectStore available. Check that it has been declared in the Spring config."); } }
Source:
private void makeEmailStateConsistent(FeedbackSessionAttributes oldSession, FeedbackSessionAttributes newSession) { if (oldSession.isSentOpenEmail()) { newSession.setSentOpenEmail(newSession.isOpened()); } if (oldSession.isSentClosedEmail()) { newSession.setSentClosedEmail(newSession.isClosed()); newSession.setSentClosingEmail( newSession.isClosed() || !newSession.isClosingWithinTimeLimit(SystemParams.NUMBER_OF_HOURS_BEFORE_CLOSING_ALERT)); } if (oldSession.isSentPublishedEmail()) { newSession.setSentPublishedEmail(newSession.isPublished()); } }

Target:
private void makeEmailStateConsistent(FeedbackSessionAttributes oldSession, FeedbackSessionAttributes newSession) { if (oldSession.isSentOpenEmail()) { newSession.setSentOpenEmail(newSession.isOpened()); } if (oldSession.isSentClosedEmail()) { newSession.setSentClosedEmail(newSession.isClosed()); newSession.setSentClosingEmail( newSession.isClosed() || !newSession.isClosedAfter(SystemParams.NUMBER_OF_HOURS_BEFORE_CLOSING_ALERT)); } if (oldSession.isSentPublishedEmail()) { newSession.setSentPublishedEmail(newSession.isPublished()); } }
Source:
private void updateGeoRepStatus(GlusterVolumeEntity volume, GlusterGeoRepSession session) { if (!areAllBricksActiveInVolume(volume)) { log.info("Not all bricks are up for this volume '{}' ", volume.getName()); throw new EngineException(EngineError.GlusterVolumeGeoRepSyncFailed, "Not all bricks are up for this volume"); } List<Set<GeoRepSessionStatus>> list = new ArrayList<>(); int replicaCount = volume.getReplicaCount() == 0 ? 1 : volume.getReplicaCount(); for (int i = 0; i < volume.getBricks().size(); i = i + replicaCount) { Set<GeoRepSessionStatus> subVolumeStatusSet = new HashSet<>(); int j = 0; while (j < replicaCount) { Guid brickId = volume.getBricks().get(i + j).getId(); subVolumeStatusSet.add(getStatusForBrickFromSession(session, brickId)); j++; } list.add(subVolumeStatusSet); } session.setStatus(GeoRepSessionStatus.ACTIVE); for (Set<GeoRepSessionStatus> subVolumeStatusValues : list) { if (subVolumeStatusValues.contains(GeoRepSessionStatus.ACTIVE)) { continue; } else if (subVolumeStatusValues.contains(GeoRepSessionStatus.FAULTY)) { session.setStatus(GeoRepSessionStatus.FAULTY); return; } if (ArrayUtils.contains(overridableStatuses, session.getStatus())) { if (subVolumeStatusValues.size() == 1) { session.setStatus((GeoRepSessionStatus) subVolumeStatusValues.toArray()[0]); } else { log.info("Multiple status values found in volume '{}'", session.getMasterVolumeName()); } } } }

Target:
private void updateGeoRepStatus(GlusterVolumeEntity volume, GlusterGeoRepSession session) { List<Set<GeoRepSessionStatus>> list = new ArrayList<>(); int replicaCount = volume.getReplicaCount() == 0 ? 1 : volume.getReplicaCount(); if (replicaCount > volume.getBricks().size()) { throw new EngineException(EngineError.GlusterVolumeGeoRepSyncFailed, "Not all bricks are up for this volume"); } for (int i = 0; i < volume.getBricks().size(); i = i + replicaCount) { Set<GeoRepSessionStatus> subVolumeStatusSet = new HashSet<>(); int j = 0; while (j < replicaCount) { Guid brickId = volume.getBricks().get(i + j).getId(); subVolumeStatusSet.add(getStatusForBrickFromSession(session, brickId)); j++; } list.add(subVolumeStatusSet); } session.setStatus(GeoRepSessionStatus.ACTIVE); for (Set<GeoRepSessionStatus> subVolumeStatusValues : list) { if (subVolumeStatusValues.contains(GeoRepSessionStatus.ACTIVE)) { continue; } else if (subVolumeStatusValues.contains(GeoRepSessionStatus.FAULTY)) { session.setStatus(GeoRepSessionStatus.FAULTY); return; } if (ArrayUtils.contains(overridableStatuses, session.getStatus())) { if (subVolumeStatusValues.size() == 1) { session.setStatus((GeoRepSessionStatus) subVolumeStatusValues.toArray()[0]); } else { log.info("Multiple status values found in volume '{}'", session.getMasterVolumeName()); } } } }
Source:
public boolean createNewFile(File lock) throws IOException { if (!lock.createNewFile()) { return false; } if (supportsAtomicCreateNewFile() || !supportsUnixView) { return true; } Path lockPath = lock.toPath(); Path link = Files.createLink(Paths.get(lock.getAbsolutePath() + ".lnk"), lockPath); try { Integer nlink = (Integer) (Files.getAttribute(lockPath, "unix:nlink")); if (nlink == 2) { return true; } else { LOG.warn("nlink of link to lock file {0} was not 2 but {1}", lock.getPath(), nlink); } return (nlink == 2); } catch (UnsupportedOperationException e) { supportsUnixView = false; return true; } finally { Files.delete(link); } }

Target:
public boolean createNewFile(File lock) throws IOException { if (!lock.createNewFile()) { return false; } if (supportsAtomicCreateNewFile() || !supportsUnixView) { return true; } Path lockPath = lock.toPath(); Path link = Files.createLink(Paths.get(lock.getAbsolutePath() + ".lnk"), lockPath); try { Integer nlink = (Integer) (Files.getAttribute(lockPath, "unix:nlink")); if (nlink != 2) { LOG.warn("nlink of link to lock file {0} was not 2 but {1}", lock.getPath(), nlink); return false; } return true; } catch (UnsupportedOperationException e) { supportsUnixView = false; return true; } finally { Files.delete(link); } }
Source:
protected StorageDomain deprecatedPopulate(StorageDomain model, storage_domains entity) { if (StorageDomainSharedStatus.Unattached.equals(entity.getstorage_domain_shared_status())) { model.setStatus(StatusUtils.create(StorageDomainStatus.UNATTACHED)); } else { model.setStatus(null); } return model; }

Target:
protected StorageDomain deprecatedPopulate(StorageDomain model, storage_domains entity) { if (StorageDomainSharedStatus.Unattached.equals(entity.getstorage_domain_shared_status())) { model.setStatus(StatusUtils.create(StorageDomainStatus.UNATTACHED)); } else { model.setStatus(null); } return super.deprecatedPopulate(model, entity); }
Source:
public void testIsMultipart() throws Exception { Assert.assertEquals(false, MultipartFormDataParser.isMultipart(null)); Assert.assertEquals(false, MultipartFormDataParser.isMultipart("blah")); Assert.assertEquals(true, MultipartFormDataParser.isMultipart("multipart/form-data")); Assert.assertEquals(true, MultipartFormDataParser.isMultipart("multipart/form-data;")); Assert.assertEquals(true, MultipartFormDataParser.isMultipart("multipart/form-data; boundary=----WebKitFormBoundary8OOwv1Xp4c5XkBmD")); }

Target:
public void testIsMultipart() throws Exception { Assert.assertFalse("Wrongly identified \"multipart/form-data\"", MultipartFormDataParser.isMultiPartForm(null)); Assert.assertFalse("Wrongly identified \"multipart/form-data\"", MultipartFormDataParser.isMultiPartForm("blah")); Assert.assertTrue("Failed to identify \"multipart/form-data\"", MultipartFormDataParser.isMultiPartForm("multipart/form-data")); Assert.assertTrue("Failed to identify \"multipart/form-data\"", MultipartFormDataParser.isMultiPartForm("multipart/form-data;")); Assert.assertTrue("Failed to identify \"multipart/form-data\"", MultipartFormDataParser.isMultiPartForm("multipart/form-data; boundary=----WebKitFormBoundary8OOwv1Xp4c5XkBmD")); }
Source:
private static void checkRx() { if (!Utils.hasRxJavaOnClasspath()) { throw new NullPointerException("RxJava is not on classpath, " + "make sure that you have it in your dependencies"); } }

Target:
private static void checkRx() { if (!Utils.hasRxJavaOnClasspath()) { throw new NoClassDefFoundError("RxJava is not on classpath, " + "make sure that you have it in your dependencies"); } }
Source:
public VXQueryIndexingOperatorDescriptor(IOperatorDescriptorRegistry spec, VXQueryIndexingDataSource ds, RecordDescriptor rDesc) { super(spec, 1, 1); this.functionCall = ds.getFunctionCall(); collectionPartitions = ds.getPartitions(); dataSourceId = (short) ds.getDataSourceId(); totalDataSources = (short) ds.getTotalDataSources(); recordDescriptors[0] = rDesc; childSeq = ds.getChildSeq(); indexSeq=ds.getIndexSeq(); }

Target:
public VXQueryIndexingOperatorDescriptor(IOperatorDescriptorRegistry spec, VXQueryIndexingDataSource ds, RecordDescriptor rDesc) { super(spec, 1, 1); this.functionCall = ds.getFunctionCall(); collectionPartitions = ds.getPartitions(); dataSourceId = (short) ds.getDataSourceId(); totalDataSources = (short) ds.getTotalDataSources(); recordDescriptors[0] = rDesc; childSeq = ds.getChildSeq(); indexChildSeq = ds.getIndexChildSeq(); indexAttsSeq = ds.getIndexAttsSeq(); indexSeq = ds.getIndexValueSeq(); }
Source:
private static void logGcConfiguration(Project.NameKey projectName, Repository repo, boolean aggressive) { StringBuilder b = new StringBuilder(); Config cfg = repo.getConfig(); b.append("gc.aggressive="); b.append(aggressive); b.append("; "); b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION, null)); for (String subsection : cfg.getSubsections(ConfigConstants.CONFIG_GC_SECTION)) { b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION, subsection)); } if (b.length() == 0) { b.append("no set"); } logGcInfo(projectName, "gc config: " + b.toString()); logGcInfo(projectName, "pack config: " + (new PackConfig(repo)).toString()); }

Target:
private static void logGcConfiguration(Project.NameKey projectName, Repository repo, boolean aggressive) { StringBuilder b = new StringBuilder(); Config cfg = repo.getConfig(); b.append("gc.aggressive=").append(aggressive).append("; "); b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION, null)); for (String subsection : cfg.getSubsections(ConfigConstants.CONFIG_GC_SECTION)) { b.append(formatConfigValues(cfg, ConfigConstants.CONFIG_GC_SECTION, subsection)); } if (b.length() == 0) { b.append("no set"); } logGcInfo(projectName, "gc config: " + b.toString()); logGcInfo(projectName, "pack config: " + (new PackConfig(repo)).toString()); }
Source:
public static boolean isJetpackUser(SiteStore siteStore) { return siteStore.getSitesAccessedViaWPComRestCount() - siteStore.getWPComSitesCount() > 0; }

Target:
static boolean isJetpackUser(SiteStore siteStore) { return siteStore.getSitesAccessedViaWPComRestCount() - siteStore.getWPComSitesCount() > 0; }
Source:
public InputColumn<?>[] getInputColumns(InputColumn<?>[] allInputColumns) { if (_inputColumns == null) { _inputColumns = new InputColumn[_inputColumnNames.length]; for (int i = 0; i < _inputColumnNames.length; i++) { boolean found = false; final String name = _inputColumnNames[i]; for (int j = 0; j < allInputColumns.length; j++) { InputColumn<?> inputColumn = allInputColumns[j]; if (name.equals(inputColumn.getName())) { _inputColumns[i] = inputColumn; found = true; } } if (!found) { for (int j = 0; j < allInputColumns.length; j++) { InputColumn<?> inputColumn = allInputColumns[j]; if (name.trim().equalsIgnoreCase(inputColumn.getName().trim())) { _inputColumns[i] = inputColumn; found = true; } } } if (!found) { List<String> names = CollectionUtils.map(allInputColumns, new HasNameMapper()); throw new IllegalStateException("Column '" + name + "' not found. Available columns: " + names); } } } return _inputColumns; }

Target:
public InputColumn<?>[] getInputColumns(InputColumn<?>[] allInputColumns) { if (_inputColumns == null) { _inputColumns = new InputColumn[_inputColumnNames.length]; for (int i = 0; i < _inputColumnNames.length; i++) { boolean found = false; final String name = _inputColumnNames[i]; for (int j = 0; j < allInputColumns.length; j++) { final InputColumn<?> inputColumn = allInputColumns[j]; if (name.equals(inputColumn.getName())) { _inputColumns[i] = inputColumn; found = true; } } if (!found) { for (int j = 0; j < allInputColumns.length; j++) { final InputColumn<?> inputColumn = allInputColumns[j]; if (name.trim().equalsIgnoreCase(inputColumn.getName().trim())) { _inputColumns[i] = inputColumn; found = true; } } } if (!found) { final List<String> names = CollectionUtils.map(allInputColumns, new HasNameMapper()); throw new IllegalStateException("Column '" + name + "' not found. Available columns: " + names); } } } return _inputColumns; }
Source:
public String dump() { List<Map.Entry<String, Pair<Long, Long>>> list = new ArrayList<>(this.ruleAttempts.entrySet()); Collections.sort(list, (left, right) -> right.getValue().left.compareTo(left.getValue().left)); StringBuilder sb = new StringBuilder(); sb.append(String .format(Locale.ROOT, "%n%-60s%20s%20s%n", "Rules", "Attempts", "Time (us)")); for (Map.Entry<String, Pair<Long, Long>> entry : list) { sb.append( String.format(Locale.ROOT, "%-60s%20s%20s%n", entry.getKey(), NumberFormat.getNumberInstance(Locale.US).format(entry.getValue().left), NumberFormat.getNumberInstance(Locale.US).format(entry.getValue().right))); } return sb.toString(); }

Target:
public String dump() { List<Map.Entry<String, Pair<Long, Long>>> list = new ArrayList<>(this.ruleAttempts.entrySet()); Collections.sort(list, (left, right) -> { int res = right.getValue().left.compareTo(left.getValue().left); if (res == 0) { res = right.getValue().right.compareTo(left.getValue().right); } if (res == 0) { res = left.getKey().compareTo(right.getKey()); } return res; }); StringBuilder sb = new StringBuilder(); sb.append(String .format(Locale.ROOT, "%n%-60s%20s%20s%n", "Rules", "Attempts", "Time (us)")); NumberFormat usFormat = NumberFormat.getNumberInstance(Locale.US); for (Map.Entry<String, Pair<Long, Long>> entry : list) { sb.append( String.format(Locale.ROOT, "%-60s%20s%20s%n", entry.getKey(), usFormat.format(entry.getValue().left), usFormat.format(entry.getValue().right))); } return sb.toString(); }
Source:
private void updateUI(int orientation) { if (orientation == Configuration.ORIENTATION_LANDSCAPE) { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.GONE); } else { if (transcriptAdapter == null) { messageContainer.setVisibility(View.VISIBLE); transcriptListView.setVisibility(View.GONE); initTranscriptListView(); } else { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.VISIBLE); transcriptListLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { transcriptListView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { transcriptListView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } final float transcriptRowHeight = getResources().getDimension(R.dimen.transcript_row_height); final float listviewHeight = transcriptListView.getHeight(); topOffset = (listviewHeight / 2) - (transcriptRowHeight / 2); } }; transcriptListView.getViewTreeObserver().addOnGlobalLayoutListener(transcriptListLayoutListener); } } }

Target:
private void updateUI(int orientation) { if (orientation == Configuration.ORIENTATION_LANDSCAPE) { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.GONE); } else { if (transcriptAdapter == null) { messageContainer.setVisibility(View.VISIBLE); transcriptListView.setVisibility(View.GONE); initTranscriptListView(); } else { messageContainer.setVisibility(View.GONE); transcriptListView.setVisibility(View.VISIBLE); transcriptListLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { transcriptListView.getViewTreeObserver().removeOnGlobalLayoutListener(this); final float transcriptRowHeight = getResources().getDimension(R.dimen.transcript_row_height); final float listviewHeight = transcriptListView.getHeight(); topOffset = (listviewHeight / 2) - (transcriptRowHeight / 2); } }; transcriptListView.getViewTreeObserver().addOnGlobalLayoutListener(transcriptListLayoutListener); } } }
Source:
public MutableBoundedValue<Integer> fireTicks() { return new SpongeBoundedValue<Integer>(Keys.FIRE_TICKS, this.fireTicks, intComparator(), 0, this.fireTicks); }

Target:
public MutableBoundedValue<Integer> fireTicks() { return new SpongeBoundedValue<Integer>(Keys.FIRE_TICKS, this.fireTicks, intComparator(), 0, Integer.MAX_VALUE); }
Source:
public void removeObserver( RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> observer) { if (observer != null) { RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> remoteEmfObserver = observer; if (remoteEmfObserver.getConsumer() == this) { remoteEmfObserver.internalSetConsumer(null); } } remoteEmfObservers.remove(observer); release(); }

Target:
public void removeObserver( RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> observer) { if (observer != null) { RemoteEmfObserver<EParentObjectType, EObjectType, LocalKeyType, ObjectCurrentType> remoteEmfObserver = observer; if (remoteEmfObserver.getConsumer() == this) { remoteEmfObserver.internalSetConsumer(null); } remoteEmfObservers.remove(observer); } release(); }
Source:
public void defineStream(StreamDefinition streamDefinition) { DefinitionParserHelper.validateDefinition(streamDefinition, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap); streamDefinitionMap.put(streamDefinition.getId(), streamDefinition); DefinitionParserHelper.addStreamJunction(streamDefinition, streamJunctionMap, executionPlanContext); DefinitionParserHelper.addEventSource(streamDefinition, eventSourceMap, executionPlanContext); DefinitionParserHelper.addEventSink(streamDefinition, eventSinkMap, executionPlanContext); }

Target:
public void defineStream(StreamDefinition streamDefinition) { DefinitionParserHelper.validateDefinition(streamDefinition, streamDefinitionMap, tableDefinitionMap, windowDefinitionMap); AbstractDefinition currentDefinition = streamDefinitionMap .putIfAbsent(streamDefinition.getId(), streamDefinition); if (currentDefinition != null) { streamDefinition = (StreamDefinition) currentDefinition; } DefinitionParserHelper.addStreamJunction(streamDefinition, streamJunctionMap, executionPlanContext); DefinitionParserHelper.addEventSource(streamDefinition, eventSourceMap, executionPlanContext); DefinitionParserHelper.addEventSink(streamDefinition, eventSinkMap, executionPlanContext); }
Source:
public Object execute(Map<String, ?> lookupMap, QueryParams queryParams) { List<Object> args = getLookupArgs(lookupMap); List<Class> argTypes = buildArgTypes(); if (queryParams != null) { args.add(queryParams); argTypes.add(QueryParams.class); } try { return MethodUtils.invokeMethod(dataService, lookup.getMethodName(), args.toArray(new Object[args.size()]), argTypes.toArray(new Class[argTypes.size()])); } catch (NoSuchMethodException | IllegalAccessException e) { throw new LookupExecutorException("Unable to execute lookup " + lookup.getLookupName(), e); } catch (InvocationTargetException e) { throw new LookupExecutorException("Unable to execute lookup " + lookup.getLookupName() + ". " + e.getTargetException().getMessage() + ".", e); } }

Target:
public Object execute(Map<String, ?> lookupMap, QueryParams queryParams) { List<Object> args = getLookupArgs(lookupMap); List<Class> argTypes = buildArgTypes(); String lookupExceptionMessage = "Unable to execute lookup "; String lookupExceptionMessageKey = "mds.error.lookupExecError"; if (queryParams != null) { args.add(queryParams); argTypes.add(QueryParams.class); } try { return MethodUtils.invokeMethod(dataService, lookup.getMethodName(), args.toArray(new Object[args.size()]), argTypes.toArray(new Class[argTypes.size()])); } catch (NoSuchMethodException | IllegalAccessException e) { throw new LookupExecutorException(lookupExceptionMessage + lookup.getLookupName() + ".", e, null); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof JDOUserException) { JDOUserException userException = (JDOUserException) e.getTargetException(); lookupExceptionMessageKey = "mds.error.lookupExecUserError"; for (Throwable exception : userException.getNestedExceptions()) { if (exception instanceof QueryNotUniqueException) { lookupExceptionMessageKey = "mds.error.lookupExecNotUniqueError"; } } } throw new LookupExecutorException(lookupExceptionMessage + lookup.getLookupName() + ".", e, lookupExceptionMessageKey); } }
Source:
private void execute(Ignite node, BiFunction<IgniteEvents, String, UUID> func, boolean isForbiddenCase) { final String cacheName = "test_cache_" + INDEX.getAndIncrement(); grid(SRV).createCache(new CacheConfiguration<>(cacheName).setCacheMode(CacheMode.REPLICATED)); IgniteEvents evts = node.events(node.cluster().forNodeId(grid(SRV).localNode().id())); UUID id = func.apply(evts, cacheName); try { GridTestUtils.RunnableX r = () -> { error = null; latch = new CountDownLatch(1); grid(SRV).cache(cacheName).put("key", "value"); latch.await(10, TimeUnit.SECONDS); if (error != null) throw error; }; if (isForbiddenCase) runForbiddenOperation(r, AccessControlException.class); else runOperation(r); } finally { evts.stopRemoteListen(id); } }

Target:
private void execute(Ignite node, BiFunction<IgniteEvents, String, UUID> func, boolean isForbiddenCase) { final String cacheName = "test_cache_" + INDEX.getAndIncrement(); grid(SRV).createCache(new CacheConfiguration<>(cacheName).setCacheMode(CacheMode.REPLICATED)); IgniteEvents evts = node.events(node.cluster().forNodeId(grid(SRV).localNode().id())); UUID id = func.apply(evts, cacheName); try { GridTestUtils.RunnableX r = () -> { error = null; latch = new CountDownLatch(1); grid(SRV).cache(cacheName).put("key", "value"); latch.await(10, TimeUnit.SECONDS); if (error != null) throw error; }; if (isForbiddenCase) runForbiddenOperation(r, AccessControlException.class); else runOperation(r); assertEquals("value", grid(SRV).cache(cacheName).get("key")); } finally { evts.stopRemoteListen(id); } }
Source:
public void shouldDoNothingOnWriteLineIfAllSubConsumersAreClosed() throws Exception { final String message = "Test line"; for (int i = 0; i < subConsumers.length; i++) { LineConsumer closedConsumer = mock(LineConsumer.class); doThrow(ConsumerAlreadyClosedException.class).when(closedConsumer).writeLine(anyString()); subConsumers[i] = closedConsumer; } compositeLineConsumer = new CompositeLineConsumer(subConsumers); compositeLineConsumer.writeLine("Error"); compositeLineConsumer.writeLine(message); for (LineConsumer subConsumer : subConsumers) { verify(subConsumer, never()).writeLine(eq(message)); } }

Target:
public void shouldDoNothingOnWriteLineIfAllSubConsumersAreClosed() throws Exception { final String message = "Test line"; LineConsumer[] closedConsumers = subConsumers; for (LineConsumer consumer : closedConsumers) { doThrow(ConsumerAlreadyClosedException.class).when(consumer).writeLine(anyString()); } compositeLineConsumer = new CompositeLineConsumer(closedConsumers); compositeLineConsumer.writeLine("Error"); compositeLineConsumer.writeLine(message); for (LineConsumer subConsumer : closedConsumers) { verify(subConsumer, never()).writeLine(eq(message)); } }
Source:
public static void main(String[] args) { ServerBuilder sb = new ServerBuilder(); sb.http(8080) .annotatedService("/", new HelloService()) .annotatedService("/", new PostgresDbService()) .annotatedService("/", new PostgresFortunesService()) .decorator((delegate, ctx, req) -> { ctx.addAdditionalResponseHeader(HttpHeaderNames.SERVER, "armeria"); ctx.addAdditionalResponseHeader(HttpHeaderNames.DATE, DateTimeFormatter.RFC_1123_DATE_TIME.format( ZonedDateTime.now(ZoneOffset.UTC))); return delegate.serve(ctx, req); }); Server server = sb.build(); server.start().join(); }

Target:
public static void main(String[] args) { ServerBuilder sb = new ServerBuilder(); sb.http(8080) .annotatedService(new HelloService()) .annotatedService(new PostgresDbService()) .annotatedService(new PostgresFortunesService()) .decorator((delegate, ctx, req) -> { ctx.addAdditionalResponseHeader(HttpHeaderNames.SERVER, "armeria"); ctx.addAdditionalResponseHeader(HttpHeaderNames.DATE, DateTimeFormatter.RFC_1123_DATE_TIME.format( ZonedDateTime.now(ZoneOffset.UTC))); return delegate.serve(ctx, req); }); Server server = sb.build(); server.start().join(); }
Source:
public void writeScopedState(ScopedPersistentState state) { File stateFile = getStateFile(state.getScope()); try (PrintWriter w = new PrintWriter(stateFile)) { state.forEach((key, value) -> { w.printf("%s=%s%n", key, Util.unicodeEscapeString(value)); }); } catch (IOException e) { throw log.failedWritingGlobalState(e, stateFile); } }

Target:
public void writeScopedState(ScopedPersistentState state) { File stateFile = getStateFile(state.getScope()); try (PrintWriter w = new PrintWriter(stateFile)) { state.forEach((key, value) -> { w.printf("%s=%s%n", Util.unicodeEscapeString(key), Util.unicodeEscapeString(value)); }); } catch (IOException e) { throw log.failedWritingGlobalState(e, stateFile); } }
Source:
Row getEmbeddedObjectRow(final String className, final RealmObjectProxy parentProxy, final String parentProperty, final RealmSchema schema, final RealmObjectSchema parentObjectSchema) { final long parentPropertyColKey = parentObjectSchema.getColumnKey(parentProperty); final RealmFieldType parentPropertyType = parentObjectSchema.getFieldType(parentProperty); final String linkedType = parentObjectSchema.getLinkedType(parentProperty); final Row row = parentProxy.realmGet$proxyState().getRow$realm(); Row embeddedObject; switch (parentPropertyType) { case OBJECT: case LIST: if (linkedType.equals(className)) { long objKey = row.createEmbeddedObject(parentPropertyColKey, parentPropertyType); embeddedObject = schema.getTable(className).getCheckedRow(objKey); } else { throw new IllegalArgumentException(String.format("Parent type %s expects that property '%s' be of type %s but was %s.", parentObjectSchema.getClassName(), parentProperty, linkedType, className)); } break; default: throw new IllegalArgumentException("Parent property is not a reference to embedded objects of the appropriate type: " + parentPropertyType); } return embeddedObject; }

Target:
Row getEmbeddedObjectRow(final String className, final RealmObjectProxy parentProxy, final String parentProperty, final RealmSchema schema, final RealmObjectSchema parentObjectSchema) { final long parentPropertyColKey = parentObjectSchema.getColumnKey(parentProperty); final RealmFieldType parentPropertyType = parentObjectSchema.getFieldType(parentProperty); final Row row = parentProxy.realmGet$proxyState().getRow$realm(); final RealmFieldType fieldType = parentObjectSchema.getFieldType(parentProperty); boolean propertyAcceptable = parentObjectSchema.isPropertyAcceptableForEmbeddedObject(fieldType); if (!propertyAcceptable) { throw new IllegalArgumentException(String.format("Field '%s' does not contain a valid link", parentProperty)); } final String linkedType = parentObjectSchema.getPropertyClassName(parentProperty); Row embeddedObject; if (linkedType.equals(className)) { long objKey = row.createEmbeddedObject(parentPropertyColKey, parentPropertyType); embeddedObject = schema.getTable(className).getCheckedRow(objKey); } else { throw new IllegalArgumentException(String.format("Parent type %s expects that property '%s' be of type %s but was %s.", parentObjectSchema.getClassName(), parentProperty, linkedType, className)); } return embeddedObject; }
Source:
private void nameSpaceStrategyValidation() throws ValidationException { if (!"<username>-che".equals(defaultNamespaceName)) { String message = format( "Workspace configuration not valid: Asynchronous storage available only for 'per-user' namespace strategy"); LOG.warn(message); throw new ValidationException(message); } }

Target:
private void nameSpaceStrategyValidation() throws ValidationException { if (Strings.isNullOrEmpty(defaultNamespaceName) || !defaultNamespaceName.contains("<username>")) { String message = "Workspace configuration not valid: Asynchronous storage available only for 'per-user' namespace strategy"; LOG.warn(message); throw new ValidationException(message); } }
Source:
public void testRemoteService() throws Exception { assertInjectedService(remoteService); }

Target:
public void testRemoteService() throws Exception { assertInjectedService(remoteService, Access.REMOTE); }
Source:
public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); createInternalAAAConfigurations(); createKerberosLdapAAAConfigurations(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getLoadedExtensions()) { if (EngineLocalConfig.getInstance().getBoolean( ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), Boolean.parseBoolean( extension.getContext().<Properties>get(Base.ContextKeys.CONFIGURATION).getProperty(Base.ConfigKeys.ENABLED, "true") ) )) { instance.initialize(extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME)); } } } } } instance.dump(); return instance; }

Target:
public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); createInternalAAAConfigurations(); createKerberosLdapAAAConfigurations(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getLoadedExtensions()) { if ( EngineLocalConfig.getInstance().getBoolean( ( ENGINE_EXTENSION_ENABLED + extension.getContext() .<String> get(Base.ContextKeys.INSTANCE_NAME) ), Boolean.parseBoolean( extension.getContext().<Properties> get( Base.ContextKeys.CONFIGURATION ).getProperty(Base.ConfigKeys.ENABLED, "true") ) ) ) { instance.initialize(extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME)); } } } } } instance.dump(); return instance; }
Source:
public List<DruidServerMetadata> getCandidates(final int numCandidates) { List<DruidServerMetadata> candidates = new ArrayList<>(); synchronized (this) { if (numCandidates > 0) { candidates.addAll( strategy.pick(historicalServers, segment.get(), numCandidates) .stream() .map(server -> server.getServer().getMetadata()) .collect(Collectors.toList()) ); if (candidates.size() < numCandidates) { candidates.addAll( strategy.pick(realtimeServers, segment.get(), numCandidates - candidates.size()) .stream() .map(server -> server.getServer().getMetadata()) .collect(Collectors.toList()) ); } } else { candidates.addAll( historicalServers.values() .stream() .flatMap(Collection::stream) .map(server -> server.getServer().getMetadata()) .collect(Collectors.toList()) ); candidates.addAll( realtimeServers.values() .stream() .flatMap(Collection::stream) .map(server -> server.getServer().getMetadata()) .collect(Collectors.toList()) ); } return candidates; } }

Target:
public List<DruidServerMetadata> getCandidates(final int numCandidates) { List<DruidServerMetadata> candidates; synchronized (this) { if (numCandidates > 0) { candidates = new ArrayList<>(numCandidates); strategy.pick(historicalServers, segment.get(), numCandidates) .stream() .map(server -> server.getServer().getMetadata()) .forEach(candidates::add); if (candidates.size() < numCandidates) { strategy.pick(realtimeServers, segment.get(), numCandidates - candidates.size()) .stream() .map(server -> server.getServer().getMetadata()) .forEach(candidates::add); } return candidates; } else { return getAllServers(); } } }
Source:
public void setDetails(Map<String, Object> details) { this.details.putAll(details); }

Target:
public void setDetails(Map<String, Object> details) { this.details = details; }
Source:
private JCheckBox getButtonUseCsrf() { if (useCsrf == null) { useCsrf = new JCheckBox(); useCsrf.setToolTipText(Constant.messages.getString("manReq.checkBox.useCSRF")); } return useCsrf; }

Target:
private JToggleButton getButtonUseCsrf() { if (useCsrf == null) { useCsrf = new JToggleButton( new ImageIcon( HttpPanelSender.class.getResource( "/resource/icon/csrf-button.png"))); useCsrf.setToolTipText(Constant.messages.getString("manReq.checkBox.useCSRF")); } return useCsrf; }
Source:
private Response performCreate(ImageTransfer imageTransfer, TransferDiskImageParameters params) { updateTransferType(imageTransfer, params); if (imageTransfer.isSetHost()) { params.setVdsId(Guid.createGuidFromString(imageTransfer.getHost().getId())); } return performCreate(ActionType.TransferDiskImage, params, new QueryIdResolver<Guid>(QueryType.GetImageTransferById, IdQueryParameters.class)); }

Target:
private Response performCreate(ImageTransfer imageTransfer, TransferDiskImageParameters params) { updateTransferType(imageTransfer, params); if (imageTransfer.isSetHost() && imageTransfer.getHost().isSetId()) { params.setVdsId(Guid.createGuidFromString(imageTransfer.getHost().getId())); } return performCreate(ActionType.TransferDiskImage, params, new QueryIdResolver<Guid>(QueryType.GetImageTransferById, IdQueryParameters.class)); }
Source:
private void send(String destination, Serializable message, String propertyName, String propertValue, boolean transacted, boolean useTopic) { Connection connection = null; try { if (transacted) { connection = xaConnectionFactory.createConnection(); } else { connection = connectionFactory.createConnection(); } Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer; if (useTopic) { messageProducer = session.createProducer(session.createTopic(destination)); } else { messageProducer = session.createProducer(session.createQueue(destination)); } logger.debug("Destination is " + destination.toString()); connection.start(); ObjectMessage objectMessage = session.createObjectMessage(message); if (propertyName != null) { objectMessage.setStringProperty(propertyName, propertValue); } messageProducer.send(objectMessage); logger.debug("Sending complete"); } catch (JMSException e) { logger.error("Error sending", e.getMessage(), e); throw new MessageDeliveryException("Failed to queue push message for further processing", e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { logger.error("Failed to close JMS connection: ", e); } } } }

Target:
private void send(String destination, Serializable message, String propertyName, String propertValue, boolean transacted, boolean useTopic) { Connection connection = null; try { if (transacted) { connection = xaConnectionFactory.createConnection(); } else { connection = connectionFactory.createConnection(); } Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); final MessageProducer messageProducer; if (useTopic) { messageProducer = session.createProducer(session.createTopic(destination)); } else { messageProducer = session.createProducer(session.createQueue(destination)); } logger.debug("Destination is {}", destination); connection.start(); ObjectMessage objectMessage = session.createObjectMessage(message); if (propertyName != null) { objectMessage.setStringProperty(propertyName, propertValue); } messageProducer.send(objectMessage); logger.debug("Sending complete"); } catch (JMSException e) { logger.error("Error sending", e.getMessage(), e); throw new MessageDeliveryException("Failed to queue push message for further processing", e); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { logger.error("Failed to close JMS connection: ", e); } } } }
Source:
public void setHighlighted(String name) { for (MenuRow item : mMenuItems) item.setSelected(item.getMenuText().equals(name)); notifyDataSetChanged(); }

Target:
public void setHighlighted(String name) { for (MenuRow item : mMenuItems) { item.setSelected(item.getMenuText().equals(name)); } notifyDataSetChanged(); }
Source:
private void edit(String key, Object value) throws IOException { root.retrieve() .method("POST") .withPreview(INERTIA) .with(key, value) .method("PATCH") .withUrlPath(getApiRoute()) .to(); }

Target:
private void edit(String key, Object value) throws IOException { root.createRequest().method("PATCH").withPreview(INERTIA).with(key, value).withUrlPath(getApiRoute()).send(); }
Source:
public URL getFileUrl() { String fileURLString = String.format("%s/%s/%s", azureFileStorageClient.getUrl(), shareName, filePath); if (snapshot != null) { fileURLString = String.format("%s?snapshot=%s", fileURLString, snapshot); } try { return new URL(fileURLString); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new RuntimeException( String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), fileURLString), e)); } }

Target:
public URL getFileUrl() { StringBuilder fileURLString = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileURLString.append("?snapshot=").append(snapshot); } try { return new URL(fileURLString.toString()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new RuntimeException( String.format("Invalid URL on %s: %s" + getClass().getSimpleName(), fileURLString), e)); } }
Source:
public List<String> pollerPluginIds() { return Collections.singletonList(GERRIT_CS_POLLER_PLUGIN_ID); }

Target:
public List<String> pollerPluginIds() { return singletonList(GERRIT_CS_POLLER_PLUGIN_ID); }
Source:
public void detectBubbleEnemy(Level level, double delta) { ArrayList<NPC> enemies = level.getNPCs(); ArrayList<Fruit> fruits = level.getFruits(); ArrayList<Bubble> bubbles = level.getBubbles(); if (bubbles.size() > 0 && enemies.size() > 0) { for (int i = 0; i < enemies.size(); i++) { for (int j = 0; j < bubbles.size(); j++) { if (enemies.size() != i && enemies.get(i).inBoxRangeOf(bubbles.get(j), Constants.COLLISION_RADIUS) && new Collision(bubbles.get(j), enemies.get(i), delta).colliding()) { enemies.remove(i); bubbles.get(j).setHasNPC(true); bubbles.get(j).setLifetime(1.5 * Constants.BUBBLE_LIFETIME); } } } } }

Target:
public void detectBubbleEnemy(Level level, double delta) { ArrayList<NPC> enemies = level.getNPCs(); ArrayList<Bubble> bubbles = level.getBubbles(); ArrayList<Bubble> enemyBubbles = level.getEnemyBubbles(); if (bubbles.size() > 0 && enemies.size() > 0) { for (int i = 0; i < enemies.size(); i++) { for (int j = 0; j < bubbles.size(); j++) { if (!(bubbles.get(j).hasNPC()) && enemies.size() != i && enemies.get(i).inBoxRangeOf(bubbles.get(j), Constants.COLLISION_RADIUS) && new Collision(bubbles.get(j), enemies.get(i), delta).colliding()) { enemies.remove(i); enemyBubbles.add(bubbles.get(j)); bubbles.get(j).setHasNPC(true); bubbles.get(j).setLifetime(1.5 * Constants.BUBBLE_LIFETIME); } } } } }
Source:
public Subscriber(Publisher pub, String remote, String dir) throws IOException, ConfigInvalidException, URISyntaxException { publisher = pub; directory = dir; this.remote = remote; load(); }

Target:
public Subscriber(Publisher pub, String remote, String dir) throws IOException, ConfigInvalidException, URISyntaxException { publisher = pub; directory = dir; this.remote = remote; RemoteConfig rc = load(); subscribeSpecs = rc.getFetchRefSpecs(); if (rc.getURIs().size() == 0) throw new ConfigInvalidException(MessageFormat.format( JGitText.get().invalidRemote, remote)); name = rc.getURIs().get(0).getPath().substring(1); }
Source:
public void testExecuteScriptResources() throws IOException, InterruptedException { TestApplicationTemplate app = new TestApplicationTemplate(); Instance instance = app.getTomcatVm(); List<ExecutionResult> result1 = AgentUtils.executeScriptResources(instance, app.getName(), instance.getName()); Assert.assertEquals(0,result1.size()); File dir = InstanceHelpers.findInstanceDirectoryOnAgent( instance ); Utils.createDirectory( dir ); File script1 = new File( dir, "toto.script" ); File script2 = new File( dir, "titi.script" ); Utils.writeStringInto( "#!/bin/bash\necho Bonjour le monde cruel", script1); Utils.writeStringInto( "#!/bin/bash\necho titiiii > titi.txt", script2); List<ExecutionResult> result2 = AgentUtils.executeScriptResources(instance, app.getName(), instance.getName()); Assert.assertEquals(2,result2.size()); Assert.assertEquals(0, result2.get(0).getExitValue()); Assert.assertEquals(0, result2.get(1).getExitValue()); String s = Utils.readFileContent(new File( dir, "titi.txt")); Assert.assertEquals("titiiii",s.trim()); }

Target:
public void testExecuteScriptResources() throws IOException, InterruptedException { Assume.assumeTrue( isUnix()); File scriptsDir = this.folder.newFolder(); AgentUtils.executeScriptResources( scriptsDir ); Assert.assertEquals(0, scriptsDir.listFiles().length); File script = new File( scriptsDir, "toto-script.sh" ); Utils.writeStringInto( "#!/bin/bash\necho totototototo > toto.txt", script); AgentUtils.executeScriptResources( scriptsDir ); File toto = new File(scriptsDir,"toto.txt"); Assert.assertTrue( toto.exists() ); Assert.assertEquals( 2,scriptsDir.listFiles().length ); String s = Utils.readFileContent( toto ); Assert.assertEquals("totototototo",s.trim()); }
Source:
public void delete(ProcessDTO processDTO){ try { ProcessForm processForm = new ProcessForm(); processForm.setProcess(ServiceManager.getProcessService().getById(processDTO.getId())); processForm.delete(); } catch (DAOException e) { Helper.setErrorMessage("errorOnSearch", searchQuery); } filteredList.remove(processDTO); }

Target:
public void delete(ProcessDTO processDTO) { try { ProcessForm processForm = new ProcessForm(); processForm.setProcess(ServiceManager.getProcessService().getById(processDTO.getId())); processForm.delete(); filteredList.remove(processDTO); } catch (DAOException e) { Helper.setErrorMessage("errorOnSearch", searchQuery); } }
Source:
public void waitingForVisibilityOfAllElementsLocatedByReturnsListOfElements() { List<WebElement> webElements = new ArrayList<WebElement>(); webElements.add(mockElement); String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(webElements); when(mockElement.isDisplayed()).thenReturn(true); List<WebElement> returnedElements = wait.until(visibilityOfAllElementsLocatedBy(By.cssSelector(testSelector))); assertEquals(webElements, returnedElements); }

Target:
public void waitingForVisibilityOfAllElementsLocatedByReturnsListOfElements() { List webElements = Lists.newArrayList(mockElement); String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))).thenReturn(webElements); when(mockElement.isDisplayed()).thenReturn(true); List returnedElements = wait.until(visibilityOfAllElementsLocatedBy(By.cssSelector(testSelector))); assertEquals(webElements, returnedElements); }
Source:
public String getCaptchaUrl(Site site) { return site.getScriptPath("index.php") + "?title=Special:Captcha/image&wpCaptchaId=\" + captchaId"; }

Target:
public String getCaptchaUrl(Site site) { return site.getFullPath("index.php") + "?title=Special:Captcha/image&wpCaptchaId=" + captchaId; }
Source:
public void setOnsetDate(Date onsetDate) { this.onsetDate = new Date(onsetDate.getTime()); }

Target:
public void setOnsetDate(Date onsetDate) { this.onsetDate = onsetDate != null ? new Date(onsetDate.getTime()) : null; }