auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Member sponsorMember(PerunSession session, Vo vo, User sponsored, User sponsor) throws MemberNotExistsException, InternalErrorException, AlreadyMemberException { Member sponsoredMember; try { sponsoredMember = getMemberByUser(session, vo, sponsored); if(!sponsoredMember.isSponsored()) { throw new IllegalArgumentException("member "+sponsoredMember.getId()+" is not marked as sponsored"); } getMembersManagerImpl().addSponsor(session, sponsoredMember,sponsor); getPerunBl().getAuditer().log(session, "{} added sponsor {}", sponsoredMember, sponsor); } catch (MemberNotExistsException ex) { sponsoredMember = getMembersManagerImpl().createSponsoredMember(session, vo, sponsored, sponsor); getPerunBl().getAuditer().log(session, "{} created, sponsored by {}", sponsoredMember, sponsor); } return sponsoredMember; }

Target:
public Member sponsorMember(PerunSession session, Vo vo, User sponsored, User sponsor) throws MemberNotExistsException, InternalErrorException, AlreadyMemberException, MemberNotSponsoredException { Member sponsoredMember; try { sponsoredMember = getMemberByUser(session, vo, sponsored); if(!sponsoredMember.isSponsored()) { throw new MemberNotSponsoredException("member "+sponsoredMember.getId()+" is not marked as sponsored"); } getMembersManagerImpl().addSponsor(session, sponsoredMember,sponsor); getPerunBl().getAuditer().log(session, "{} added sponsor {}", sponsoredMember, sponsor); } catch (MemberNotExistsException ex) { sponsoredMember = getMembersManagerImpl().createSponsoredMember(session, vo, sponsored, sponsor); getPerunBl().getAuditer().log(session, "{} created, sponsored by {}", sponsoredMember, sponsor); } return sponsoredMember; }
Source:
public static ReactiveSocket createClient() { try { String target = "tcp://localhost:4567/rs"; URI uri = new URI(target); Publisher<ReactiveSocket> socketPublisher = buildConnection(uri); SocketWrapper client = new SocketWrapper(); CountDownLatch hold = new CountDownLatch(1); socketPublisher.subscribe(new Subscriber<ReactiveSocket>() { @Override public void onSubscribe(Subscription s) { s.request(1); } @Override public void onNext(ReactiveSocket reactiveSocket) { client.setSocket(reactiveSocket); hold.countDown(); } @Override public void onError(Throwable t) { System.out.println("error when getting reactive socket"); } @Override public void onComplete() { } }); hold.await(); return client.getSocket(); } catch (Exception e) { System.out.println("Something went wrong"); } return null; }

Target:
public static ReactiveSocket createClient() { ConnectionSetupPayload setupPayload = ConnectionSetupPayload.create("", ""); if ("tcp".equals(uri.getScheme())) { Function<SocketAddress, TcpClient<ByteBuf, ByteBuf>> clientFactory = socketAddress -> TcpClient.newClient(socketAddress); if (debug) clientFactory = socketAddress -> TcpClient.newClient(socketAddress).enableWireLogging("rs", LogLevel.ERROR); return toObservable( TcpReactiveSocketConnector.create(setupPayload, Throwable::printStackTrace, clientFactory) .connect(new InetSocketAddress(uri.getHost(), uri.getPort()))).toSingle() .toBlocking() .value(); } else { throw new UnsupportedOperationException("uri unsupported: " + uri); } }
Source:
public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); } catch (CandybeanException e) { return null; } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }

Target:
public static ExpectedCondition<WebDriverElement> present(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return createWebDriverElement(hook, element, driver); } catch (CandybeanException | StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }
Source:
public boolean isAvailable() { boolean isAvailable = false; if (!lastAvailable || (lastAvailableDate.before( new Date(System.currentTimeMillis() - availabilityPollInterval)))) { Response response = null; try { response = getClientFactory().getWebClient().head(); } catch (Exception e) { LOGGER.debug("Web Client was unable to connect to endpoint.", e); } if (response != null && !(response.getStatus() >= HttpStatus.SC_NOT_FOUND || response.getStatus() == HttpStatus.SC_BAD_REQUEST || response.getStatus() == HttpStatus.SC_PAYMENT_REQUIRED)) { isAvailable = true; lastAvailableDate = new Date(); } } else { isAvailable = lastAvailable; } updateMonitors(isAvailable); lastAvailable = isAvailable; return isAvailable; }

Target:
public synchronized boolean isAvailable() { boolean isAvailable = false; if (!lastAvailable || (lastAvailableDate.before( new Date(System.currentTimeMillis() - availabilityPollInterval)))) { Response response = null; try { response = getClientFactory().getWebClient().head(); } catch (Exception e) { LOGGER.debug("Web Client was unable to connect to endpoint.", e); } if (response != null && !(response.getStatus() >= HttpStatus.SC_NOT_FOUND || response.getStatus() == HttpStatus.SC_BAD_REQUEST || response.getStatus() == HttpStatus.SC_PAYMENT_REQUIRED)) { isAvailable = true; lastAvailableDate = new Date(); } } else { isAvailable = lastAvailable; } updateMonitors(isAvailable); lastAvailable = isAvailable; return isAvailable; }
Source:
void markDependencySuccess(final DependencyInstanceContext context) { this.executorService.submit(() -> { final DependencyInstance depInst = findDependencyInstanceByContext(context); if (depInst != null) { logger.info( String.format("setting dependency instance[id: %s, name: %s] status to success", depInst.getTriggerInstance().getId(), depInst.getDepName())); if (Status.isDone(depInst.getStatus())) { logger.warn(String.format("OnSuccess of dependency instance[id: %s, name: %s] is ignored", depInst.getTriggerInstance().getId(), depInst.getDepName())); return; } processStatusUpdate(depInst, Status.SUCCEEDED); if (depInst.getTriggerInstance().getStatus() == Status.SUCCEEDED) { logger.info(String.format("trigger instance with execId %s succeeded", depInst.getTriggerInstance().getId())); this.triggerProcessor.processSucceed(depInst.getTriggerInstance()); this.runningTriggers.remove(depInst.getTriggerInstance()); } } else { logger.debug(String.format("unable to find trigger instance with context %s when marking " + "it success", context)); } }); }

Target:
public void markDependencySuccess(final DependencyInstanceContext context) { this.executorService.submit(() -> { final DependencyInstance depInst = findDependencyInstanceByContext(context); if (depInst != null) { logger.info( String.format("setting dependency instance[id: %s, name: %s] status to success", depInst.getTriggerInstance().getId(), depInst.getDepName())); if (Status.isDone(depInst.getStatus())) { logger.warn(String.format("OnSuccess of dependency instance[id: %s, name: %s] is ignored", depInst.getTriggerInstance().getId(), depInst.getDepName())); return; } processStatusUpdate(depInst, Status.SUCCEEDED); if (depInst.getTriggerInstance().getStatus() == Status.SUCCEEDED) { logger.info(String.format("trigger instance with execId %s succeeded", depInst.getTriggerInstance().getId())); this.triggerProcessor.processSucceed(depInst.getTriggerInstance()); this.runningTriggers.remove(depInst.getTriggerInstance()); } } else { logger.debug(String.format("unable to find trigger instance with context %s when marking " + "it success", context)); } }); }
Source:
public Collection<ContainerRendered> getContainersRendered(final Template template, final Context velocityContext, PageMode mode) throws DotSecurityException, DotDataException { final User systemUser = this.userAPI.getSystemUser(); if (!template.isDrawed()) { return Collections.EMPTY_LIST; } final TemplateLayout layout = DotTemplateTool.themeLayout(template.getInode()); final List<ContainerUUID> containersUUID = this.templateAPI.getContainersUUID(layout); final Map<String, List<ContainerUUID>> groupByContainerID = containersUUID.stream().collect(Collectors.groupingBy(ContainerUUID::getIdentifier)); return groupByContainerID.entrySet().stream().map(entry -> { final String containerId = entry.getKey(); try { final Container container = (mode.showLive) ? (Container) APILocator.getVersionableAPI().findLiveVersion(containerId, systemUser, false) : (Container) APILocator.getVersionableAPI().findWorkingVersion(containerId, systemUser, false); final List<ContainerStructure> containerStructures = this.containerAPI.getContainerStructures(container); Map<String, String> containersRendered = null; if (velocityContext != null) { containersRendered = entry.getValue().stream() .map(containerUUID -> containerUUID.getUUID()) .collect(Collectors.toMap(uuid -> "uuid-" + uuid, uuid -> { final VelocityResourceKey key = new VelocityResourceKey(container, uuid, mode); try { return VelocityUtil.mergeTemplate(key.path, velocityContext); } catch (Exception e) { throw new DotRuntimeException(String.format("Container '%s' could not be " + "rendered via " + "Velocity.", container.getIdentifier()), e); } })); } return new ContainerRendered(container, containerStructures, containersRendered); } catch (DotDataException | DotSecurityException e) { Logger.error(ContainerRenderedBuilder.class, e.getMessage()); throw new DotRuntimeException(e); } }).collect(Collectors.toList()); }

Target:
public Collection<ContainerRendered> getContainersRendered(final Template template, final Context velocityContext, PageMode mode) throws DotSecurityException, DotDataException { if (!template.isDrawed()) { return Collections.EMPTY_LIST; } final TemplateLayout layout = DotTemplateTool.themeLayout(template.getInode()); final List<ContainerUUID> containersUUID = this.templateAPI.getContainersUUID(layout); final Map<String, List<ContainerUUID>> groupByContainerID = containersUUID.stream().collect(Collectors.groupingBy(ContainerUUID::getIdentifier)); return groupByContainerID.entrySet().stream().map(entry -> { final String containerId = entry.getKey(); try { final Container container = getContainer(mode, containerId); final List<ContainerStructure> containerStructures = this.containerAPI.getContainerStructures(container); Map<String, String> containersRendered = velocityContext != null ? render(velocityContext, mode, entry.getValue(), container): null; return new ContainerRendered(container, containerStructures, containersRendered); } catch (DotDataException | DotSecurityException e) { Logger.error(ContainerRenderedBuilder.class, e.getMessage()); throw new DotRuntimeException(e); } }).collect(Collectors.toList()); }
Source:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { FPlayer playerdata = plugin.pl.getPlayer(playerSender); playerdata.setCommandSpy(!playerdata.cmdspyEnabled()); if (playerdata.cmdspyEnabled() == true) { plugin.al.setCommandSpyActive(true, playerSender); } else { plugin.al.setCommandSpyActive(false, playerSender); } msg("CommandSpy " + (playerdata.cmdspyEnabled() ? "enabled." : "disabled.")); return true; }

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { Admin admin = getAdmin(playerSender); FPlayer playerdata = plugin.pl.getPlayer(playerSender); playerdata.setCommandSpy(!playerdata.cmdspyEnabled()); if (playerdata.cmdspyEnabled()) { admin.setCommandSpy(true); } else { admin.setCommandSpy(false); } msg("CommandSpy " + (playerdata.cmdspyEnabled() ? "enabled." : "disabled.")); return true; }
Source:
protected Control createContents(Composite parent) { Label l = new Label(parent, SWT.NONE); Repository repo = (Repository) getElement() .getAdapter(Repository.class); if (repo == null) return l; if (repo instanceof FileRepository) { GC gc = new GC((FileRepository) repo); try { RepoStatistics stats = gc.getStatistics(); StringBuilder b=new StringBuilder(); b.append(MessageFormat.format( UIText.RepositoryStatistics_NrOfLoosePackedObjects, Long.valueOf(stats.numberOfLooseObjects), Long.valueOf(stats.numberOfPackedObjects))).append('\n'); b.append(MessageFormat.format( UIText.RepositoryStatistics_BytesUsedToPersistLoosePackedObjects, describeSize(stats.sizeOfLooseObjects), describeSize(stats.sizeOfPackedObjects))).append('\n'); b.append(MessageFormat.format( UIText.RepositoryStatistics_NrOfLoosePackedRefs, Long.valueOf(stats.numberOfLooseRefs), Long.valueOf(stats.numberOfPackedRefs))).append('\n'); b.append(MessageFormat.format( UIText.RepositoryStatistics_NrOfPackfiles, Long.valueOf(stats.numberOfPackFiles))); l.setText(b.toString()); } catch (IOException e) { l.setText(e.getMessage()); } } return l; }

Target:
protected Control createContents(Composite parent) { Table table = new Table(parent, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION); String[] titles = { UIText.RepositoryStatistics_Description, UIText.RepositoryStatistics_LooseObjects, UIText.RepositoryStatistics_PackedObjects }; for (int i = 0; i < titles.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(titles[i]); } Repository repo = (Repository) getElement() .getAdapter(Repository.class); if (repo == null) return table; if (repo instanceof FileRepository) { GC gc = new GC((FileRepository) repo); try { RepoStatistics stats = gc.getStatistics(); table.setLinesVisible(true); table.setHeaderVisible(true); GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.heightHint = 200; table.setLayoutData(data); TableItem item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_NrOfObjects); item.setText(1, bigIntFmt.format(stats.numberOfLooseObjects)); item.setText(2, bigIntFmt.format(stats.numberOfPackedObjects)); item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_SpaceNeededOnFilesystem); item.setText(1, describeSize(stats.sizeOfLooseObjects)); item.setText(2, describeSize(stats.sizeOfPackedObjects)); item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_NrOfRefs); item.setText(1, bigIntFmt.format(stats.numberOfLooseRefs) .toString()); item.setText(2, bigIntFmt.format(stats.numberOfPackedRefs) .toString()); item = new TableItem(table, SWT.NONE); item.setText(0, UIText.RepositoryStatistics_NrOfPackfiles); item.setText(2, bigIntFmt.format(stats.numberOfPackFiles) .toString()); for (int i = 0; i < titles.length; i++) { table.getColumn(i).pack(); } parent.pack(); } catch (IOException e) { } } return table; }
Source:
public void force_shutdown_after_timeout() throws InterruptedException { final ExecutorService service = Executors.newSingleThreadExecutor(); service.submit(this::sleep); final long beginShutdownTime = System.currentTimeMillis(); this.executorServiceUtils.gracefulShutdown(service, Duration.ofMillis(1)); final long endShutdownTime = System.currentTimeMillis(); assertThat(service.isShutdown()).isTrue(); final long shutdownDuration = endShutdownTime - beginShutdownTime; assertThat(shutdownDuration).isLessThan(100); }

Target:
public void force_shutdown_after_timeout() throws InterruptedException { final ExecutorService service = Executors.newSingleThreadExecutor(); service.submit(this::sleep); final long beginShutdownTime = System.currentTimeMillis(); this.executorServiceUtils.gracefulShutdown(service, Duration.ofMillis(1)); final long endShutdownTime = System.currentTimeMillis(); assertThat(service.isShutdown()).isTrue(); assertThat(this.isTestThreadInterrupted).isTrue(); final long shutdownDuration = endShutdownTime - beginShutdownTime; assertThat(shutdownDuration).isLessThan(1000); }
Source:
private void parseApiKey(String key, String value) throws ConfigurationException { if (value == null) { logger.warn("Weather apikey setting '{}' has no value. Check openhab.cfg.", key); return; } String provider = PropertyResolver.last(key); ProviderName providerName = getProviderName(provider); ProviderConfig pConfig = providerConfigs.get(providerName); if (pConfig == null) { pConfig = new ProviderConfig(); pConfig.setProviderName(providerName); providerConfigs.put(providerName, pConfig); } String keyId = PropertyResolver.first(key); if (StringUtils.equalsIgnoreCase(keyId, "apikey")) { pConfig.setApiKey(value); } else if (StringUtils.equalsIgnoreCase(keyId, "apikey2")) { pConfig.setApiKey2(value); } else { logger.debug("Unknown configuration key '{}'. Check openhab.cfg.", key); } }

Target:
private void parseApiKey(String key, String value) throws ConfigurationException { if (value == null) { logger.warn("Weather apikey setting '{}' has no value. Check openhab.cfg.", key); return; } String provider = PropertyResolver.last(key); ProviderName providerName = getProviderName(provider); ProviderConfig pConfig = providerConfigs.get(providerName); if (pConfig == null) { pConfig = new ProviderConfig(); pConfig.setProviderName(providerName); providerConfigs.put(providerName, pConfig); } String keyId = PropertyResolver.first(key); if (StringUtils.equalsIgnoreCase(keyId, "apikey")) { pConfig.setApiKey(value); } else if (StringUtils.equalsIgnoreCase(keyId, "apikey2")) { pConfig.setApiKey2(value); } else { logger.warn("Unknown configuration key '{}'. Check openhab.cfg.", key); } }
Source:
public final void handleMessage(Message<?> message) { Assert.notNull(message, "Message must not be null"); Assert.notNull(message.getPayload(), "Message payload must not be null"); if (this.logger.isDebugEnabled()) { this.logger.debug(this + " received message: " + message); } long start = 0; try { if (message != null && this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } if (this.countsEnabled) { this.handlerMetrics.beforeHandle(message); } this.handleMessageInternal(message); this.handlerMetrics.afterHandle(start, true); } catch (Exception e) { this.handlerMetrics.afterHandle(start, false); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageHandlingException(message, "error occurred in message handler [" + this + "]", e); } }

Target:
public final void handleMessage(Message<?> message) { Assert.notNull(message, "Message must not be null"); Assert.notNull(message.getPayload(), "Message payload must not be null"); if (this.logger.isDebugEnabled()) { this.logger.debug(this + " received message: " + message); } long start = 0; try { if (message != null && this.shouldTrack) { message = MessageHistory.write(message, this, this.getMessageBuilderFactory()); } if (this.countsEnabled) { start = this.handlerMetrics.beforeHandle(message); } this.handleMessageInternal(message); this.handlerMetrics.afterHandle(start, true); } catch (Exception e) { this.handlerMetrics.afterHandle(start, false); if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessageHandlingException(message, "error occurred in message handler [" + this + "]", e); } }
Source:
private void createCommandHandler(String handlerClassName) throws ExecutorException { commandHandlers.add((CommandHandler) createInstance(handlerClassName)); }

Target:
private void createCommandHandler(String handlerClassName) throws CommandHandlerException { try { commandHandlers.add((CommandHandler) createInstance(handlerClassName)); } catch (ClassCastException e) { String errMsg = String.format("Error trying to cast Object of class %s to CommandHandler", handlerClassName); LOG.error(errMsg); throw new CommandHandlerException(errMsg, e); } catch (Exception e) { LOG.error(e.getMessage()); throw new CommandHandlerException(e); } }
Source:
public Scheduler(Schedulable singleThreadEntryValve, SiddhiAppContext siddhiAppContext) { this.threadBarrier = siddhiAppContext.getThreadBarrier(); this.siddhiAppContext = siddhiAppContext; this.singleThreadEntryValve = singleThreadEntryValve; this.scheduledExecutorService = siddhiAppContext.getScheduledExecutorService(); this.eventCaller = new EventCaller(); mutex = new Semaphore(1); (siddhiAppContext.getTimestampGenerator()) .addTimeChangeListener(new TimestampGenerator.TimeChangeListener() { @Override public void onTimeChange(long currentTimestamp) { Long lastTime = toNotifyQueue.peek(); if (lastTime != null && lastTime <= currentTimestamp) { sendTimerEvents(); } } }); }

Target:
public Scheduler(Schedulable singleThreadEntryValve, SiddhiAppContext siddhiAppContext) { this.threadBarrier = siddhiAppContext.getThreadBarrier(); this.siddhiAppContext = siddhiAppContext; this.singleThreadEntryValve = singleThreadEntryValve; this.scheduledExecutorService = siddhiAppContext.getScheduledExecutorService(); this.eventCaller = new EventCaller(); mutex = new Semaphore(1); siddhiAppContext.getTimestampGenerator() .addTimeChangeListener(new TimestampGenerator.TimeChangeListener() { @Override public void onTimeChange(long currentTimestamp) { Long lastTime = toNotifyQueue.peek(); if (lastTime != null && lastTime <= currentTimestamp) { sendTimerEvents(); } } }); }
Source:
protected void checkRemainingProperties(Set<String> missingProperties, List<String> availableProperties, String path, Class<?> clazz) { Properties properties = System.getProperties(); List<String> cleanNames = missingProperties.stream() .filter(propertyName -> !isPolymorphicType(clazz) || !polymorphicTypes.stream().anyMatch(type -> Objects.equals(type.getTypePath(), propertyName))) .map(propertyName -> toPath(path, propertyName)) .filter(propertyName -> !properties.containsKey(propertyName)) .filter(propertyName -> new HashSet<>(properties.entrySet()).stream().noneMatch(entry -> entry.getKey().toString().startsWith(propertyName + "."))) .sorted() .collect(Collectors.toList()); if (!cleanNames.isEmpty()) { throw new ConfigurationException("Unknown properties present in configuration: " + Joiner.on(", ").join(cleanNames) + "\n" + "Available properties:\n- " + Joiner.on("\n- ").join(availableProperties)); } }

Target:
protected void checkRemainingProperties(Set<String> missingProperties, List<String> availableProperties, String path, Class<?> clazz) { Properties properties = new Properties(); properties.putAll(System.getProperties()); List<String> cleanNames = missingProperties.stream() .filter(propertyName -> !isPolymorphicType(clazz) || !polymorphicTypes.stream().anyMatch(type -> Objects.equals(type.getTypePath(), propertyName))) .map(propertyName -> toPath(path, propertyName)) .filter(propertyName -> !properties.containsKey(propertyName)) .filter(propertyName -> properties.entrySet().stream().noneMatch(entry -> entry.getKey().toString().startsWith(propertyName + "."))) .sorted() .collect(Collectors.toList()); if (!cleanNames.isEmpty()) { throw new ConfigurationException("Unknown properties present in configuration: " + Joiner.on(", ").join(cleanNames) + "\n" + "Available properties:\n- " + Joiner.on("\n- ").join(availableProperties)); } }
Source:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error("Handling error for message type: " + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build()); }

Target:
protected void handleError(final Exception e, final String correlationUid, final String organisationIdentification, final String deviceIdentification, final String messageType) { LOGGER.error("Handling error for message type: " + messageType, e); OsgpException osgpException = null; if (e instanceof OsgpException) { osgpException = (OsgpException) e; } else { osgpException = new TechnicalException(ComponentType.DOMAIN_PUBLIC_LIGHTING, "An unknown error occurred", e); } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(ResponseMessageResultType.NOT_OK) .withOsgpException(osgpException).withDataObject(e).build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
public static void getMRandYarn(MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> yarnOperationEntities = extractor.extractMetadata(marker, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", null).getEntities(); getFirstResult(yarnOperationEntities); List<String> sourceTypes = Lists.newArrayList("MAPREDUCE", "YARN"); List<String> types = Lists.newArrayList("OPERATION EXECUTION"); String entityQuery = ClientUtils.buildQuery(sourceTypes, types); Iterable<Map<String, Object>> yarnOperationEntities2 = extractor.extractMetadata(marker, entityQuery, "").getEntities(); getFirstResult(yarnOperationEntities2); Iterable<Map<String, Object>> yarnOperationRelations = extractor.extractMetadata(marker, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", "type:DATA_FLOW " + "AND endpoint1SourceType:HDFS OR endpoint2SourceType:HDFS").getRelations(); getFirstResult(yarnOperationRelations); }

Target:
public static String getMRandYarn(MetadataExtractor extractor, String marker){ Iterable<Map<String, Object>> yarnOpEntities = extractor.extractMetadata( marker, null, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", null).getEntities(); getFirstResult(yarnOpEntities); List<String> sourceTypes = Lists.newArrayList("MAPREDUCE", "YARN"); List<String> types = Lists.newArrayList("OPERATION EXECUTION"); String entityQuery = ClientUtils.buildQuery(sourceTypes, types); Iterable<Map<String, Object>> yarnOpEntities2 = extractor.extractMetadata( marker, null, entityQuery, "").getEntities(); getFirstResult(yarnOpEntities2); MetadataResultSet yarnOp = extractor.extractMetadata( marker, null, "sourceType:(MAPREDUCE OR YARN) AND type:OPERATION_EXECUTION", "type:DATA_FLOW AND endpoint1SourceType:HDFS OR endpoint2SourceType:HDFS"); Iterable<Map<String, Object>> yarnOpRelations = yarnOp.getRelations(); getFirstResult(yarnOpRelations); return yarnOp.getMarker(); }
Source:
public void hsbHueAlwaysGreaterThanZeroAndLessThan360() { final State lightState = new State(); lightState.colormode = ColorMode.CT.toString(); for (int hue = 0; hue <= 65535; ++hue) { lightState.hue = hue; assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() >= 0); assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() < 360); } }

Target:
public void hsbHueAlwaysGreaterThanZeroAndLessThan360() { final State lightState = new State(); for (int hue = 0; hue <= 65535; ++hue) { lightState.hue = hue; assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() >= 0); assertTrue(LightStateConverter.toHSBType(lightState).getHue().intValue() < 360); } }
Source:
public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException{ Variable v = symbolTable.get(identifier); if(v == null){ if(parentScope == null){ throw new VariableNotDefinedException(identifier); } return parentScope.getVariable(identifier); }else{ return v; } }

Target:
public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException { Variable v = symbolTable.get(identifier); if (v == null) { if (parentScope == null) { throw new VariableNotDefinedException(identifier); } else { return parentScope.getVariable(identifier); } } else { return v; } }
Source:
public void queryDepartures() throws Exception { final QueryDeparturesResult result = queryDepartures("NA190", false); print(result); }

Target:
public void queryDepartures() throws Exception { final QueryDeparturesResult result = queryDepartures("OAW:SP:CH240", false); print(result); }
Source:
public Response install(Action action) { VDS vds = getEntity(); UpdateVdsActionParameters params = new UpdateVdsActionParameters(vds.getStaticData(), action.getRootPassword(), true); if (action.isSetSsh()) { if (action.getSsh().isSetUser()) { if (action.getSsh().getUser().isSetPassword()) { params.setRootPassword(action.getSsh().getUser().getPassword()); } } if (action.getSsh().isSetPort()) { params.getvds().setSshPort(action.getSsh().getPort().intValue()); } if (action.getSsh().isSetFingerprint()) { params.getvds().setSshKeyFingerprint(action.getSsh().getFingerprint()); } if (action.getSsh().isSetAuthenticationMethod()) { AuthenticationMethod m = getMapper(String.class, AuthenticationMethod.class). map(action.getSsh().getAuthenticationMethod(), null); if (m != null) { params.setAuthMethod( getMapper(AuthenticationMethod.class, org.ovirt.engine.core.common.action.VdsOperationActionParameters.AuthenticationMethod.class).map(m, null)); } } } if (vds.getVdsType()==VDSType.oVirtNode) { params.setIsReinstallOrUpgrade(true); if (action.isSetImage()) { params.setoVirtIsoFile(action.getImage()); } } else { validateParameters(action, "rootPassword"); } return doAction(VdcActionType.UpdateVds, params, action); }

Target:
public Response install(Action action) { VDS vds = getEntity(); validateEnums(Action.class, action); UpdateVdsActionParameters params = new UpdateVdsActionParameters(vds.getStaticData(), action.getRootPassword(), true); params = (UpdateVdsActionParameters) getMapper (Action.class, VdsOperationActionParameters.class).map(action, (VdsOperationActionParameters) params); if (vds.getVdsType()==VDSType.oVirtNode) { params.setIsReinstallOrUpgrade(true); if (action.isSetImage()) { params.setoVirtIsoFile(action.getImage()); } } else { validateParameters(action, "rootPassword"); } return doAction(VdcActionType.UpdateVds, params, action); }
Source:
public NamespaceHandler(HttpHandler containerHandler) { log.info("Creating NamespaceHandler"); this.containerHandler = containerHandler; try { this.token = getToken(); log.info("Received token from " + TOKEN_FILE_LOCATION); } catch (Exception e){ log.info("Error retrieving token from file " + TOKEN_FILE_LOCATION); throw new RuntimeException(e); } namespaceListener = new NamespaceListener(token); NamespaceOverrideMapper nom = new NamespaceOverrideMapper(token); log.info("Received namespace overrides: " + nom.overrides); this.projectOverwrites = nom.overrides; }

Target:
public NamespaceHandler(HttpHandler containerHandler) { log.info("Creating NamespaceHandler"); this.containerHandler = containerHandler; try { this.token = getToken(); log.info("Received token from " + TOKEN_FILE_LOCATION); } catch (Exception e){ log.error("Error retrieving token from file " + TOKEN_FILE_LOCATION); throw new RuntimeException(e); } namespaceListener = new NamespaceListener(token); NamespaceOverrideMapper nom = new NamespaceOverrideMapper(token); log.info("Received namespace overrides: " + nom.overrides); this.projectOverwrites = nom.overrides; }
Source:
public void instead(String consumerEndpointId, MessageHandler mockMessageHandler, boolean autoStartup) { instead(consumerEndpointId, mockMessageHandler, IntegrationConsumer.class, "handler", autoStartup); if (mockMessageHandler instanceof MessageProducer) { Object targetMessageHandler = this.beans.get(consumerEndpointId); if (targetMessageHandler instanceof MessageProducer) { MessageChannel outputChannel = TestUtils.getPropertyValue(targetMessageHandler, "outputChannel", MessageChannel.class); ((MessageProducer) mockMessageHandler).setOutputChannel(outputChannel); } } }

Target:
public void instead(String consumerEndpointId, MessageHandler mockMessageHandler, boolean autoStartup) { Object endpoint = this.beanFactory.getBean(consumerEndpointId, IntegrationConsumer.class); if (autoStartup && endpoint instanceof Lifecycle) { ((Lifecycle) endpoint).stop(); } DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(endpoint); Object targetMessageHandler = directFieldAccessor.getPropertyValue("handler"); this.beans.put(consumerEndpointId, targetMessageHandler); if (mockMessageHandler instanceof MessageProducer) { if (targetMessageHandler instanceof MessageProducer) { MessageChannel outputChannel = TestUtils.getPropertyValue(targetMessageHandler, "outputChannel", MessageChannel.class); ((MessageProducer) mockMessageHandler).setOutputChannel(outputChannel); } else { if (mockMessageHandler instanceof MockMessageHandler) { if (TestUtils.getPropertyValue(mockMessageHandler, "hasReplies", Boolean.class)) { throw new IllegalStateException("The [" + mockMessageHandler + "] " + "with replies can't replace simple MessageHandler [" + targetMessageHandler + "]"); } } else { throw new IllegalStateException("The MessageProducer handler [" + mockMessageHandler + "] " + "can't replace simple MessageHandler [" + targetMessageHandler + "]"); } } } directFieldAccessor.setPropertyValue("handler", mockMessageHandler); if (autoStartup && endpoint instanceof Lifecycle) { ((Lifecycle) endpoint).start(); } }
Source:
public DataSet buildDataSet(Map<String, String> params) { final DataSetBuilder dsBuilder = DataSetFactory.newDataSetBuilder(); for (final DataColumnDef columnDef : dataSetdef.getColumns()) { dsBuilder.column(columnDef.getId(), columnDef.getColumnType()); } final Collection<OrganizationalUnit> orgUnitList = organizationalUnitService.getOrganizationalUnits(); for (final OrganizationalUnit orgUnit : orgUnitList) { final String org = orgUnit.getName(); final Collection<Project> projects = projectService.getAllProjects(orgUnit); if (projects.isEmpty()) { dsBuilder.row(org, null, null, "Empty organizational unit", null); } else { for (final Project project : projects) { final String repoAlias = project.getRepository().getAlias(); final String projectName = project.getName(); org.uberfire.backend.vfs.Path rootPath = project.getRootPath(); final Path projectRoot = Paths.convert(rootPath); final List<VersionRecord> recordList = recordService.loadVersionRecords(projectRoot); if (recordList.isEmpty()) { dsBuilder.row(org, repoAlias, null, null, null, "Empty project", null); } else { for (VersionRecord record : recordList) { String alias = record.author(); String author = authorMappings.getProperty(alias); author = author == null ? alias : author; String msg = record.comment(); Date date = record.date(); dsBuilder.row(org, repoAlias, projectName, author, msg, date); } } } } } DataSet dataSet = dsBuilder.buildDataSet(); dataSet.setUUID(GIT_CONTRIB); return dataSet; }

Target:
public DataSet buildDataSet(Map<String, String> params) { final DataSetBuilder dsBuilder = DataSetFactory.newDataSetBuilder(); for (final DataColumnDef columnDef : dataSetdef.getColumns()) { dsBuilder.column(columnDef.getId(), columnDef.getColumnType()); } final Collection<OrganizationalUnit> orgUnitList = organizationalUnitService.getOrganizationalUnits(); for (final OrganizationalUnit orgUnit : orgUnitList) { final String org = orgUnit.getName(); final Collection<WorkspaceProject> projects = projectService.getAllWorkspaceProjects(orgUnit); if (projects.isEmpty()) { dsBuilder.row(org, null, null, "Empty organizational unit", null); } else { for (final WorkspaceProject project : projects) { final String repoAlias = project.getRepository().getAlias(); final String projectName = project.getName(); org.uberfire.backend.vfs.Path rootPath = project.getRootPath(); final Path projectRoot = Paths.convert(rootPath); final List<VersionRecord> recordList = recordService.loadVersionRecords(projectRoot); if (recordList.isEmpty()) { dsBuilder.row(org, repoAlias, null, null, null, "Empty project", null); } else { for (VersionRecord record : recordList) { String alias = record.author(); String author = authorMappings.getProperty(alias); author = author == null ? alias : author; String msg = record.comment(); Date date = record.date(); dsBuilder.row(org, repoAlias, projectName, author, msg, date); } } } } } DataSet dataSet = dsBuilder.buildDataSet(); dataSet.setUUID(GIT_CONTRIB); return dataSet; }
Source:
public StudyEventBean getNextParticipantEvent(StudySubjectBean studySubject) { List<StudyEventBean> studyEvents = (ArrayList<StudyEventBean>)getStudyEventDAO().findAllBySubjectIdOrdered(studySubject.getId()); for (StudyEventBean studyEvent:studyEvents) { if ( (studyEvent.getRemoved()!=null && studyEvent.getRemoved()) || (studyEvent.getArchived()!=null && studyEvent.getArchived()) || (!studyEvent.getWorkflowStatus().equals(StudyEventWorkflowStatusEnum.DATA_ENTRY_STARTED) && !studyEvent.getWorkflowStatus().equals(StudyEventWorkflowStatusEnum.SCHEDULED))) continue; List<EventDefinitionCRFBean> eventDefCrfs = getEventDefCrfsForStudyEvent(studySubject, studyEvent); for (EventDefinitionCRFBean eventDefCrf:eventDefCrfs) { boolean participantForm = eventDefCrf.isParticipantForm(); if (participantForm) { List<FormLayoutBean> formLayouts = getAllFormLayouts(eventDefCrf); boolean eventCrfExists = false; for (FormLayoutBean formLayout:formLayouts) { EventCRFBean eventCRF = getEventCRFDAO().findByEventFormLayout(studyEvent, formLayout); if (eventCRF != null && (eventCRF.getRemoved()==null || !eventCRF.getRemoved()) && (eventCRF.getArchived()==null || !eventCRF.getArchived())) return studyEvent; else if (eventCRF != null) eventCrfExists = true; } if (!eventCrfExists) return studyEvent; } } } return null; }

Target:
public StudyEventBean getNextParticipantEvent(StudySubjectBean studySubject) { List<StudyEventBean> studyEvents = (ArrayList<StudyEventBean>)getStudyEventDAO().findAllBySubjectIdOrdered(studySubject.getId()); for (StudyEventBean studyEvent:studyEvents) { if ( BooleanUtils.isTrue(studyEvent.getRemoved()) || BooleanUtils.isTrue(studyEvent.getArchived()) || (!studyEvent.getWorkflowStatus().equals(StudyEventWorkflowStatusEnum.DATA_ENTRY_STARTED) && !studyEvent.getWorkflowStatus().equals(StudyEventWorkflowStatusEnum.SCHEDULED))) continue; List<EventDefinitionCRFBean> eventDefCrfs = getEventDefCrfsForStudyEvent(studySubject, studyEvent); for (EventDefinitionCRFBean eventDefCrf:eventDefCrfs) { boolean participantForm = eventDefCrf.isParticipantForm(); if (participantForm) { List<FormLayoutBean> formLayouts = getAllFormLayouts(eventDefCrf); boolean eventCrfExists = false; for (FormLayoutBean formLayout:formLayouts) { EventCRFBean eventCRF = getEventCRFDAO().findByEventFormLayout(studyEvent, formLayout); if (BooleanUtils.isFalse(eventCRF.getRemoved()) && BooleanUtils.isFalse(eventCRF.getArchived())) return studyEvent; else if (eventCRF != null) eventCrfExists = true; } if (!eventCrfExists) return studyEvent; } } } return null; }
Source:
public boolean updateMembers(Collection<Address> newMembers) { collector.retain(newMembers); log.tracef("Rebalance confirmation collector %d@%s members list updated, remaining list is %s", topologyId, cacheName, collector.pending()); return collector.isAllCollected(); }

Target:
public boolean updateMembers(Collection<Address> newMembers) { synchronized (this) { boolean modified = confirmationsNeeded.retainAll(newMembers); log.tracef("Rebalance confirmation collector %d@%s members list updated, remaining list is %s", topologyId, cacheName, confirmationsNeeded); return modified && confirmationsNeeded.isEmpty(); } }
Source:
public boolean isTopicCreationEnabled() { return config.getBoolean(TOPIC_CREATION_ENABLE_CONFIG); }

Target:
public boolean isTopicCreationEnabled() { return config.topicCreationEnable(); }
Source:
public GroupItem(String name, GenericItem baseItem, GroupFunction function) { super(TYPE, name); if (baseItem == null || function == null) { baseItem = null; function = null; } members = new CopyOnWriteArraySet<Item>(); this.function = function; this.baseItem = baseItem; }

Target:
public GroupItem(String name, GenericItem baseItem, GroupFunction function) { super(TYPE, name); if (baseItem == null || function == null) { this.baseItem = null; this.function = null; } else { this.function = function; this.baseItem = baseItem; } members = new CopyOnWriteArraySet<Item>(); }
Source:
public static void checkNewVersion(@NonNull final App app) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app); if (!prefs.getBoolean(app.getString(R.string.update_app_key), true) || !isGithubApk(app)) { if (disposable != null) { disposable.dispose(); } return; } disposable = Observable.fromCallable(() -> { if (!isConnected(app)) { return null; } try { return DownloaderImpl.getInstance().get(NEWPIPE_API_URL).responseBody(); } catch (IOException | ReCaptchaException e) { if (DEBUG) { Log.w(TAG, Log.getStackTraceString(e)); } } return null; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(response -> { if (response != null) { try { final JsonObject githubStableObject = JsonParser.object().from(response) .getObject("flavors").getObject("github").getObject("stable"); final String versionName = githubStableObject.getString("version"); final int versionCode = githubStableObject.getInt("version_code"); final String apkLocationUrl = githubStableObject.getString("apk"); compareAppVersionAndShowNotification(app, versionName, apkLocationUrl, versionCode); } catch (final JsonParserException e) { if (DEBUG) { Log.w(TAG, Log.getStackTraceString(e)); } } } }); }

Target:
public static Disposable checkNewVersion(@NonNull final App app) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app); if (!prefs.getBoolean(app.getString(R.string.update_app_key), true) || !isGithubApk(app)) { return Disposables.empty(); } return Observable.fromCallable(() -> { if (!isConnected(app)) { return null; } try { return DownloaderImpl.getInstance().get(NEWPIPE_API_URL).responseBody(); } catch (IOException | ReCaptchaException e) { if (DEBUG) { Log.w(TAG, Log.getStackTraceString(e)); } } return null; }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(response -> { if (response != null) { try { final JsonObject githubStableObject = JsonParser.object().from(response) .getObject("flavors").getObject("github").getObject("stable"); final String versionName = githubStableObject.getString("version"); final int versionCode = githubStableObject.getInt("version_code"); final String apkLocationUrl = githubStableObject.getString("apk"); compareAppVersionAndShowNotification(app, versionName, apkLocationUrl, versionCode); } catch (final JsonParserException e) { if (DEBUG) { Log.w(TAG, Log.getStackTraceString(e)); } } } }); }
Source:
public void addEventListenerFactory(EventListenerFactory eventListenerFactory) { configuredEventListener.set(Optional.of(eventListenerFactory.create(ImmutableMap.of(), new EventListenerContext() { private final MBeanServer mBeanServer = getMBeanNamespaceManager().createMBeanServer("TestEventListener"); @Override public MBeanServer getMBeanServer() { return mBeanServer; } }))); }

Target:
public void addEventListenerFactory(EventListenerFactory eventListenerFactory) { configuredEventListener.set(Optional.of(eventListenerFactory.create(ImmutableMap.of(), new EventListenerContext() { @Override public MBeanServer getMBeanServer() { return mBeanServer; } }))); }
Source:
private void waitForPriorityEvents(InputGate inputGate, MailboxExecutor mailboxExecutor) { final CompletableFuture<?> priorityEventAvailableFuture = inputGate.getPriorityEventAvailableFuture(); FutureUtils.assertNoException(priorityEventAvailableFuture.thenRun(() -> { try { mailboxExecutor.execute(this::processPriorityEvents, "process priority event @ gate %s", inputGate); } catch (RejectedExecutionException ex) { LOG.info("Ignored RejectedExecutionException in CheckpointedInputGate.waitForPriorityEvents"); } })); }

Target:
private void waitForPriorityEvents(InputGate inputGate, MailboxExecutor mailboxExecutor) { final CompletableFuture<?> priorityEventAvailableFuture = inputGate.getPriorityEventAvailableFuture(); assertNoException(priorityEventAvailableFuture.thenRun(() -> { try { mailboxExecutor.execute(this::processPriorityEvents, "process priority event @ gate %s", inputGate); } catch (RejectedExecutionException ex) { LOG.debug("Ignored RejectedExecutionException in CheckpointedInputGate.waitForPriorityEvents"); } })); }
Source:
public void handlePeriodicMeterReadsresponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final PeriodicMeterReadsResponseDto periodMeterReadsValueDTO) { LOGGER.info("handlePeriodicMeterReadsresponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send( ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception) .withDataObject( this.monitoringMapper.map(periodMeterReadsValueDTO, PeriodicMeterReadsContainer.class)) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }

Target:
public void handlePeriodicMeterReadsresponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final PeriodicMeterReadsResponseDto periodMeterReadsValueDTO) { LOGGER.info("handlePeriodicMeterReadsresponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error(DEVICE_RESPONSE_NOT_OK_LOG_MSG, exception); result = ResponseMessageResultType.NOT_OK; } final ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception) .withDataObject(this.monitoringMapper.map(periodMeterReadsValueDTO, PeriodicMeterReadsContainer.class)) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
private boolean isCandidate(Map<ColumnHandle, NullableValue> bindings) { if (!arguments.stream().anyMatch(bindings.keySet()::contains)) { return true; } LookupSymbolResolver inputs = new LookupSymbolResolver(assignments, bindings); Object optimized = evaluator.optimize(inputs); if (Boolean.FALSE.equals(optimized) || optimized == null || optimized instanceof NullLiteral) { return false; } return true; }

Target:
private boolean isCandidate(Map<ColumnHandle, NullableValue> bindings) { if (intersection(bindings.keySet(), arguments).isEmpty()) { return true; } LookupSymbolResolver inputs = new LookupSymbolResolver(assignments, bindings); Object optimized = evaluator.optimize(inputs); if (Boolean.FALSE.equals(optimized) || optimized == null || optimized instanceof NullLiteral) { return false; } return true; }