auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable tempTvp = ppool.takeOne(TaggedValuePointable.class); TaggedValuePointable tempValue = ppool.takeOne(TaggedValuePointable.class); UTF8StringPointable tempKey = ppool.takeOne(UTF8StringPointable.class); try { abvs.reset(); ob.reset(abvs); tvps.clear(); TaggedValuePointable arg = args[0]; if (arg.getTag() == ValueTag.SEQUENCE_TAG) { arg.getValue(sp); for (int i = 0; i < sp.getEntryCount(); ++i) { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); sp.getEntry(i, tempTvp); tempTvp.getValue(op); op.getKeys(tempTvp); if (tempTvp.getTag() == ValueTag.XS_STRING_TAG) { addPair(tempTvp, tempKey, tempValue); } else if (tempTvp.getTag() == ValueTag.SEQUENCE_TAG) { tempTvp.getValue(sp1); for (int j = 0; j < sp1.getEntryCount(); ++j) { key = ppool.takeOne(TaggedValuePointable.class); sp1.getEntry(j, tempTvp); addPair(tempTvp, tempKey, tempValue); } } } } ob.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } finally { ppool.giveBack(tempKey); ppool.giveBack(tempTvp); for (TaggedValuePointable pointable : tvps) { ppool.giveBack(pointable); } } }

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { TaggedValuePointable arg = args[0]; if (!(arg.getTag() == ValueTag.SEQUENCE_TAG || arg.getTag() == ValueTag.OBJECT_TAG)) { throw new SystemException(ErrorCode.FORG0006); } TaggedValuePointable tempTvp = ppool.takeOne(TaggedValuePointable.class); TaggedValuePointable tempValue = ppool.takeOne(TaggedValuePointable.class); try { abvs.reset(); ob.reset(abvs); tvps.clear(); if (arg.getTag() == ValueTag.SEQUENCE_TAG) { arg.getValue(sp); for (int i = 0; i < sp.getEntryCount(); ++i) { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); sp.getEntry(i, tempTvp); tempTvp.getValue(op); op.getKeys(tempTvp); addPairs(tempTvp, tempValue); } } else { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); arg.getValue(op); addPairs(tempTvp, tempValue); } ob.finish(); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } finally { ppool.giveBack(tempTvp); for (TaggedValuePointable pointable : tvps) { ppool.giveBack(pointable); } } }
Source:
public void unbindConsumers(String inputName) { List<Binding<?>> bindings = this.consumerBindings.remove(inputName); if (bindings != null && !CollectionUtils.isEmpty(bindings)) { for (Binding<?> binding : bindings) { binding.unbind(); } } else if (log.isWarnEnabled()) { log.warn("Trying to unbind channel '" + inputName + "', but no binding found."); } }

Target:
public void unbindConsumers(String inputName) { List<Binding<?>> bindings = this.consumerBindings.remove(inputName); if (bindings != null && !CollectionUtils.isEmpty(bindings)) { for (Binding<?> binding : bindings) { binding.unbind(); } } else if (log.isWarnEnabled()) { log.warn("Trying to unbind '" + inputName + "', but no binding found."); } }
Source:
} catch (Exception exception) { throw new ExceptionInInitializerError(new IOException("Error parsing id_rsa", exception)); }

Target:
} catch (Exception exception) { throw new ExceptionInInitializerError(new IOException("Error parsing net.xml.", exception)); }
Source:
public void handleLifecycleEvent(SaveablesLifecycleEvent event) { if (currentPart == null || event.getEventType() != SaveablesLifecycleEvent.DIRTY_CHANGED) { return; } if (!isDirtyStateSupported()) { return; } Saveable[] saveables = event.getSaveables(); for (Saveable saveable : saveables) { if (new DefaultSaveable(PropertySheet.this).equals(saveable)) { return; } } if (event.getSource() instanceof SaveablesList) { SaveablesList saveablesList = (SaveablesList) event.getSource(); for (Saveable saveable : saveables) { IWorkbenchPart[] parts = saveablesList.getPartsForSaveable(saveable); for (IWorkbenchPart part : parts) { if (PropertySheet.this.currentPart == part) { firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY); return; } } } } }

Target:
public void handleLifecycleEvent(SaveablesLifecycleEvent event) { if (currentPart == null || event.getEventType() != SaveablesLifecycleEvent.DIRTY_CHANGED || !isDirtyStateSupported()) { return; } Saveable[] saveables = event.getSaveables(); if (saveables == null) { return; } for (Saveable saveable : saveables) { if (new DefaultSaveable(PropertySheet.this).equals(saveable)) { return; } } if (event.getSource() instanceof SaveablesList) { SaveablesList saveablesList = (SaveablesList) event.getSource(); for (Saveable saveable : saveables) { IWorkbenchPart[] parts = saveablesList.getPartsForSaveable(saveable); for (IWorkbenchPart part : parts) { if (PropertySheet.this.currentPart == part) { firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY); return; } } } } }
Source:
private void handleKeyAlreadyExistsException( long commitTs, KeyAlreadyExistsException ex, LockToken commitLocksToken) { try { if (wasCommitSuccessful(commitTs)) { return; } Set<LockToken> expiredLocks = refreshCommitAndImmutableTsLocks(commitLocksToken); if (!expiredLocks.isEmpty()) { transactionOutcomeMetrics.markLocksExpired(); throw new TransactionLockTimeoutException("Our commit was already rolled back at commit time" + " because our locks timed out. startTs: " + getStartTimestamp() + ". " + getExpiredLocksErrorString(commitLocksToken, expiredLocks), ex); } else { log.info("This transaction has been rolled back by someone else.", SafeArg.of("immutableTimestampLock", immutableTimestampLock), SafeArg.of("commitLocksToken", commitLocksToken)); } } catch (TransactionFailedException e1) { throw e1; } catch (Exception e1) { log.error("Failed to determine if we can retry this transaction. startTs: {}", SafeArg.of("startTs", getStartTimestamp()), e1); } String msg = "Our commit was already rolled back at commit time." + " Locking should prevent this from happening, but our locks may have timed out." + " startTs: " + getStartTimestamp(); throw new TransactionCommitFailedException(msg, ex); }

Target:
private void handleKeyAlreadyExistsException( long commitTs, KeyAlreadyExistsException ex, LockToken commitLocksToken) { try { if (wasCommitSuccessful(commitTs)) { return; } Set<LockToken> expiredLocks = refreshCommitAndImmutableTsLocks(commitLocksToken); if (!expiredLocks.isEmpty()) { transactionOutcomeMetrics.markLocksExpired(); throw new TransactionLockTimeoutException("Our commit was already rolled back at commit time" + " because our locks timed out. startTs: " + getStartTimestamp() + ". " + getExpiredLocksErrorString(commitLocksToken, expiredLocks), ex); } else { log.info("This transaction has been rolled back by someone else, even though we believe we still hold " + "the locks. This is not expected to occur frequently.", immutableTimestampLock .map(token -> token.toSafeArg("immutableTimestampLock")) .orElseGet(() -> SafeArg.of("immutableTimestampLock", null)), commitLocksToken.toSafeArg("commitLocksToken")); } } catch (TransactionFailedException e1) { throw e1; } catch (Exception e1) { log.error("Failed to determine if we can retry this transaction. startTs: {}", SafeArg.of("startTs", getStartTimestamp()), e1); } String msg = "Our commit was already rolled back at commit time." + " Locking should prevent this from happening, but our locks may have timed out." + " startTs: " + getStartTimestamp(); throw new TransactionCommitFailedException(msg, ex); }
Source:
ImageEditorPanel(MainFrame mainFrame, BufferedImage image, String name) { this.image = image; this.name = name; setTransferHandler(new ImageTransferHandler(mainFrame)); checkImage(); setOpaque(false); setLayout(new BorderLayout()); loadSupport(); buildImageViewer(); buildStatusPanel(); }

Target:
ImageEditorPanel(MainFrame mainFrame, BufferedImage image, String name) { this.image = image; this.name = name; setTransferHandler(new ImageTransferHandler(mainFrame)); setOpaque(false); setLayout(new BorderLayout()); loadSupport(); buildImageViewer(); buildStatusPanel(); checkImage(); }
Source:
@Test public void unprocessedRequest() throws Exception { MOCK_RESPONSE.set(SUCCESS_RESPONSE); AtomicReference<RequestLog> log = new AtomicReference<>(); http = new HttpCall.Factory(new HttpClientBuilder(server.httpUri("/")) .decorator((client, ctx, req) -> { throw new UnprocessedRequestException("Could not process request.", new EndpointGroupException("No endpoints")); }) .build()); assertThatThrownBy(() -> http.newCall(REQUEST, BodyConverters.NULL, "test").execute()) .isInstanceOf(RejectedExecutionException.class) .hasMessageContaining("No endpoints"); }

Target:
@Test public void unprocessedRequest() throws Exception { MOCK_RESPONSE.set(SUCCESS_RESPONSE); AtomicReference<RequestLog> log = new AtomicReference<>(); http = new HttpCall.Factory(new HttpClientBuilder(server.httpUri("/")) .decorator((client, ctx, req) -> { throw new UnprocessedRequestException("Could not process request.", new EndpointGroupException("No endpoints")); }) .build()); assertThatThrownBy(() -> http.newCall(REQUEST, BodyConverters.NULL, "test").execute()) .isInstanceOf(RejectedExecutionException.class) .hasMessage("Rejected execution: No endpoints"); }
Source:
public static ShellLogHandler getLogHandler(Map<String, Object> topoConf) { if (topoConf == null) { throw new IllegalArgumentException("Config is required"); } if (topoConf.containsKey(Config.TOPOLOGY_MULTILANG_LOG_HANDLER)) { try { return (ShellLogHandler) Class.forName(topoConf.get(Config.TOPOLOGY_MULTILANG_LOG_HANDLER).toString()).newInstance(); } catch (ClassCastException | InstantiationException | IllegalAccessException | ClassNotFoundException e) { LOG.warn(e.toString()); } } return new DefaultShellLogHandler(); }

Target:
public static ShellLogHandler getLogHandler(Map<String, Object> topoConf) { if (topoConf == null) { throw new IllegalArgumentException("Config is required"); } String logHandlerClassName = null; if (topoConf.containsKey(Config.TOPOLOGY_MULTILANG_LOG_HANDLER)) { try { logHandlerClassName = topoConf.get(Config.TOPOLOGY_MULTILANG_LOG_HANDLER).toString(); return (ShellLogHandler) Class.forName(logHandlerClassName).newInstance(); } catch (ClassCastException | InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException("Error loading ShellLogHandler " + logHandlerClassName, e); } } return new DefaultShellLogHandler(); }
Source:
private void verifyFeedbackIsReportedToService() { AuthHeader authHeader = AuthHeader.valueOf("Bearer omitted"); SettableRefreshable<AtlasDbRuntimeConfig> refreshableRuntimeConfig = Refreshable.create(mockAtlasDbRuntimeConfig); Refreshable<List<TimeLockClientFeedbackService>> timeLockClientFeedbackServices = TransactionManagers.getTimeLockClientFeedbackServices( config, refreshableRuntimeConfig, USER_AGENT, DialogueClients.create(Refreshable.only(ServicesConfigBlock.builder().build())) .withBlockingExecutor(PTExecutors.newCachedThreadPool("atlas-dialogue-blocking"))); ConjureTimeLockClientFeedback feedbackReport = ConjureTimeLockClientFeedback .builder() .atlasVersion("1.0") .serviceName("service") .nodeId(UUID.randomUUID()) .build(); assertThat(timeLockClientFeedbackServices.current().size()).isEqualTo(1); timeLockClientFeedbackServices.current().get(0).reportFeedback(authHeader, feedbackReport); List<LoggedRequest> requests = findAll(postRequestedFor(urlMatching(FEEDBACK_PATH))); assertThat(requests.size()).isEqualTo(1); availableServer.verify(postRequestedFor(urlMatching(FEEDBACK_PATH)) .withHeader("Authorization", WireMock.containing("Bearer omitted"))); timeLockRuntimeConfig = getTimelockRuntimeConfig(ImmutableList.of()); mockAtlasDbRuntimeConfig = mock(AtlasDbRuntimeConfig.class); when(mockAtlasDbRuntimeConfig.timelockRuntime()).thenReturn(Optional.of(timeLockRuntimeConfig)); refreshableRuntimeConfig.update(mockAtlasDbRuntimeConfig); assertThat(timeLockClientFeedbackServices.current().size()).isEqualTo(0); }

Target:
private void verifyFeedbackIsReportedToService() { AuthHeader authHeader = AuthHeader.valueOf("Bearer omitted"); SettableRefreshable<AtlasDbRuntimeConfig> refreshableRuntimeConfig = Refreshable.create(mockAtlasDbRuntimeConfig); Refreshable<List<TimeLockClientFeedbackService>> timeLockClientFeedbackServices = TransactionManagers.getTimeLockClientFeedbackServices( config, refreshableRuntimeConfig, USER_AGENT, DialogueClients.create(Refreshable.only(ServicesConfigBlock.builder().build()))); ConjureTimeLockClientFeedback feedbackReport = ConjureTimeLockClientFeedback .builder() .atlasVersion("1.0") .serviceName("service") .nodeId(UUID.randomUUID()) .build(); assertThat(timeLockClientFeedbackServices.current().size()).isEqualTo(1); timeLockClientFeedbackServices.current().get(0).reportFeedback(authHeader, feedbackReport); List<LoggedRequest> requests = findAll(postRequestedFor(urlMatching(FEEDBACK_PATH))); assertThat(requests.size()).isEqualTo(1); availableServer.verify(postRequestedFor(urlMatching(FEEDBACK_PATH)) .withHeader("Authorization", WireMock.containing("Bearer omitted"))); timeLockRuntimeConfig = getTimelockRuntimeConfig(ImmutableList.of()); mockAtlasDbRuntimeConfig = mock(AtlasDbRuntimeConfig.class); when(mockAtlasDbRuntimeConfig.timelockRuntime()).thenReturn(Optional.of(timeLockRuntimeConfig)); refreshableRuntimeConfig.update(mockAtlasDbRuntimeConfig); assertThat(timeLockClientFeedbackServices.current().size()).isEqualTo(0); }
Source:
public void shutdown() { Awaitility.await().atMost(30, TimeUnit.SECONDS).pollInterval(3, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { Unirest.post(String.format("http://%s:4242/cluster/shutdown", crateMesosFrameworkHostIp)).asJson(); } catch (UnirestException e) { } return 0 == crateNodesCount(); } }); }

Target:
public void shutdown() { Awaitility.await().atMost(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS) .pollInterval(3, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { Unirest.post( String.format("http://%s:%d/cluster/shutdown", crateMesosFrameworkHostIp, API_PORT) ).asJson(); } catch (UnirestException e) { } return 0 == crateNodesCount(); } }); }
Source:
public void getOwnedTicketsAndFromTeamMembersNull() { thrown.expect(UserNotFoundException.class); thrown.expectMessage("could not find user 'null'."); ticketService.getOwnedTicketsAndFromTeamMembers(null); }

Target:
public void getOwnedTicketsAndFromTeamMembersNull() { thrown.expect(IllegalArgumentException.class); ticketService.getOwnedTicketsAndFromTeamMembers(null); }
Source:
public void before() { writer = new StringWriter(); delegate = new HtmlDocumentBuilder(writer); delegate.setEmitAsDocument(false); builder = new HtmlSubsetDocumentBuilder(delegate); builder.setSupportedBlockTypes(Sets.newHashSet(BlockType.PARAGRAPH)); builder.setSupportedSpanTypes(Sets.newHashSet(SpanType.BOLD), Collections.<SpanHtmlElementStrategy> emptyList(), ImmutableMap.<SpanType, String> of()); builder.setSupportedHeadingLevel(3); builder.beginDocument(); }

Target:
public void before() { writer = new StringWriter(); delegate = new HtmlDocumentBuilder(writer); delegate.setEmitAsDocument(false); builder = new HtmlSubsetDocumentBuilder(delegate); builder.setSupportedBlockTypes(Sets.newHashSet(BlockType.PARAGRAPH)); builder.setSupportedSpanTypes(Sets.newHashSet(SpanType.BOLD), Collections.<SpanHtmlElementStrategy> emptyList()); builder.setSupportedHeadingLevel(3); builder.beginDocument(); }
Source:
private void renderChunksOpaque() { PerformanceMonitor.startActivity("Render Chunks (Opaque)"); renderChunk(renderQueues.chunksOpaque, ChunkMesh.RenderPhase.OPAQUE, playerCamera, ChunkRenderMode.DEFAULT); PerformanceMonitor.endActivity(); }

Target:
private void renderChunksOpaque() { PerformanceMonitor.startActivity("Render Chunks (Opaque)"); renderChunks(renderQueues.chunksOpaque, ChunkMesh.RenderPhase.OPAQUE, playerCamera, ChunkRenderMode.DEFAULT); PerformanceMonitor.endActivity(); }
Source:
void setKey(Input newInput, char newKeyChar) { this.input = newInput; this.keyChar = newKeyChar; }

Target:
protected void setKey(Input newInput, char newKeyChar) { this.input = newInput; this.keyChar = newKeyChar; }
Source:
public ItemStack onItemUseFinish(ItemStack stack, World world, LivingEntity player) { if(player instanceof PlayerEntity && !player.world.isRemote) { Random ran = new Random(); ItemStack[] items = new ItemStack[]{new ItemStack(Items.MELON_SLICE), new ItemStack(Items.STICK), new ItemStack(Items.EGG), new ItemStack(Blocks.DIRT), new ItemStack(Blocks.PUMPKIN), new ItemStack(Blocks.COBBLESTONE)}; int num = ran.nextInt(items.length); ((PlayerEntity) player).inventory.addItemStackToInventory(items[num].copy()); ITextComponent message = new TranslationTextComponent(getTranslationKey() + ".message", items[num].getDisplayName()); message.getStyle().setColor(TextFormatting.GOLD); player.sendMessage(message); } return super.onItemUseFinish(stack, world, player); }

Target:
public ItemStack onItemUseFinish(ItemStack stack, World world, LivingEntity player) { if(player instanceof PlayerEntity && !player.world.isRemote) { Random ran = new Random(); ItemStack[] items = new ItemStack[]{new ItemStack(Items.MELON_SLICE), new ItemStack(Items.STICK), new ItemStack(Items.EGG), new ItemStack(Blocks.DIRT), new ItemStack(Blocks.PUMPKIN), new ItemStack(Blocks.COBBLESTONE)}; int num = ran.nextInt(items.length); if(!((PlayerEntity) player).inventory.addItemStackToInventory(items[num].copy())) if(!world.isRemote) ((PlayerEntity) player).dropItem(items[num].copy(), false); ITextComponent message = new TranslationTextComponent(getTranslationKey() + ".message", items[num].getDisplayName()); message.getStyle().setColor(TextFormatting.GOLD); player.sendMessage(message); } return super.onItemUseFinish(stack, world, player); }
Source:
public void onInstanceConfigChange(List<InstanceConfig> instanceConfigs, NotificationContext context) { _instanceConfigs = instanceConfigs; }

Target:
public synchronized void onInstanceConfigChange(List<InstanceConfig> instanceConfigs, NotificationContext context) { if (context.getType() == NotificationContext.Type.INIT) { _listenerInitiated = true; } if(_lastEventTimestamp > context.getCreationTime()) { LOGGER.warn("RECEIVED OUT OF ORDER EVENT"); } if (_lastEventTimestamp <= context.getCreationTime()) { _instanceConfigs = instanceConfigs; _lastEventTimestamp = context.getCreationTime(); } }
Source:
private GraphQLObjectType buildConnectionObject(Class<?> entityClass) { if (connectionObjectRegistry.containsKey(entityClass)) { return connectionObjectRegistry.get(entityClass); } String relationName = dictionary.getJsonAliasFor(entityClass); GraphQLObjectType connectionObject = newObject() .name(relationName) .field(newFieldDefinition() .name("edges") .dataFetcher(dataFetcher) .type(buildEdgesObject(relationName, buildQueryObject(entityClass)))) .field(newFieldDefinition() .name("pageInfo") .dataFetcher(dataFetcher) .type(pageInfoObject)) .build(); connectionObjectRegistry.put(entityClass, connectionObject); return connectionObject; }

Target:
private GraphQLObjectType buildConnectionObject(Class<?> entityClass) { if (connectionObjectRegistry.containsKey(entityClass)) { return connectionObjectRegistry.get(entityClass); } String entityName = dictionary.getJsonAliasFor(entityClass); GraphQLObjectType connectionObject = newObject() .name(entityName) .field(newFieldDefinition() .name("edges") .dataFetcher(dataFetcher) .type(buildEdgesObject(entityName, buildQueryObject(entityClass)))) .field(newFieldDefinition() .name("pageInfo") .dataFetcher(dataFetcher) .type(pageInfoObject)) .build(); connectionObjectRegistry.put(entityClass, connectionObject); return connectionObject; }
Source:
public <T> T data(Class<T> type) { ArgChecker.notNull(type, "type"); Object result = additionalData.get(type); if (result == null) { throw new IllegalArgumentException("Unknown type: " + type.getName()); } return type.cast(result); }

Target:
public <T> T data(Class<T> type) { ArgChecker.notNull(type, "type"); @SuppressWarnings("unchecked") T result = (T) additionalData.get(type); if (result == null) { throw new IllegalArgumentException("Unknown type: " + type.getName()); } return result; }
Source:
public String verse(int verseNumber) { return constructVerse(verseNumber); }

Target:
public String verse(int verseNumber) { StringBuilder stringBuilder = new StringBuilder("On the " + days[verseNumber - 1] + " day of Christmas my true love gave to me, "); for (int i = verseNumber; i > 0; i--) { if (verseNumber != 1 && i == 1) stringBuilder.append("and "); stringBuilder.append(gifts[i - 1]); } stringBuilder.append("\n"); return stringBuilder.toString(); }
Source:
private boolean arrayMatched(JSONArray value) { if (value.isEmpty() && "[]".equals(getExpectedValue())) { return true; } boolean foundMatch = Arrays.stream(value.toArray()) .anyMatch(subj -> (subj == null && isExpectNull()) || isEquals(subj)); return foundMatch || isEquals(value); }

Target:
private boolean arrayMatched(JSONArray value) { if (value.isEmpty() && "[]".equals(getExpectedValue())) { return true; } for (Object subj : value.toArray()) { if ((subj == null && isExpectNull()) || isEquals(subj)) { return true; } } return isEquals(value); }
Source:
public void csvWithNoFieldsShouldReturnNull() { DefaultCSVMetaDataBuilder builder = new DefaultCSVMetaDataBuilder(); CSVMetaDataModel model = builder.setDelimiter(",").build(); Assert.assertThat(model, CoreMatchers.nullValue()); }

Target:
public void csvWithNoFieldsShouldReturnNull() { DefaultCSVMetaDataBuilder builder = new DefaultCSVMetaDataBuilder(); CSVMetaDataModel model = builder.setDelimiter(COMMA_DELIMITER).build(); assertThat(model, nullValue()); }
Source:
public void execute(SensorContext context) { System.out.println("EXECUTE DA SENSOR"); javaResourceLocator.setSensorContext(context); sonarComponents.setSensorContext(context); sonarComponents.registerCheckClasses(CheckList.REPOSITORY_KEY, CheckList.getJavaChecks()); sonarComponents.registerTestCheckClasses(CheckList.REPOSITORY_KEY, CheckList.getJavaTestChecks()); JavaConfiguration configuration = createConfiguration(); Measurer measurer = new Measurer(fs, context, noSonarFilter); JavaSquid squid = new JavaSquid(configuration, sonarComponents, measurer, javaResourceLocator, postAnalysisIssueFilter, sonarComponents.checkClasses()); squid.scan(getSourceFiles(), getTestFiles()); }

Target:
public void execute(SensorContext context) { System.out.println("EXECUTE DA SENSOR"); System.out.println("EXECUTE DA SENSOR, FOR REAL"); javaResourceLocator.setSensorContext(context); sonarComponents.setSensorContext(context); sonarComponents.registerCheckClasses(CheckList.REPOSITORY_KEY, CheckList.getJavaChecks()); sonarComponents.registerTestCheckClasses(CheckList.REPOSITORY_KEY, CheckList.getJavaTestChecks()); JavaConfiguration configuration = createConfiguration(); Measurer measurer = new Measurer(fs, context, noSonarFilter); JavaSquid squid = new JavaSquid(configuration, sonarComponents, measurer, javaResourceLocator, postAnalysisIssueFilter, sonarComponents.checkClasses()); squid.scan(getSourceFiles(), getTestFiles()); }
Source:
public void connectionCreated(final ActiveMQComponent component, final Connection connection, final ProtocolManager protocol) { if (server == null) { throw new IllegalStateException("Unable to create connection, server hasn't finished starting up"); } ConnectionEntry entry = protocol.createConnectionEntry((Acceptor) component, connection); try { server.callBrokerPlugins(server.hasBrokerPlugins() ? plugin -> plugin.afterCreateConnection(entry.connection) : null); } catch (Exception e) { throw new IllegalStateException("Error executing afterCreateConnection plugin method: " + e.getMessage(), e); } if (logger.isTraceEnabled()) { logger.trace("Connection created " + connection); } connections.put(connection.getID(), entry); connectionCountLatch.countUp(); totalConnectionCount.incrementAndGet(); }

Target:
public void connectionCreated(final ActiveMQComponent component, final Connection connection, final ProtocolManager protocol) { if (server == null) { throw new IllegalStateException("Unable to create connection, server hasn't finished starting up"); } ConnectionEntry entry = protocol.createConnectionEntry((Acceptor) component, connection); try { server.callBrokerPlugins(server.hasBrokerPlugins() ? plugin -> plugin.afterCreateConnection(entry.connection) : null); } catch (Throwable t) { logger.warn("Error executing afterCreateConnection plugin method: {}", t.getMessage(), t); } if (logger.isTraceEnabled()) { logger.trace("Connection created " + connection); } connections.put(connection.getID(), entry); connectionCountLatch.countUp(); totalConnectionCount.incrementAndGet(); }
Source:
public OutputStream prepareForRecords( OutputStream out, final SAMFormat format, final SAMFileHeader header) throws IOException { switch (format) { case BAM: prepareBAMStream(out, format, header); break; case CRAM: prepareCRAMStream(out, format, header); break; default: throw new IllegalArgumentException("Unsupported SAM file format, must be one of BAM or CRAM"); } out.flush(); return out; }

Target:
public OutputStream prepareForRecords( OutputStream out, final SAMFormat format, final SAMFileHeader header) throws IOException { switch (format) { case SAM: out = prepareSAMOrBAMStream(out, format, header); break; case BAM: out = prepareSAMOrBAMStream(out, format, header); break; case CRAM: out = prepareCRAMStream(out, format, header); break; default: throw new IllegalArgumentException ("Unsupported SAM file format, must be one of SAM, BAM or CRAM"); } out.flush(); return out; }
Source:
protected IFile findFileInWorkspace(IPath path) { URI uri; if (!path.isAbsolute()) { URI workingDirectoryURI = getWorkingDirectoryURI(); uri = EFSExtensionManager.getDefault().append(workingDirectoryURI, path.toString()); } else { uri = toURI(path); if (uri == null) return null; } return findFileInWorkspace(uri); }

Target:
protected IFile findFileInWorkspace(IPath path) { URI uri; if (!path.isAbsolute()) { URI workingDirectoryURI = getWorkingDirectoryURI(); uri = EFSExtensionManager.getDefault().append(workingDirectoryURI, path.toString()); } else { uri = toURI(path); if (uri == null) { return null; } } return findFileInWorkspace(uri); }
Source:
public AccessPoint getAccessPoint(String ssid) throws XBeeException { logger.debug("{}AS for '{}' access point.", toString(), ssid); List<AccessPoint> accessPointsList = discoverAccessPoints(); for (AccessPoint accessPoint:accessPointsList) { if (accessPoint.getSSID().equals(ssid)) return accessPoint; } return null; }

Target:
public AccessPoint getAccessPoint(String ssid) throws XBeeException { if (ssid == null) throw new NullPointerException("SSID cannot be null."); logger.debug("{}AS for '{}' access point.", toString(), ssid); List<AccessPoint> accessPointsList = discoverAccessPoints(); for (AccessPoint accessPoint:accessPointsList) { if (accessPoint.getSSID().equals(ssid)) return accessPoint; } return null; }
Source:
public URI build() { try { StringBuilder queryBuilder = new StringBuilder(encodeQuery(query.toString())); for (int i = 0; i < qParams.size(); i++) { String amp = (i != qParams.size() - 1) ? "&" : ""; String param; String queryParam = qParams.get(i); int firstEqualsIndex = queryParam.indexOf('='); if (firstEqualsIndex != -1 && firstEqualsIndex < queryParam.length() - 1) { String encodedKey = encodeQueryParameter(queryParam.substring(0, firstEqualsIndex)); String encodedValue = encodeQueryParameter(queryParam.substring(firstEqualsIndex + 1)); param = String.format("%s=%s", encodedKey, encodedValue); } else { param = qParams.get(i); } queryBuilder.append(param + amp); } String q = (queryBuilder.length() == 0) ? "" : "?" + queryBuilder.toString(); String uriString = String.format("%s://%s:%s%s%s", scheme, host, port, path, q); return new URI(uriString); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }

Target:
public URI build() { try { StringBuilder queryBuilder; if (query.length() > 0) { queryBuilder = new StringBuilder(encodeQuery(query.toString())); } else { queryBuilder = new StringBuilder(); } for (int i = 0; i < qParams.size(); i++) { String amp = (i != qParams.size() - 1) ? "&" : ""; queryBuilder.append(qParams.get(i).toURLEncodedString() + amp); } String q = (queryBuilder.length() == 0) ? "" : "?" + queryBuilder.toString(); String uriString = String.format("%s://%s:%s%s%s", scheme, host, port, path, q); return new URI(uriString); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
public void broadcastNote(Note note) { broadcast(note.getId(), new Message(OP.NOTE).put("note", note)); broadcastToWatchers(note.getId(), "", new Message(OP.NOTE).put("note", note)); }

Target:
public void broadcastNote(Note note) { broadcast(note.getId(), new Message(OP.NOTE).put("note", note)); }
Source:
private Set<String> expandRegionalChannelUris(String channelUri) { Set<String> expandedUris = null; if (BBC1_TXLOG_CHANNEL_URIS.contains(channelUri)) { expandedUris = BBC1_TXLOG_CHANNEL_URIS; } if (BBC2_TXLOG_CHANNEL_URIS.contains(channelUri)) { expandedUris = BBC2_TXLOG_CHANNEL_URIS; } return expandedUris == null ? null : Sets.difference(expandedUris, ImmutableSet.of(channelUri)); }

Target:
private Set<String> expandRegionalChannelUris(String channelUri) { if (BBC1_TXLOG_CHANNEL_URIS.contains(channelUri)) { return Sets.difference(BBC1_TXLOG_CHANNEL_URIS, ImmutableSet.of(channelUri)); } else if (BBC2_TXLOG_CHANNEL_URIS.contains(channelUri)) { return Sets.difference(BBC2_TXLOG_CHANNEL_URIS, ImmutableSet.of(channelUri)); } return null; }
Source:
BackupResult doBackupSession( final MemcachedBackupSession session, final byte[] data, final byte[] attributesData ) { if ( _log.isDebugEnabled() ) { _log.debug( "Trying to store session in memcached: " + session.getId() ); } try { storeSessionInMemcached( session, data ); return new BackupResult( BackupResultStatus.SUCCESS, data, attributesData ); } catch (final IOException e) { handleException(session, e); return new BackupResult(BackupResultStatus.FAILURE, data, null); } }

Target:
BackupResult doBackupSession( final MemcachedBackupSession session, final byte[] data, final byte[] attributesData ) throws InterruptedException { if ( _log.isDebugEnabled() ) { _log.debug( "Trying to store session in memcached: " + session.getId() ); } try { storeSessionInMemcached( session, data ); return new BackupResult( BackupResultStatus.SUCCESS, data, attributesData ); } catch (final ExecutionException e) { handleException(session, e); return new BackupResult(BackupResultStatus.FAILURE, data, null); } catch (final TimeoutException e) { handleException(session, e); return new BackupResult(BackupResultStatus.FAILURE, data, null); } }
Source:
private NettyServer getNettyServer(Properties properties) throws InstantiationException, IOException { if (properties == null) { properties = new Properties(); } VerifiableProperties verifiableProperties = new VerifiableProperties(properties); final NettyConfig nettyConfig = new NettyConfig(verifiableProperties); final NettyMetrics nettyMetrics = new NettyMetrics(new MetricRegistry()); final RestRequestHandler requestHandler = new MockRestRequestResponseHandler(); final PublicAccessLogger publicAccessLogger = new PublicAccessLogger(new String[]{}, new String[]{}); final RestServerState restServerState = new RestServerState("/healthCheck"); return new NettyServer(nettyConfig, nettyMetrics, new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline() .addLast("ConnectionStatsHandler", new ConnectionStatsHandler(nettyMetrics)) .addLast("codec", new HttpServerCodec()) .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics)) .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics)) .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds)) .addLast("chunker", new ChunkedWriteHandler()) .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler)); } }); }

Target:
private NettyServer getNettyServer(Properties properties) throws InstantiationException, IOException { if (properties == null) { properties = new Properties(); } VerifiableProperties verifiableProperties = new VerifiableProperties(properties); final NettyConfig nettyConfig = new NettyConfig(verifiableProperties); final NettyMetrics nettyMetrics = new NettyMetrics(new MetricRegistry()); final RestRequestHandler requestHandler = new MockRestRequestResponseHandler(); final PublicAccessLogger publicAccessLogger = new PublicAccessLogger(new String[]{}, new String[]{}); final RestServerState restServerState = new RestServerState("/healthCheck"); return new NettyServer(nettyConfig, nettyMetrics, new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline() .addLast("ConnectionStatsHandler", ConnectionStatsHandler.getInstance(nettyMetrics)) .addLast("codec", new HttpServerCodec()) .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics)) .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics)) .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds)) .addLast("chunker", new ChunkedWriteHandler()) .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler)); } }); }
Source:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MICROSECONDS); this.listening = false; } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } }

Target:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MICROSECONDS); } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } finally { this.listening = false; } }
Source:
protected EventSourcedAggregate<T> doLoadWithLock(String aggregateIdentifier, Long expectedVersion) { DomainEventStream eventStream = DomainEventStream.filter(eventStore.readEvents(aggregateIdentifier), e -> e.getType().equals(aggregateModel().type())); SnapshotTrigger trigger = snapshotTriggerDefinition.prepareTrigger(aggregateFactory.getAggregateType()); if (!eventStream.hasNext()) { throw new AggregateNotFoundException(aggregateIdentifier, "The aggregate was not found in the event store"); } EventSourcedAggregate<T> aggregate = EventSourcedAggregate .initialize(aggregateFactory.createAggregateRoot(aggregateIdentifier, eventStream.peek()), aggregateModel(), eventStore, trigger); aggregate.initializeState(eventStream); if (aggregate.isDeleted()) { throw new AggregateDeletedException(aggregateIdentifier); } return aggregate; }

Target:
protected EventSourcedAggregate<T> doLoadWithLock(String aggregateIdentifier, Long expectedVersion) { DomainEventStream eventStream = readEvents(aggregateIdentifier); SnapshotTrigger trigger = snapshotTriggerDefinition.prepareTrigger(aggregateFactory.getAggregateType()); if (!eventStream.hasNext()) { throw new AggregateNotFoundException(aggregateIdentifier, "The aggregate was not found in the event store"); } EventSourcedAggregate<T> aggregate = EventSourcedAggregate .initialize(aggregateFactory.createAggregateRoot(aggregateIdentifier, eventStream.peek()), aggregateModel(), eventStore, repositoryProvider, trigger); aggregate.initializeState(eventStream); if (aggregate.isDeleted()) { throw new AggregateDeletedException(aggregateIdentifier); } return aggregate; }
Source:
protected void queuePersistedMessages( final ServerSession serverSession, List<Map<String, Object>> messages, final String topic) { for (Map<String, Object> notification : messages) { final Map<String, Object> propMap = new HashMap<>(); propMap.putAll(notification); executorService.submit( new Runnable() { @Override public void run() { int maxAttempts = 10; int attempts = 0; while (!serverSession.isConnected() && attempts < maxAttempts) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } attempts++; LOGGER.trace( "Attempt of to send notifications back to client.", attempts, maxAttempts); } LOGGER.trace("Sending notifications back to client."); serverSession.deliver(controllerServerSession, topic, propMap); } }); } }

Target:
protected void queuePersistedMessages( final ServerSession serverSession, List<Map<String, Object>> messages, final String topic) { for (Map<String, Object> notification : messages) { final Map<String, Object> propMap = new HashMap<>(); propMap.putAll(notification); executorService.submit( new Runnable() { @Override public void run() { int maxAttempts = 10; int attempts = 0; while (!serverSession.isConnected() && attempts < maxAttempts) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { } attempts++; LOGGER.trace( "Attempt of to send notifications back to client.", attempts, maxAttempts); } LOGGER.trace("Sending notifications back to client."); serverSession.deliver(controllerServerSession, topic, propMap); } }); } }
Source:
public Map<K, ValueHolder<V>> bulkComputeIfAbsent(Iterable<? extends K> keys, final Function<Iterable<? extends K>, Iterable<? extends Map.Entry<? extends K, ? extends V>>> mappingFunction) throws CacheAccessException { Set<K> presentKeys = new HashSet<K>(); Set<K> missingKeys = new HashSet<K>(); for (K key : keys) { if (map.containsKey(key)) { presentKeys.add(key); } else { missingKeys.add(key); } } Map<K, ValueHolder<V>> result = new HashMap<K, ValueHolder<V>>(); for (final K key : missingKeys) { final OnHeapValueHolder<V> newValue = map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(final K k, final OnHeapValueHolder<V> oldValue) { final Iterable<K> keySet = Collections.singletonMap(k, oldValue == null ? null : oldValue.value()) .keySet(); final Iterable<? extends Map.Entry<? extends K, ? extends V>> entries = mappingFunction.apply(keySet); final java.util.Iterator<? extends Map.Entry<? extends K, ? extends V>> iterator = entries.iterator(); final Map.Entry<? extends K, ? extends V> next = iterator.next(); if (!next.getKey().equals(k) || iterator.hasNext()) { throw new IllegalArgumentException("This test is wrong!"); } return nullSafeNewValueHolder(next.getKey(), next.getValue(), timeSource.getTimeMillis()); } }); result.put(key, newValue); } for (K key : presentKeys) { result.put(key, map.get(key)); } return result; }

Target:
public Map<K, ValueHolder<V>> bulkComputeIfAbsent(Iterable<? extends K> keys, final Function<Iterable<? extends K>, Iterable<? extends Map.Entry<? extends K, ? extends V>>> mappingFunction) throws CacheAccessException { Map<K, ValueHolder<V>> result = new HashMap<K, ValueHolder<V>>(); Set<K> missingKeys = new HashSet<K>(); for (K key : keys) { checkKey(key); ValueHolder<V> value = get(key); if (value != null) { result.put(key, value); } else { missingKeys.add(key); } } for (final K key : missingKeys) { final OnHeapValueHolder<V> newValue = map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(final K k, final OnHeapValueHolder<V> oldValue) { final Iterable<K> keySet = Collections.singleton(k); final Iterable<? extends Map.Entry<? extends K, ? extends V>> entries = mappingFunction.apply(keySet); final java.util.Iterator<? extends Map.Entry<? extends K, ? extends V>> iterator = entries.iterator(); final Map.Entry<? extends K, ? extends V> next = iterator.next(); return nullSafeNewValueHolder(next.getKey(), next.getValue(), timeSource.getTimeMillis()); } }); result.put(key, newValue); } return result; }
Source:
public String getManufacturer() { String localRef = this.manufacturer; if (localRef == null) { synchronized (this) { localRef = this.manufacturer; if (localRef == null) { if (!queryManufacturerFromSysfs() && !queryManufacturerFromProcCpu()) { this.manufacturer = Constants.UNKNOWN; } localRef = this.manufacturer; } } } return localRef; }

Target:
public String getManufacturer() { return manufacturer.get(); }
Source:
public boolean filterRowKey(Cell cell) { if(cell == null) { return true; } Txn.State state = Txn.State.decode(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); return state != Txn.State.ACTIVE; }

Target:
public boolean filterRowKey(Cell cell) { return false; }
Source:
public void run(MintConfiguration configuration, Environment environment) throws Exception { DBIFactory dbiFactory = new DBIFactory(); DBI jdbi = dbiFactory.build(environment, configuration.getDatabase(), "postgres"); RegistersConfiguration registersConfiguration = new RegistersConfiguration(Optional.ofNullable(System.getProperty("registersYaml"))); FieldsConfiguration fieldsConfiguration = new FieldsConfiguration(Optional.ofNullable(System.getProperty("fieldsYaml"))); EntryValidator entryValidator = new EntryValidator(registersConfiguration, fieldsConfiguration); LoadHandler loadHandler = new LoadHandler(configuration.getRegister(), jdbi.onDemand(EntriesUpdateDAO.class), entryValidator); final Client client = new JerseyClientBuilder(environment) .using(configuration.getJerseyClientConfiguration()) .build(getName()); if(client == null && StringUtils.isNotBlank(configuration.getCTServer())) { throw new RuntimeException("Failed to create Jersey client"); } CTHandler ctHandler = new CTHandler(configuration.getRegister(), configuration.getCTServer(), client, entryValidator); List<Handler> handlers = new ArrayList<Handler>(); handlers.add(loadHandler); handlers.add(ctHandler); JerseyEnvironment jersey = environment.jersey(); jersey.register(new MintService(handlers)); jersey.register(EntryValidationExceptionMapper.class); jersey.register(JsonParseExceptionMapper.class); jersey.register(ThrowableExceptionMapper.class); configuration.getAuthenticator().build() .ifPresent(authenticator -> jersey.register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(authenticator) .buildAuthFilter() )) ); }

Target:
public void run(MintConfiguration configuration, Environment environment) throws Exception { DBIFactory dbiFactory = new DBIFactory(); DBI jdbi = dbiFactory.build(environment, configuration.getDatabase(), "postgres"); RegistersConfiguration registersConfiguration = new RegistersConfiguration(Optional.ofNullable(System.getProperty("registersYaml"))); FieldsConfiguration fieldsConfiguration = new FieldsConfiguration(Optional.ofNullable(System.getProperty("fieldsYaml"))); EntryValidator entryValidator = new EntryValidator(registersConfiguration, fieldsConfiguration); ObjectReconstructor objectReconstructor = new ObjectReconstructor(); Loader handler; if (StringUtils.isNotEmpty(configuration.getCTServer())) { handler = new CTHandler(configuration, environment, getName()); } else { handler = new LoadHandler(jdbi.onDemand(EntriesUpdateDAO.class)); } JerseyEnvironment jersey = environment.jersey(); jersey.register(new MintService(configuration.getRegister(), objectReconstructor, entryValidator, handler)); jersey.register(CTExceptionMapper.class); jersey.register(EntryValidationExceptionMapper.class); jersey.register(JsonParseExceptionMapper.class); jersey.register(ThrowableExceptionMapper.class); configuration.getAuthenticator().build() .ifPresent(authenticator -> jersey.register(new AuthDynamicFeature( new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(authenticator) .buildAuthFilter() )) ); }
Source:
public void manage(Entity e) { if (isManaged(e)) { log.warn(""+this+" redundant call to start management of entity (and descendants of) "+e+"; skipping", new Exception("source of duplicate management of "+e)); return; } AccessController.Response access = managementContext.getAccessController().canManageEntity(e); if (!access.isAllowed()) { throw new IllegalStateException("Access controller forbids management of "+e+": "+access.getMsg()); } final ManagementTransitionInfo info = new ManagementTransitionInfo(managementContext, ManagementTransitionMode.NORMAL); final List<EntityInternal> allEntities = Lists.newArrayList(); recursively(e, new Predicate<EntityInternal>() { public boolean apply(EntityInternal it) { if (it.getManagementSupport().isDeployed()) { return false; } else { allEntities.add(it); preManageNonRecursive(it); it.getManagementSupport().onManagementStarting(info); return manageNonRecursive(it); } } }); for (EntityInternal it : allEntities) { if (!it.getManagementSupport().isFullyManaged()) { it.getManagementSupport().onManagementStarted(info); managementContext.getRebindManager().getChangeListener().onManaged(it); } }; }

Target:
public void manage(Entity e) { if (isManaged(e)) { log.warn(""+this+" redundant call to start management of entity (and descendants of) "+e+"; skipping", new Exception("source of duplicate management of "+e)); return; } AccessController.Response access = managementContext.getAccessController().canManageEntity(e); if (!access.isAllowed()) { throw new IllegalStateException("Access controller forbids management of "+e+": "+access.getMsg()); } final ManagementTransitionInfo info = new ManagementTransitionInfo(managementContext, ManagementTransitionMode.NORMAL); final List<EntityInternal> allEntities = Lists.newArrayList(); recursively(e, new Predicate<EntityInternal>() { public boolean apply(EntityInternal it) { if (it.getManagementSupport().isDeployed()) { return false; } else { allEntities.add(it); preManageNonRecursive(it); it.getManagementSupport().onManagementStarting(info); return manageNonRecursive(it); } } }); for (EntityInternal it : allEntities) { if (!it.getManagementSupport().isFullyManaged()) { it.getManagementSupport().onManagementStarted(info); managementContext.getRebindManager().getChangeListener().onManaged(it); } } }