auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void configureSSLEngine() { SSLConfig config = new SSLConfig.Builder().setCiphers("someCipher").setEnabled(true) .setProtocols("someProtocol").setRequireAuth(true).setKeystore("someKeystore.jks") .setAlias("someAlias").setTruststore("someTruststore.jks") .setEndpointIdentificationEnabled(true).build(); SSLContext context = mock(SSLContext.class); SSLParameters parameters = mock(SSLParameters.class); SocketCreator socketCreator = new SocketCreator(config, context); SSLEngine engine = mock(SSLEngine.class); when(engine.getSSLParameters()).thenReturn(parameters); engine.setEnableSessionCreation(true); socketCreator.configureSSLEngine(engine, "somehost", 12345, true); verify(engine).setUseClientMode(isA(Boolean.class)); verify(engine).setSSLParameters(parameters); verify(engine).setEnabledCipherSuites(isA(String[].class)); verify(engine).setEnabledProtocols(isA(String[].class)); verify(engine, never()).setNeedClientAuth(isA(Boolean.class)); }

Target:
public void configureSSLEngine() { SSLConfig config = new SSLConfig.Builder().setCiphers("someCipher").setEnabled(true) .setProtocols("someProtocol").setRequireAuth(true).setKeystore("someKeystore.jks") .setAlias("someAlias").setTruststore("someTruststore.jks") .setEndpointIdentificationEnabled(true).build(); SSLContext context = mock(SSLContext.class); SSLParameters parameters = mock(SSLParameters.class); SocketCreator socketCreator = new SocketCreator(config, context); SSLEngine engine = mock(SSLEngine.class); when(engine.getSSLParameters()).thenReturn(parameters); socketCreator.configureSSLEngine(engine, "somehost", 12345, true); verify(engine).setUseClientMode(isA(Boolean.class)); verify(engine).setSSLParameters(parameters); verify(engine, never()).setNeedClientAuth(isA(Boolean.class)); ArgumentCaptor<String[]> stringArrayCaptor = ArgumentCaptor.forClass(String[].class); verify(engine).setEnabledProtocols(stringArrayCaptor.capture()); assertThat(stringArrayCaptor.getValue()).containsExactly("someProtocol"); verify(engine).setEnabledCipherSuites(stringArrayCaptor.capture()); assertThat(stringArrayCaptor.getValue()).containsExactly("someCipher"); }
Source:
protected Block computeSpan(SpanType type, Attributes attributes) { switch (type) { case LINK: if (attributes instanceof LinkAttributes) { return new LinkBlock((LinkAttributes) attributes); } else { return new ContentBlock("<", ">"); } case ITALIC: case EMPHASIS: return new ContentBlock("*", "*"); case BOLD: case STRONG: return new ContentBlock("**", "**"); case CODE: return new CodeSpan(); default: Logger.getLogger(getClass().getName()).warning("Unexpected block type: " + type); return new ContentBlock("", ""); } }

Target:
protected Block computeSpan(SpanType type, Attributes attributes) { switch (type) { case LINK: if (attributes instanceof LinkAttributes) { return new LinkBlock((LinkAttributes) attributes); } return new ContentBlock("<", ">"); case ITALIC: case EMPHASIS: return new ContentBlock("*", "*"); case BOLD: case STRONG: return new ContentBlock("**", "**"); case CODE: return new CodeSpan(); default: Logger.getLogger(getClass().getName()).warning("Unexpected block type: " + type); return new ContentBlock("", ""); } }
Source:
static Options processSpecialOptionKey(Options options, Enum<?> specialOptionKey) { if (specialOptionKey != null && options.containsKey(specialOptionKey)) { final TermFilter termFilter = options.get(specialOptionKey, TermFilter.class); String specialOption = termFilter.getTerm(); if (specialOption != null && specialOption.startsWith(SPECIAL_OPTION_CHARACTER) && specialOption.endsWith(")")) { String fieldAndValueWithParenSeparator = specialOption.substring(1, specialOption.length() - 1); int separatorIdx = fieldAndValueWithParenSeparator.indexOf("("); if (separatorIdx != -1) { String field = fieldAndValueWithParenSeparator.substring(0, separatorIdx).toUpperCase(); String value = fieldAndValueWithParenSeparator.substring(separatorIdx + 1); if (!CompareUtils.isEmpty(field) && !CompareUtils.isEmpty(value)) { OptionsBuilder newOptions = Options.builder(); if (specialOptionKey.name().equals(field)) { newOptions.put(field, TermFilter.builder(termFilter).term(value)); } else { newOptions.put(field, value); } for (String key : options.keySet()) { if (!specialOptionKey.name().equals(key)) { newOptions.put(key, options.get(key)); } } return newOptions.build(); } } } } return options; }

Target:
static Options processSpecialOptionKey(Options options, Enum<?> specialOptionKey) { return processSpecialOptionKey(options, specialOptionKey, Options::getString); }
Source:
public void start() { notifierThread = Execs.makeThread( threadName, () -> { while (!Thread.interrupted()) { try { logger.debug("Waiting for cache update notification"); Set<String> itemsToUpdateSnapshot; HashMap<String, byte[]> serializedMapsSnapshot; synchronized (itemsToUpdate) { if (itemsToUpdate.isEmpty()) { itemsToUpdate.wait(); } itemsToUpdateSnapshot = new HashSet<>(itemsToUpdate); serializedMapsSnapshot = new HashMap<String, byte[]>(serializedMaps); itemsToUpdate.clear(); serializedMaps.clear(); } logger.debug("Sending cache update notifications"); for (String authorizer : itemsToUpdateSnapshot) { BasicAuthDBConfig authorizerConfig = itemConfigMap.get(authorizer); if (!authorizerConfig.isEnableCacheNotifications()) { continue; } List<ListenableFuture<StatusResponseHolder>> futures = sendUpdate( authorizer, serializedMapsSnapshot.get(authorizer) ); for (ListenableFuture<StatusResponseHolder> future : futures) { try { StatusResponseHolder srh = future.get( authorizerConfig.getCacheNotificationTimeout(), TimeUnit.MILLISECONDS ); logger.debug("Got status: " + srh.getStatus()); } catch (Exception e) { logger.makeAlert(e, "Failed to get response for cache notification.").emit(); } } } logger.debug("Received responses for cache update notifications."); } catch (Throwable t) { logger.makeAlert(t, "Error occured while handling updates for cachedUserMaps.").emit(); } } }, true ); notifierThread.start(); }

Target:
public void start() { exec.submit( () -> { while (!Thread.interrupted()) { try { LOG.debug(callerName + ":Waiting for cache update notification"); Pair<String, byte[]> update = updateQueue.take(); String authorizer = update.lhs; byte[] serializedMap = update.rhs; BasicAuthDBConfig authorizerConfig = itemConfigMap.get(update.lhs); if (!authorizerConfig.isEnableCacheNotifications()) { continue; } LOG.debug(callerName + ":Sending cache update notifications"); List<ListenableFuture<StatusResponseHolder>> futures = sendUpdate( authorizer, serializedMap ); try { List<StatusResponseHolder> responses = Futures.allAsList(futures) .get( authorizerConfig.getCacheNotificationTimeout(), TimeUnit.MILLISECONDS ); for (StatusResponseHolder response : responses) { LOG.debug(callerName + ":Got status: " + response.getStatus()); } } catch (Exception e) { LOG.makeAlert(e, callerName + ":Failed to get response for cache notification.").emit(); } LOG.debug(callerName + ":Received responses for cache update notifications."); } catch (Throwable t) { LOG.makeAlert(t, callerName + ":Error occured while handling updates for cachedUserMaps.").emit(); } } } ); }
Source:
MasterRegistry(Configuration conf) throws IOException { this.hedgedReadFanOut = Math.max(1, conf.getInt(MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY, MASTER_REGISTRY_HEDGED_REQS_FANOUT_DEFAULT)); rpcTimeoutMs = (int) Math.min(Integer.MAX_VALUE, conf.getLong(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT)); rpcClient = RpcClientFactory.createClient(conf, null); rpcControllerFactory = RpcControllerFactory.instantiate(conf); populateMasterStubs(parseMasterAddrs(conf)); Runnable masterEndPointRefresher = () -> { while (!Thread.interrupted()) { try { synchronized (refreshMasters) { refreshMasters.wait(WAIT_TIME_OUT_MS); } LOG.debug("Attempting to refresh master address end points."); Set<ServerName> newMasters = new HashSet<>(getMasters().get()); populateMasterStubs(newMasters); LOG.debug("Finished refreshing master end points. {}", newMasters); } catch (InterruptedException e) { LOG.debug("Interrupted during wait, aborting refresh-masters-thread.", e); break; } catch (ExecutionException | IOException e) { LOG.debug("Error populating latest list of masters.", e); } } }; masterAddrRefresherThread = Threads.newDaemonThreadFactory( "MasterRegistry refresh end-points").newThread(masterEndPointRefresher); masterAddrRefresherThread.start(); }

Target:
MasterRegistry(Configuration conf) throws IOException { this.hedgedReadFanOut = Math.max(1, conf.getInt(MASTER_REGISTRY_HEDGED_REQS_FANOUT_KEY, MASTER_REGISTRY_HEDGED_REQS_FANOUT_DEFAULT)); rpcTimeoutMs = (int) Math.min(Integer.MAX_VALUE, conf.getLong(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT)); rpcClient = RpcClientFactory.createClient(conf, null); rpcControllerFactory = RpcControllerFactory.instantiate(conf); populateMasterStubs(parseMasterAddrs(conf)); masterAddressRefresher = new MasterAddressRefresher(conf, this); }
Source:
private EmbeddedCacheManager startCacheManager( EmbeddedCacheManager cacheMgr, String configFile, Boolean isCluster ) { new MarshallableTypeHints().getBufferSizePredictor( CacheHandle.class ); File confDir = indyConfiguration.getIndyConfDir(); File ispnConf = new File( confDir, configFile ); EmbeddedCacheManager mgr = cacheMgr; try(InputStream resouceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( configFile )) { String resourceStr = interpolateStrFromStream( resouceStream, "CLASSPATH:" + configFile ); if ( ispnConf.exists() ) { try (InputStream confStream = FileUtils.openInputStream( ispnConf )) { String confStr = interpolateStrFromStream( confStream, ispnConf.getPath() ); mgr = mergedCachesFromConfig( mgr, confStr, "CUSTOMER" ); mgr = mergedCachesFromConfig( mgr, resourceStr, "CLASSPATH" ); } catch ( IOException e ) { throw new RuntimeException( "Cannot read infinispan configuration from file: " + ispnConf, e ); } } else { try { logger.info( "Using CLASSPATH resource Infinispan configuration:\n\n{}\n\n", resourceStr ); mgr = new DefaultCacheManager( new ByteArrayInputStream( resourceStr.getBytes( StandardCharsets.UTF_8 ) ) ); if ( isCluster ) { mgr.startCaches( String.join( ",", clusterCacheManager.getCacheNames()) ); } } catch ( IOException e ) { throw new RuntimeException( "Failed to construct ISPN cacheManger due to CLASSPATH xml stream read error.", e ); } } } catch ( IOException e ) { throw new RuntimeException( "Failed to construct ISPN cacheManger due to CLASSPATH xml stream read error.", e ); } return mgr; }

Target:
private EmbeddedCacheManager startCacheManager( EmbeddedCacheManager cacheMgr, String configFile, Boolean isCluster ) { new MarshallableTypeHints().getBufferSizePredictor( CacheHandle.class ); File confDir = indyConfiguration.getIndyConfDir(); File ispnConf = new File( confDir, configFile ); EmbeddedCacheManager mgr = cacheMgr; try(InputStream resouceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( configFile )) { String resourceStr = interpolateStrFromStream( resouceStream, "CLASSPATH:" + configFile ); if ( ispnConf.exists() ) { try (InputStream confStream = FileUtils.openInputStream( ispnConf )) { String confStr = interpolateStrFromStream( confStream, ispnConf.getPath() ); mgr = mergedCachesFromConfig( mgr, confStr, "CUSTOMER" ); mgr = mergedCachesFromConfig( mgr, resourceStr, "CLASSPATH" ); } catch ( IOException e ) { throw new RuntimeException( "Cannot read infinispan configuration from file: " + ispnConf, e ); } } else { try { logger.info( "Using CLASSPATH resource Infinispan configuration:\n\n{}\n\n", resourceStr ); if ( mgr == null ) { mgr = new DefaultCacheManager( new ByteArrayInputStream( resourceStr.getBytes( StandardCharsets.UTF_8 ) ) ); } if ( isCluster ) { mgr.startCaches( String.join( ",", clusterCacheManager.getCacheNames() ) ); } } catch ( IOException e ) { throw new RuntimeException( "Failed to construct ISPN cacheManger due to CLASSPATH xml stream read error.", e ); } } } catch ( IOException e ) { throw new RuntimeException( "Failed to construct ISPN cacheManger due to CLASSPATH xml stream read error.", e ); } return mgr; }
Source:
public boolean hasNext() { return super.hasNext() || this.stashedStarts.peek() != null; }

Target:
public boolean hasNext() { return super.hasNext() || !this.stashedStarts.isEmpty(); }
Source:
RegisteredConsumer(EventConsumer consumer, Set<String> eventTypes) { this.consumer = consumer; this.eventTypes = unmodifiableSet(eventTypes); }

Target:
RegisteredConsumer(EventConsumer consumer, Set<String> eventTypes) { this.consumer = consumer; this.eventTypes.addAll(eventTypes); }
Source:
public void handleFlush(Object input) { TreeNodeCompareInput treeNodeCompareInput = (TreeNodeCompareInput)input; EObject eobject = treeNodeCompareInput.getComparisonObject(); Comparison comparison; if (eobject instanceof Match) { comparison = ((Match)eobject).getComparison(); } else if (eobject instanceof Diff) { comparison = ((Diff)eobject).getMatch().getComparison(); } else if (eobject instanceof MatchResource) { comparison = ((MatchResource)eobject).getComparison(); } else { return; } Predicate<Conflict> unresolvedConflict = new Predicate<Conflict>() { public boolean apply(Conflict conflict) { return conflict != null && conflict.getKind() != ConflictKind.PSEUDO && Iterables.any(conflict.getDifferences(), EMFComparePredicates .hasState(DifferenceState.UNRESOLVED)); } }; if (Iterables.any(comparison.getConflicts(), unresolvedConflict)) { mergeResolutionListenerRegistry.mergeResolutionCompleted(comparison); } }

Target:
public void handleFlush(Object input) { TreeNodeCompareInput treeNodeCompareInput = (TreeNodeCompareInput)input; EObject eobject = treeNodeCompareInput.getComparisonObject(); Comparison comparison = ComparisonUtil.getComparison(eobject); if (comparison == null) { return; } Predicate<Conflict> unresolvedConflict = new Predicate<Conflict>() { public boolean apply(Conflict conflict) { return conflict != null && conflict.getKind() != ConflictKind.PSEUDO && Iterables.any(conflict.getDifferences(), EMFComparePredicates .hasState(DifferenceState.UNRESOLVED)); } }; if (Iterables.any(comparison.getConflicts(), unresolvedConflict)) { mergeResolutionListenerRegistry.mergeResolutionCompleted(comparison); } }
Source:
public void testIsMetacardTransformerIdValidBadId() throws CatalogTransformerException { BinaryContent binaryContent = mock(BinaryContent.class); MultiMetacardTransformer transformer = mock(MultiMetacardTransformer.class); when(transformer.transform(any(List.class), any(Map.class))) .thenReturn(Collections.singletonList(binaryContent)); when(transformerLocator.findMultiMetacardTransformers(eq("xyz"))) .thenReturn(Collections.singletonList(transformer)); boolean isValid = transform.isMetacardTransformerIdValid("xxx"); assertThat(isValid, is(false)); }

Target:
public void testIsMetacardTransformerIdValidBadId() { MultiMetacardTransformer transformer = mock(MultiMetacardTransformer.class); when(transformerLocator.findMultiMetacardTransformers(eq("xyz"))) .thenReturn(Collections.singletonList(transformer)); boolean isValid = transform.isMetacardTransformerIdValid("xxx"); assertThat(isValid, is(false)); }
Source:
protected void assertHasAccess(String message, PID pid, Permission permission) throws SwordError { if (!aclService.hasAccess(pid, getAgentPrincipals().getPrincipals(), permission)) { throw new SwordError(ErrorURIRegistry.INSUFFICIENT_PRIVILEGES, 403, message); } }

Target:
protected void assertHasAccess(String message, PID pid, Permission permission) throws SwordError { if (!aclService.hasAccess(pid, getAgentPrincipals().getPrincipals(), permission)) { throw new SwordError(ErrorURIRegistry.INSUFFICIENT_PRIVILEGES, SC_FORBIDDEN, message); } }
Source:
public void testDummyScriptExecutionAndLoggerConsumer() throws Exception { System.setProperty("tc.install-root", "src" + File.separator + "test" + File.separator + "resources" + File.separator + "parent"); ConfigToolScriptExecutor configToolScriptExecutor = new ConfigToolScriptExecutor(); String[] cmd = new String[]{"detach", "-t", "stripe", "-d", "localhost:" + node1.getInternalAddress().toString(), "-s", node2.getInternalAddress().toString()}; int exitStatus = configToolScriptExecutor.execCommand(cmd, consumer); Assert.assertThat(sb.toString(), containsString("starting the script")); Assert.assertThat(sb.toString(), containsString("error:")); Assert.assertEquals(2, exitStatus); }

Target:
public void testDummyScriptExecutionAndLoggerConsumer() throws Exception { Path toolsDir = temporaryFolder.newFolder().toPath().resolve("tools"); Path binDir = toolsDir.resolve("bin"); Files.createDirectories(binDir); installScript("/tools/bin/config-tool.bat", binDir); installScript("/tools/bin/config-tool.sh", binDir); System.setProperty("tc.install-root", toolsDir.toString()); ConfigToolScriptExecutor configToolScriptExecutor = new ConfigToolScriptExecutor(); String[] cmd = new String[]{"detach", "-t", "stripe", "-d", "localhost:" + node1.getInternalAddress().toString(), "-s", node2.getInternalAddress().toString()}; int exitStatus = configToolScriptExecutor.execCommand(cmd, consumer); assertThat(sb.toString(), containsString("starting the script")); assertThat(sb.toString(), containsString("error:")); assertThat(exitStatus, is(2)); }
Source:
public int[] downloadSetupConfigurations(){ int[] result = new int[2]; try { List<SetupConfiguration> setupConfigurations = setupConfigurationController.downloadAllSetupConfigurations(); result[0] = SyncStatusConstants.SUCCESS; result[1] = setupConfigurations.size(); System.out.println("Setup Configs downloaded: "+setupConfigurations.size()); setupConfigurationController.saveSetupConfigurations(setupConfigurations); } catch (SetupConfigurationController.SetupConfigurationDownloadException e){ Log.e(TAG, "Exception when trying to download setup configs"); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (SetupConfigurationController.SetupConfigurationSaveException e){ Log.e(TAG, "Exception when trying to save setup configs"); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; }

Target:
public int[] downloadSetupConfigurations(){ int[] result = new int[2]; try { List<SetupConfiguration> setupConfigurations = setupConfigurationController.downloadAllSetupConfigurations(); result[0] = SyncStatusConstants.SUCCESS; result[1] = setupConfigurations.size(); Log.i(TAG, "Setup Configs downloaded: "+setupConfigurations.size()); setupConfigurationController.saveSetupConfigurations(setupConfigurations); } catch (SetupConfigurationController.SetupConfigurationDownloadException e){ Log.e(TAG, "Exception when trying to download setup configs"); result[0] = SyncStatusConstants.DOWNLOAD_ERROR; } catch (SetupConfigurationController.SetupConfigurationSaveException e){ Log.e(TAG, "Exception when trying to save setup configs"); result[0] = SyncStatusConstants.SAVE_ERROR; } return result; }
Source:
private Map<Job,Collection<ReverseBuildTrigger>> calculateCache() { Map<Job,Collection<ReverseBuildTrigger>> result = new WeakHashMap<>(); SecurityContext orig = ACL.impersonate(ACL.SYSTEM); for (Job<?, ?> downstream : Jenkins.getInstance().getAllItems(Job.class)) { ReverseBuildTrigger trigger = ParameterizedJobMixIn.getTrigger(downstream, ReverseBuildTrigger.class); if (trigger == null) { continue; } try { List<Job> upstreams = Items.fromNameList(downstream.getParent(), trigger.upstreamProjects, Job.class); LOGGER.log(Level.FINE, "from {0} see upstreams {1}", new Object[] {downstream, upstreams}); for (Job upstream : upstreams) { if (upstream instanceof AbstractProject && downstream instanceof AbstractProject) { continue; } Collection<ReverseBuildTrigger> triggers = result.get(upstream); if (triggers == null) { triggers = new LinkedList<>(); result.put(upstream, triggers); } triggers.remove(trigger); triggers.add(trigger); } } finally { SecurityContextHolder.setContext(orig); } } return result; }

Target:
private Map<Job,Collection<ReverseBuildTrigger>> calculateCache() { final Map<Job,Collection<ReverseBuildTrigger>> result = new WeakHashMap<>(); ACL.impersonate(ACL.SYSTEM, new Runnable() { @Override public void run() { for (Job<?, ?> downstream : Jenkins.getInstance().getAllItems(Job.class)) { ReverseBuildTrigger trigger = ParameterizedJobMixIn.getTrigger(downstream, ReverseBuildTrigger.class); if (trigger == null) { continue; } List<Job> upstreams = Items.fromNameList(downstream.getParent(), trigger.upstreamProjects, Job.class); LOGGER.log(Level.FINE, "from {0} see upstreams {1}", new Object[] {downstream, upstreams}); for (Job upstream : upstreams) { if (upstream instanceof AbstractProject && downstream instanceof AbstractProject) { continue; } Collection<ReverseBuildTrigger> triggers = result.get(upstream); if (triggers == null) { triggers = new LinkedList<>(); result.put(upstream, triggers); } triggers.remove(trigger); triggers.add(trigger); } } } }); return result; }
Source:
public Step loadVepAnnotationStep(StepBuilderFactory stepBuilderFactory, JobOptions jobOptions) { logger.debug("Building '" + LOAD_VEP_ANNOTATION_STEP + "'"); return stepBuilderFactory.get(LOAD_VEP_ANNOTATION_STEP) .<VariantAnnotation, VariantAnnotation>chunk(jobOptions.getPipelineOptions().getInt(JobParametersNames.CONFIG_CHUNK_SIZE)) .reader(variantAnnotationReader) .writer(variantAnnotationItemWriter) .faultTolerant().skipLimit(50).skip(FlatFileParseException.class) .listener(new SkippedItemListener()) .build(); }

Target:
public Step loadVepAnnotationStep(StepBuilderFactory stepBuilderFactory, JobOptions jobOptions) { logger.debug("Building '" + LOAD_VEP_ANNOTATION_STEP + "'"); final int chunkSize = jobOptions.getPipelineOptions().getInt(JobParametersNames.CONFIG_CHUNK_SIZE); return stepBuilderFactory.get(LOAD_VEP_ANNOTATION_STEP) .<VariantAnnotation, VariantAnnotation>chunk(chunkSize) .reader(variantAnnotationReader) .writer(variantAnnotationItemWriter) .faultTolerant().skipLimit(50).skip(FlatFileParseException.class) .listener(new SkippedItemListener()) .build(); }
Source:
public boolean matches(Message msg) { return msg.getFlags() != null && msg.getFlags().contains("starred"); }

Target:
public boolean matches(Message msg) { return (msg.getFlags() != null && msg.getFlags().contains("starred")) || (msg.getMessageStar()); }
Source:
public void initialize() { try { logger.debug("Initializing NTP handler for '{}'.",getThing().getUID()); Configuration config = getThing().getConfiguration(); this.hostname = (String) config.get(PROPERTY_NTP_SERVER); this.refreshInterval = new BigDecimal (config.get(PROPERTY_REFRESH_INTERVAL).toString()); this.refreshNtp = new BigDecimal (config.get(PROPERTY_REFRESH_NTP).toString());; this.refreshNtpCount = 0; try { timeZone = TimeZone.getTimeZone((String) config.get(PROPERTY_TIMEZONE)); } catch (Exception e) { timeZone = TimeZone.getDefault(); logger.debug("using default TZ: {}", timeZone); } try { String localeString = (String) config.get(PROPERTY_LOCALE); locale = new Locale(localeString); } catch (Exception e) { locale = Locale.getDefault(); logger.debug("using default locale: {}", locale); } dateTimeChannelUID = new ChannelUID(getThing().getUID(), CHANNEL_DATE_TIME); startAutomaticRefresh(); } catch (Exception ex) { String msg = "Error occured while initializing NTP handler: " + ex.getMessage(); logger.error(msg, ex); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg); } }

Target:
public void initialize() { try { logger.debug("Initializing NTP handler for '{}'.",getThing().getUID()); Configuration config = getThing().getConfiguration(); this.hostname = (String) config.get(PROPERTY_NTP_SERVER); this.refreshInterval = (BigDecimal) config.get(PROPERTY_REFRESH_INTERVAL); this.refreshNtp = (BigDecimal) config.get(PROPERTY_REFRESH_NTP); this.refreshNtpCount = 0; try { timeZone = TimeZone.getTimeZone((String) config.get(PROPERTY_TIMEZONE)); } catch (Exception e) { timeZone = TimeZone.getDefault(); logger.debug("using default TZ: {}", timeZone); } try { String localeString = (String) config.get(PROPERTY_LOCALE); locale = new Locale(localeString); } catch (Exception e) { locale = Locale.getDefault(); logger.debug("using default locale: {}", locale); } dateTimeChannelUID = new ChannelUID(getThing().getUID(), CHANNEL_DATE_TIME); startAutomaticRefresh(); } catch (Exception ex) { String msg = "Error occured while initializing NTP handler: " + ex.getMessage(); logger.error(msg, ex); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg); } }
Source:
private static boolean isArrayOrList(Type type) { if (type.getClass().isArray()) { return true; } return isList(type); }

Target:
private static boolean isArrayOrList(Type type) { return type.getClass().isArray() || isList(type); }
Source:
public ResponseEntity<?> commitCursors(@PathVariable("subscriptionId") final String subscriptionId, @RequestBody final List<SubscriptionCursor> cursors, final NativeWebRequest request, final Client client) { if (!featureToggleService.isFeatureEnabled(HIGH_LEVEL_API)) { return new ResponseEntity<>(NOT_IMPLEMENTED); } try { validateSubscriptionReadScopes(client, subscriptionId); final boolean allCommitted = cursorsService.commitCursors(subscriptionId, cursors); return allCommitted ? ok().build() : noContent().build(); } catch (final NakadiException e) { return create(e.asProblem(), request); } catch (InvalidCursorException e) { return create(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage()), request); } }

Target:
public ResponseEntity<?> commitCursors(@PathVariable("subscriptionId") final String subscriptionId, @RequestBody final List<SubscriptionCursor> cursors, final NativeWebRequest request, final Client client) { if (!featureToggleService.isFeatureEnabled(HIGH_LEVEL_API)) { return new ResponseEntity<>(NOT_IMPLEMENTED); } try { validateSubscriptionReadScopes(client, subscriptionId); final Map<SubscriptionCursor, Boolean> result = cursorsService.commitCursors(subscriptionId, cursors); final List<CursorCommitResult> items = result.entrySet().stream() .map(entry -> new CursorCommitResult(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); final boolean allCommited = result.values().stream().reduce(Boolean::logicalAnd).orElseGet(() -> true); final ItemsWrapper<CursorCommitResult> body = new ItemsWrapper<>(items); return allCommited ? noContent().build() : ok(body); } catch (final NakadiException e) { return create(e.asProblem(), request); } catch (InvalidCursorException e) { return create(Problem.valueOf(UNPROCESSABLE_ENTITY, e.getMessage()), request); } }
Source:
protected void applyDataRowStyle(final int row) { super.applyDataRowStyle(row); final CellFormatter fmt = table.getCellFormatter(); fmt.addStyleName(row, C_STAR, Gerrit.RESOURCES.css().iconCell()); for (int i = C_ID; i < columns; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().dataCell()); } if (!showLegacyId) { fmt.addStyleName(row, C_ID, Gerrit.RESOURCES.css().dataCellHidden()); } fmt.addStyleName(row, C_SUBJECT, Gerrit.RESOURCES.css().cSUBJECT()); fmt.addStyleName(row, C_STATUS, Gerrit.RESOURCES.css().cSTATUS()); fmt.addStyleName(row, C_OWNER, Gerrit.RESOURCES.css().cOWNER()); fmt.addStyleName(row, C_LAST_UPDATE, Gerrit.RESOURCES.css().cLastUpdate()); fmt.addStyleName(row, C_SIZE, Gerrit.RESOURCES.css().cSIZE()); for (int i = C_SIZE; i < columns; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().cAPPROVAL()); } }

Target:
protected void applyDataRowStyle(final int row) { super.applyDataRowStyle(row); final CellFormatter fmt = table.getCellFormatter(); fmt.addStyleName(row, C_STAR, Gerrit.RESOURCES.css().iconCell()); for (int i = C_ID; i < columns; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().dataCell()); } if (!showLegacyId) { fmt.addStyleName(row, C_ID, Gerrit.RESOURCES.css().dataCellHidden()); } fmt.addStyleName(row, C_SUBJECT, Gerrit.RESOURCES.css().cSUBJECT()); fmt.addStyleName(row, C_STATUS, Gerrit.RESOURCES.css().cSTATUS()); fmt.addStyleName(row, C_OWNER, Gerrit.RESOURCES.css().cOWNER()); fmt.addStyleName(row, C_LAST_UPDATE, Gerrit.RESOURCES.css().cLastUpdate()); fmt.addStyleName(row, C_SIZE, Gerrit.RESOURCES.css().cSIZE()); for (int i = C_SIZE + 1; i < columns; i++) { fmt.addStyleName(row, i, Gerrit.RESOURCES.css().cAPPROVAL()); } }
Source:
public void addSpecificUserOwner(PerunSession sess, User user, User specificUser) throws InternalErrorException, UserNotExistsException, PrivilegeException, SpecificUserExpectedException, NotSpecificUserExpectedException, RelationExistsException { Utils.checkPerunSession(sess); getUsersManagerBl().checkUserExists(sess, user); getUsersManagerBl().checkUserExists(sess, specificUser); if (user.isServiceUser()) throw new NotSpecificUserExpectedException(user); if (user.isSponsoredUser() && specificUser.isSponsoredUser()) throw new NotSpecificUserExpectedException(specificUser); if (!specificUser.isSpecificUser()) throw new SpecificUserExpectedException(specificUser); if(!AuthzResolver.authorizedInternal(sess, "addSpecificUserOwner_User_User_policy", Collections.singletonList(specificUser))) { throw new PrivilegeException(sess, "addSpecificUserOwner"); } getUsersManagerBl().addSpecificUserOwner(sess, user, specificUser); }

Target:
public void addSpecificUserOwner(PerunSession sess, User user, User specificUser) throws InternalErrorException, UserNotExistsException, PrivilegeException, SpecificUserExpectedException, NotSpecificUserExpectedException, RelationExistsException { Utils.checkPerunSession(sess); getUsersManagerBl().checkUserExists(sess, user); getUsersManagerBl().checkUserExists(sess, specificUser); if (user.isServiceUser()) throw new NotSpecificUserExpectedException(user); if (user.isSponsoredUser() && specificUser.isSponsoredUser()) throw new NotSpecificUserExpectedException(specificUser); if (!specificUser.isSpecificUser()) throw new SpecificUserExpectedException(specificUser); if(!AuthzResolver.authorizedInternal(sess, "addSpecificUserOwner_User_User_policy", Collections.singletonList(specificUser)) && !AuthzResolver.authorizedInternal(sess, "owner-addSpecificUserOwner_User_User_policy", Collections.singletonList(user))) { throw new PrivilegeException(sess, "addSpecificUserOwner"); } getUsersManagerBl().addSpecificUserOwner(sess, user, specificUser); }
Source:
public static <ResType> List<ResType> filterAuthorizedResources( final HttpServletRequest request, final Collection<ResType> resources, final Function<? super ResType, ResourceAction> resourceActionGenerator, final AuthorizerMapper authorizerMapper ) { final AuthenticationResult authenticationResult = (AuthenticationResult) request.getAttribute( AuthConfig.DRUID_AUTHENTICATION_RESULT ); if (authenticationResult == null) { throw new ISE("Null authentication result"); } final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName()); if (authorizer == null) { throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName()); } int initialSize = resources.size(); final Map<ResourceAction, Access> resultCache = Maps.newHashMap(); List<ResType> filteredResources = new ArrayList<>(); for (ResType resource : resources) { final ResourceAction resourceAction = resourceActionGenerator.apply(resource); Access access = resultCache.get(resourceAction); if (access == null) { access = authorizer.authorize( authenticationResult, resourceAction.getResource(), resourceAction.getAction() ); resultCache.put(resourceAction, access); } if (access.isAllowed()) { filteredResources.add(resource); } } request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, (filteredResources.size() > 0 || initialSize == 0)); return filteredResources; }

Target:
public static <ResType> List<ResType> filterAuthorizedResources( final HttpServletRequest request, final Collection<ResType> resources, final Function<? super ResType, ResourceAction> resourceActionGenerator, final AuthorizerMapper authorizerMapper ) { final AuthenticationResult authenticationResult = (AuthenticationResult) request.getAttribute( AuthConfig.DRUID_AUTHENTICATION_RESULT ); if (authenticationResult == null) { throw new ISE("Null authentication result"); } final Authorizer authorizer = authorizerMapper.getAuthorizer(authenticationResult.getAuthorizerName()); if (authorizer == null) { throw new ISE("No authorizer found with name: [%s].", authenticationResult.getAuthorizerName()); } final Map<ResourceAction, Access> resultCache = Maps.newHashMap(); List<ResType> filteredResources = new ArrayList<>(); for (ResType resource : resources) { final ResourceAction resourceAction = resourceActionGenerator.apply(resource); Access access = resultCache.computeIfAbsent( resourceAction, ra -> authorizer.authorize( authenticationResult, ra.getResource(), ra.getAction() ) ); if (access.isAllowed()) { filteredResources.add(resource); } } request.setAttribute(AuthConfig.DRUID_AUTHORIZATION_CHECKED, true); return filteredResources; }
Source:
private ThrowableCategory throwableCategory(Throwable t) { Throwable current = t; StringBuilder builder = new StringBuilder(); do { if (current.getMessage() != null && current.getMessage().startsWith("Acquire operation")) { return new ThrowableCategory(ThrowableType.ACUIRE_TIMEOUT); } if (current.getClass().getName().equals("io.netty.handler.timeout.ReadTimeoutException")) { return new ThrowableCategory(ThrowableType.READ_TIMEOUT); } if (current.getCause() == null) { builder.append(current.getClass().getName()).append(": ").append(current.getMessage()); } else { builder.append(current.getClass().getSimpleName()); builder.append("/"); } current = current.getCause(); } while (current != null); return new ThrowableCategory(ThrowableType.UNKNOWN, builder.toString()); }

Target:
private ThrowableCategory throwableCategory(Throwable t) { Throwable current = t; StringBuilder builder = new StringBuilder(); do { if (current.getMessage() != null && current.getMessage().startsWith("Acquire operation")) { return ACQUIRE_TIMEOUT_CATEGORY; } if (current.getClass().getName().equals("io.netty.handler.timeout.ReadTimeoutException")) { return READ_TIMEOUT_CATEGORY; } if (current.getCause() == null) { builder.append(current.getClass().getName()).append(": ").append(current.getMessage()); } else { builder.append(current.getClass().getSimpleName()); builder.append("/"); } current = current.getCause(); } while (current != null); return new ThrowableCategory(ThrowableType.OTHER, builder.toString()); }
Source:
public ImmutableList<VariantOutput> getOutputFiles() { ImmutableList.Builder<VariantOutput> outputs = ImmutableList.builder(); if (packageSplitResourcesTask != null) { outputs.addAll(packageSplitResourcesTask.getOutputFiles()); } outputs.add(new VariantOutput.MainVariantOutput(getOutputFile())); return outputs.build(); }

Target:
public ImmutableList<APKOutput> getOutputFiles() { ImmutableList.Builder<APKOutput> outputs = ImmutableList.builder(); if (packageSplitResourcesTask != null) { outputs.addAll(packageSplitResourcesTask.getOutputFiles()); } outputs.add(new APKOutput.MainAPKOutput(getOutputFile())); return outputs.build(); }
Source:
public void handleUploadButton(View view) { if (!Utils.isNetworkAvailable(view.getContext(), true)) { return; } if (!viewSwitchLock.tryLock()) { return; } if (BuildConfig.CREATE_AT_SCHOOL && !Utils.isCreateAtSchoolUser(this)) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); sharedPreferences.edit().putString(Constants.TOKEN, Constants.NO_TOKEN).apply(); sharedPreferences.edit().putString(Constants.USERNAME, Constants.NO_USERNAME).apply(); } ProjectManager.getInstance().uploadProject(Utils.getCurrentProjectName(this), this); }

Target:
public void handleUploadButton(View view) { if (!Utils.isNetworkAvailable(view.getContext(), true)) { return; } if (!viewSwitchLock.tryLock()) { return; } if (BuildConfig.CREATE_AT_SCHOOL && !Utils.isCreateAtSchoolUser(this)) { SharedPreferences.Editor sharedPrefEditor = PreferenceManager.getDefaultSharedPreferences(this).edit(); sharedPrefEditor.putString(Constants.TOKEN, Constants.NO_TOKEN); sharedPrefEditor.putString(Constants.USERNAME, Constants.NO_USERNAME); sharedPrefEditor.apply(); } ProjectManager.getInstance().uploadProject(Utils.getCurrentProjectName(this), this); }
Source:
public void toggleFavoriteBranch(Branch favoriteBranch) throws OseeCoreException { HashSet<Long> branchUuids = new HashSet<Long>(); for (Branch branch : BranchManager.getBranches(BranchArchivedState.UNARCHIVED, BranchType.WORKING, BranchType.BASELINE)) { branchUuids.add(branch.getUuid()); } boolean found = false; @SuppressWarnings("deprecation") Collection<Attribute<String>> attributes = getAttributes(CoreAttributeTypes.FavoriteBranch); for (Attribute<String> attribute : attributes) { Long uuid = 0L; try { uuid = Long.valueOf(attribute.getValue()); } catch (Exception ex) { throw new OseeStateException("Invalid Favorite Branch uuid [%s] for user [%s]", attribute.getValue(), toStringWithId()); } if (!branchUuids.contains(uuid)) { attribute.delete(); } else if (favoriteBranch.getUuid().equals(uuid)) { attribute.delete(); found = true; } } if (!found) { addAttribute(CoreAttributeTypes.FavoriteBranch, String.valueOf(favoriteBranch.getUuid())); } setSetting(CoreAttributeTypes.FavoriteBranch.getName(), String.valueOf(favoriteBranch.getUuid())); saveSettings(); }

Target:
public void toggleFavoriteBranch(Branch favoriteBranch) throws OseeCoreException { HashSet<Long> branchUuids = new HashSet<Long>(); for (Branch branch : BranchManager.getBranches(BranchArchivedState.UNARCHIVED, BranchType.WORKING, BranchType.BASELINE)) { branchUuids.add(branch.getUuid()); } boolean found = false; @SuppressWarnings("deprecation") Collection<Attribute<String>> attributes = getAttributes(CoreAttributeTypes.FavoriteBranch); for (Attribute<String> attribute : attributes) { Long uuid = 0L; try { uuid = Long.valueOf(attribute.getValue()); } catch (Exception ex) { continue; } if (!branchUuids.contains(uuid)) { attribute.delete(); } else if (favoriteBranch.getUuid().equals(uuid)) { attribute.delete(); found = true; } } if (!found) { addAttribute(CoreAttributeTypes.FavoriteBranch, String.valueOf(favoriteBranch.getUuid())); } setSetting(CoreAttributeTypes.FavoriteBranch.getName(), String.valueOf(favoriteBranch.getUuid())); saveSettings(); }
Source:
private void setTabularResult(String key, Object obj, List<String> columns, List<String> line, TypeSystem typeSystem) { if (obj instanceof Value) { Value value = (Value) obj; if (value.hasType(typeSystem.MAP())) { Map<String, Object> map = value.asMap(); for (Entry<String, Object> entry : map.entrySet()) { setTabularResult(String.format(MAP_KEY_TEMPLATE, key, entry.getKey()), entry.getValue(), columns, line, typeSystem); } } else { addValueToLine(key, columns, line, value); } } else if (obj instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) obj; for (Entry<String, Object> entry : map.entrySet()) { setTabularResult(String.format(MAP_KEY_TEMPLATE, key, entry.getKey()), entry.getValue(), columns, line, typeSystem); } } else { addValueToLine(key, columns, line, obj); } }

Target:
private void setTabularResult(String key, Object obj, List<String> columns, List<String> line, TypeSystem typeSystem) { if (obj instanceof Value) { Value value = (Value) obj; if (value.hasType(typeSystem.MAP())) { Map<String, Object> map = value.asMap(); for (Entry<String, Object> entry : map.entrySet()) { setTabularResult(String.format(MAP_KEY_TEMPLATE, key, entry.getKey()), entry.getValue(), columns, line, typeSystem); } } else { addValueToLine(key, columns, line, value); } } else if (obj instanceof Map) { Map<String, Object> map = (Map<String, Object>) obj; for (Entry<String, Object> entry : map.entrySet()) { setTabularResult(String.format(MAP_KEY_TEMPLATE, key, entry.getKey()), entry.getValue(), columns, line, typeSystem); } } else { addValueToLine(key, columns, line, obj); } }
Source:
protected void ExecuteVdsBrokerCommand() { if (getParameters().getGracefully()) { status = getBroker().shutdown(getParameters().getVmId().toString(), (Integer.valueOf(getParameters().getSecondsToWait())).toString(), Config.<String> GetValue(ConfigValues.VmGracefulShutdownMessage)); } else { status = getBroker().destroy(getParameters().getVmId().toString()); } ProceedProxyReturnValue(); }

Target:
protected void ExecuteVdsBrokerCommand() { if (getParameters().getGracefully()) { status = getBroker().shutdown(getParameters().getVmId().toString(), String.valueOf(getParameters().getSecondsToWait()), Config.<String> GetValue(ConfigValues.VmGracefulShutdownMessage)); } else { status = getBroker().destroy(getParameters().getVmId().toString()); } ProceedProxyReturnValue(); }
Source:
private void initiateRequest(AjpClientExchange AjpClientExchange) { currentRequest = AjpClientExchange; ClientRequest request = AjpClientExchange.getRequest(); String connectionString = request.getRequestHeaders().getFirst(CONNECTION); if (connectionString != null) { if (connectionString.equals(CLOSE)) { state |= CLOSE_REQ; } } else if (request.getProtocol() != Protocols.HTTP_1_1) { state |= CLOSE_REQ; } if (request.getRequestHeaders().contains(UPGRADE)) { state |= UPGRADE_REQUESTED; } long length = 0; String fixedLengthString = request.getRequestHeaders().getFirst(CONTENT_LENGTH); String transferEncodingString = request.getRequestHeaders().getLast(TRANSFER_ENCODING); if (fixedLengthString != null) { length = Long.parseLong(fixedLengthString); } else if (transferEncodingString != null) { length = -1; } AjpClientRequestClientStreamSinkChannel sinkChannel = connection.sendRequest(request.getMethod(), request.getPath(), request.getProtocol(), request.getRequestHeaders(), request, requestFinishListener); currentRequest.setRequestChannel(sinkChannel); AjpClientExchange.invokeReadReadyCallback(AjpClientExchange); if (length == 0) { try { sinkChannel.shutdownWrites(); if (!sinkChannel.flush()) { handleFailedFlush(sinkChannel); } } catch (Throwable t) { handleError((t instanceof IOException) ? (IOException) t : new IOException(t)); } } }

Target:
private void initiateRequest(AjpClientExchange AjpClientExchange) { currentRequest = AjpClientExchange; ClientRequest request = AjpClientExchange.getRequest(); String connectionString = request.getRequestHeaders().getFirst(CONNECTION); if (connectionString != null) { if (CLOSE.equalToString(connectionString)) { state |= CLOSE_REQ; } } else if (request.getProtocol() != Protocols.HTTP_1_1) { state |= CLOSE_REQ; } if (request.getRequestHeaders().contains(UPGRADE)) { state |= UPGRADE_REQUESTED; } long length = 0; String fixedLengthString = request.getRequestHeaders().getFirst(CONTENT_LENGTH); String transferEncodingString = request.getRequestHeaders().getLast(TRANSFER_ENCODING); if (fixedLengthString != null) { length = Long.parseLong(fixedLengthString); } else if (transferEncodingString != null) { length = -1; } AjpClientRequestClientStreamSinkChannel sinkChannel = connection.sendRequest(request.getMethod(), request.getPath(), request.getProtocol(), request.getRequestHeaders(), request, requestFinishListener); currentRequest.setRequestChannel(sinkChannel); AjpClientExchange.invokeReadReadyCallback(AjpClientExchange); if (length == 0) { try { sinkChannel.shutdownWrites(); if (!sinkChannel.flush()) { handleFailedFlush(sinkChannel); } } catch (Throwable t) { handleError((t instanceof IOException) ? (IOException) t : new IOException(t)); } } }
Source:
private JavaPairRDD<Integer, List<double[]>> fetchClusteredPoints(JavaRDD<Vector> evalData) { return evalData.mapToPair(new PairFunction<Vector, Integer, List<double[]>>() { @Override public Tuple2<Integer, List<double[]>> call(Vector vector) { double closestDist = Double.POSITIVE_INFINITY; int minCluster = -1; double[] vec = vector.toArray(); for (int i = 0; i < numClusters; i++) { ClusterInfo cluster = clusters.get(i); double distance = distanceFn.distance(cluster.getCenter(), vec); if (distance < closestDist) { closestDist = distance; minCluster = i; } } Preconditions.checkState(minCluster >= 0); List<double[]> pointsList = new ArrayList<>(); pointsList.add(vec); return new Tuple2<>(minCluster, pointsList); } }).reduceByKey(new Function2<List<double[]>, List<double[]>, List<double[]>>() { @Override public List<double[]> call(List<double[]> v1, List<double[]> v2) { v1.addAll(v2); return v1; } }); }

Target:
private JavaPairRDD<Integer, Iterable<double[]>> fetchClusteredPoints(JavaRDD<Vector> evalData) { return evalData.mapToPair(new PairFunction<Vector, Integer, double[]>() { @Override public Tuple2<Integer, double[]> call(Vector vector) { double closestDist = Double.POSITIVE_INFINITY; int minCluster = -1; double[] vec = vector.toArray(); for (int i = 0; i < numClusters; i++) { ClusterInfo cluster = clusters.get(i); double distance = distanceFn.distance(cluster.getCenter(), vec); if (distance < closestDist) { closestDist = distance; minCluster = i; } } Preconditions.checkState(minCluster >= 0); return new Tuple2<>(minCluster, vec); } }).groupByKey(); }
Source:
public static void main(String[] args) throws IOException, InterruptedException, BookieException, KeeperException { Bookie b = new Bookie(new ServerConfiguration()); b.start(); CounterCallback cb = new CounterCallback(); long start = MathUtils.now(); for (int i = 0; i < 100000; i++) { ByteBuf buff = Unpooled.buffer(1024); buff.writeLong(1); buff.writeLong(i); cb.incCount(); b.addEntry(buff, cb, null, new byte[0], LedgerType.FORCE_ON_JOURNAL); } cb.waitZero(); long end = MathUtils.now(); System.out.println("Took " + (end - start) + "ms"); }

Target:
public static void main(String[] args) throws IOException, InterruptedException, BookieException, KeeperException { Bookie b = new Bookie(new ServerConfiguration()); b.start(); CounterCallback cb = new CounterCallback(); long start = MathUtils.now(); for (int i = 0; i < 100000; i++) { ByteBuf buff = Unpooled.buffer(1024); buff.writeLong(1); buff.writeLong(i); cb.incCount(); b.addEntry(buff, LedgerType.FORCE_ON_JOURNAL, cb, null, new byte[0]); } cb.waitZero(); long end = MathUtils.now(); System.out.println("Took " + (end - start) + "ms"); }
Source:
public GanttCategoryDataset createDebugEventGanttChartDataset() { splitEventsIntoAListPerType(); final TaskSeries allTasks = new TaskSeries("Debug Events"); allTasks.add( createTaskForEventsWithName("Breakpoint Added", bpAddEvents)); allTasks.add(createTaskForEventsWithName("Breakpoint Changed", bpChangeEvents)); allTasks.add(createTaskForEventsWithName("Breakpoint Removed", bpRemoveEvents)); allTasks.add(createTaskForEventsWithName("Suspended (breakpoint)", suspendBpEvents)); allTasks.add(createTaskForEventsWithName("Suspended (client)", suspendClientEvents)); allTasks.add(createTaskForEventsWithName("Stepped Out", stepOutEvents)); allTasks.add( createTaskForEventsWithName("Stepped Into", stepIntoEvents)); allTasks.add( createTaskForEventsWithName("Stepped Over", stepOverEvents)); allTasks.add(createTaskForEventsWithName("Resumed (client)", resumeClientEvents)); allTasks.add(createTaskForEventsWithName("Inspected Variable", inspectEvents)); allTasks.add(createTaskForEventsWithName("Defined Watch", defineWatchEvents)); allTasks.add(createTaskForEventsWithName("Evaluated Expression", evalExpressionEvents)); allTasks.add(createTaskForEventsWithName("Modified Variable Value", modVarValueEvents)); final TaskSeriesCollection collection = new TaskSeriesCollection(); collection.add(allTasks); return collection; }

Target:
public GanttCategoryDataset createDebugEventGanttChartDataset() { splitEventsIntoAListPerType(); TaskSeries allTasks = new TaskSeries("Debug Events"); allTasks.add( createTaskForEventsWithName(bpAddEvents, "Breakpoint Added")); allTasks.add(createTaskForEventsWithName(bpChangeEvents, "Breakpoint Changed" )); allTasks.add(createTaskForEventsWithName(bpRemoveEvents, "Breakpoint Removed" )); allTasks.add(createTaskForEventsWithName(suspendBpEvents, "Suspended (breakpoint)" )); allTasks.add(createTaskForEventsWithName(suspendClientEvents, "Suspended (client)" )); allTasks.add(createTaskForEventsWithName(stepOutEvents, "Stepped Out")); allTasks.add( createTaskForEventsWithName(stepIntoEvents, "Stepped Into")); allTasks.add( createTaskForEventsWithName(stepOverEvents, "Stepped Over")); allTasks.add(createTaskForEventsWithName(resumeClientEvents, "Resumed (client)" )); allTasks.add(createTaskForEventsWithName(inspectEvents, "Inspected Variable" )); allTasks.add(createTaskForEventsWithName(defineWatchEvents, "Defined Watch" )); allTasks.add(createTaskForEventsWithName(evalExpressionEvents, "Evaluated Expression" )); allTasks.add(createTaskForEventsWithName(modVarValueEvents, "Modified Variable Value" )); TaskSeriesCollection collection = new TaskSeriesCollection(); collection.add(allTasks); return collection; }