auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static boolean createCluster(String destZkString, String destClusterName) { HelixZkClient destZkClient = DedicatedZkClientFactory.getInstance().buildZkClient(new HelixZkClient.ZkConnectionConfig(destZkString)); destZkClient.setZkSerializer(new ZNRecordSerializer()); HelixAdmin destAdmin = new ZKHelixAdmin(destZkClient); if (destAdmin.getClusters().contains(destClusterName)) { System.out.println("Create cluster failed. " + destClusterName + " already exist."); return false; } ClusterSetup clusterSetup = new ClusterSetup(destZkString); clusterSetup.addCluster(destClusterName, true); HelixConfigScope configScope = new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER). forCluster(destClusterName).build(); Map<String, String> helixClusterProperties = new HashMap<>(); helixClusterProperties.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, String.valueOf(true)); destAdmin.setConfig(configScope, helixClusterProperties); ConfigAccessor configAccessor = new ConfigAccessor(destZkClient); ClusterConfig clusterConfig = configAccessor.getClusterConfig(destClusterName); clusterConfig.setPersistBestPossibleAssignment(true); configAccessor.setClusterConfig(destClusterName, clusterConfig); System.out.println("Cluster " + destClusterName + " create done."); return true; }

Target:
static void createCluster(String destZkString, String destClusterName) { HelixZkClient destZkClient = DedicatedZkClientFactory.getInstance().buildZkClient(new HelixZkClient.ZkConnectionConfig(destZkString)); destZkClient.setZkSerializer(new ZNRecordSerializer()); HelixAdmin destAdmin = new ZKHelixAdmin(destZkClient); if (destAdmin.getClusters().contains(destClusterName)) { System.out.println("Failed to create cluster becuase " + destClusterName + " already exist."); return; } ClusterSetup clusterSetup = new ClusterSetup(destZkString); clusterSetup.addCluster(destClusterName, true); HelixConfigScope configScope = new HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER). forCluster(destClusterName).build(); Map<String, String> helixClusterProperties = new HashMap<>(); helixClusterProperties.put(ZKHelixManager.ALLOW_PARTICIPANT_AUTO_JOIN, String.valueOf(true)); destAdmin.setConfig(configScope, helixClusterProperties); ConfigAccessor configAccessor = new ConfigAccessor(destZkClient); ClusterConfig clusterConfig = configAccessor.getClusterConfig(destClusterName); clusterConfig.setPersistBestPossibleAssignment(true); configAccessor.setClusterConfig(destClusterName, clusterConfig); System.out.println("Cluster " + destClusterName + " is created successfully!"); return; }
Source:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { String authorizationValue = this.credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(), context.getHttpRequest().getHeaders().toMap()); context.getHttpRequest().setHeader("Authorization", authorizationValue); return next.process(); }

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { String authorizationValue = credential.generateAuthorizationHeader(context.getHttpRequest().getUrl(), context.getHttpRequest().getHeaders().toMap()); context.getHttpRequest().setHeader("Authorization", authorizationValue); return next.process(); }
Source:
public EnumFacing getFacing() { return EnumFacing.getFront(getBlockMetadata()); }

Target:
public EnumFacing getFacing() { return getWorld().getBlockState(getPos()).getValue(BlockBase.FACING); }
Source:
private void addSystemDrivers( Tracer tracer, HttpClient.Factory clientFactory, LocalNode.Builder node) { List<WebDriverInfo> infos = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false) .filter(WebDriverInfo::isAvailable) .collect(Collectors.toList()); List<DriverService.Builder> builders = new ArrayList<>(); ServiceLoader.load(DriverService.Builder.class).forEach(builders::add); infos.forEach(info -> { Capabilities caps = info.getCanonicalCapabilities(); builders.stream() .filter(builder -> builder.score(caps) > 0) .peek(builder -> LOG.finest(String.format("Adding %s %d times", caps, info.getMaximumSimultaneousSessions()))) .forEach(builder -> { DriverService.Builder freePortBuilder = builder.usingAnyFreePort(); for (int i = 0; i < info.getMaximumSimultaneousSessions(); i++) { node.add( caps, new DriverServiceSessionFactory( tracer, clientFactory, c -> freePortBuilder.score(c) > 0, freePortBuilder)); } }); }); }

Target:
private void addSystemDrivers( Tracer tracer, HttpClient.Factory clientFactory, LocalNode.Builder node) { List<WebDriverInfo> infos = StreamSupport.stream(ServiceLoader.load(WebDriverInfo.class).spliterator(), false) .filter(WebDriverInfo::isAvailable) .collect(Collectors.toList()); List<DriverService.Builder> builders = new ArrayList<>(); ServiceLoader.load(DriverService.Builder.class).forEach(builders::add); infos.forEach(info -> { Capabilities caps = info.getCanonicalCapabilities(); builders.stream() .filter(builder -> builder.score(caps) > 0) .peek(builder -> LOG.info(String.format("Adding %s %d times", caps, info.getMaximumSimultaneousSessions()))) .forEach(builder -> { DriverService.Builder freePortBuilder = builder.usingAnyFreePort(); for (int i = 0; i < info.getMaximumSimultaneousSessions(); i++) { node.add( caps, new DriverServiceSessionFactory( tracer, clientFactory, c -> freePortBuilder.score(c) > 0, freePortBuilder)); } }); }); }
Source:
public void testConnectNoRandomize() throws IOException, InterruptedException { try (NatsTestServer ts1 = new NatsTestServer(false)) { try (NatsTestServer ts2 = new NatsTestServer(false)) { int one = 0; int two = 0; for (int i=0; i < 10; i++) { String[] servers = {ts1.getURI(), ts2.getURI()}; Options options = new Options.Builder().noRandomize().servers(servers).build(); Connection nc = Nats.connect(options); try { assertConnected(nc); if (nc.getConnectedUrl().equals(ts1.getURI())) { one++; } else { two++; } } finally { closeConnectionAssertClosed(nc); } } assertEquals(one, 10, "always got one"); assertEquals(two, 0, "never got two"); } } }

Target:
public void testConnectNoRandomize() throws IOException, InterruptedException { try (NatsTestServer ts1 = new NatsTestServer(false)) { try (NatsTestServer ts2 = new NatsTestServer(false)) { int one = 0; int two = 0; for (int i=0; i < 10; i++) { String[] servers = {ts1.getURI(), ts2.getURI()}; Options options = new Options.Builder().noRandomize().servers(servers).build(); Connection nc = Nats.connect(options); try { assertConnected(nc); if (nc.getConnectedUrl().equals(ts1.getURI())) { one++; } else { two++; } } finally { closeThenAssertClosed(nc); } } assertEquals(one, 10, "always got one"); assertEquals(two, 0, "never got two"); } } }
Source:
public void testHasDeletionBeenProcessed(final String cigarString, final List<Boolean> expected) { Cigar cigar = TextCigarCodec.decode(cigarString); SAMRecord deletionRecord = createRecordFromCigar(cigar.toString()); CollectSamErrorMetrics collectSamErrorMetrics = new CollectSamErrorMetrics(); final SAMSequenceRecord samSequenceRecord = new SAMSequenceRecord("chr1", 2000); SamLocusIterator.LocusInfo locusInfo; int position = 100; int iExpected = 0; for(CigarElement cigarElement : cigar.getCigarElements()) { for(int iCigarElementPosition = 0; iCigarElementPosition < cigarElement.getLength(); iCigarElementPosition++) { locusInfo = new SamLocusIterator.LocusInfo(samSequenceRecord, ++position); if(cigarElement.getOperator() == CigarOperator.D) { Assert.assertEquals(collectSamErrorMetrics.processDeletionLocus(new SamLocusIterator.RecordAndOffset(deletionRecord, 0), locusInfo), (boolean) expected.get(iExpected++)); } } } }

Target:
public void testHasDeletionBeenProcessed(final String cigarString, final List<Boolean> expected) { final Cigar cigar = TextCigarCodec.decode(cigarString); final SAMRecord deletionRecord = createRecordFromCigar(cigar.toString()); final CollectSamErrorMetrics collectSamErrorMetrics = new CollectSamErrorMetrics(); final SAMSequenceRecord samSequenceRecord = new SAMSequenceRecord("chr1", 2000); int position = 100; int iExpected = 0; for(CigarElement cigarElement : cigar.getCigarElements()) { for(int iCigarElementPosition = 0; iCigarElementPosition < cigarElement.getLength(); iCigarElementPosition++) { final SamLocusIterator.LocusInfo locusInfo = new SamLocusIterator.LocusInfo(samSequenceRecord, ++position); if(cigarElement.getOperator() == CigarOperator.D) { Assert.assertEquals(collectSamErrorMetrics.processDeletionLocus(new SamLocusIterator.RecordAndOffset(deletionRecord, 0), locusInfo), (boolean) expected.get(iExpected++)); } } } }
Source:
public static char[][][] internQualifiedNames(char[][][] qualifiedNames, boolean keepWellKnown) { if (qualifiedNames == null) return EmptyQualifiedNames; int length = qualifiedNames.length; if (length == 0) return EmptyQualifiedNames; char[][][] keepers = new char[length][][]; char[][] prev = null; boolean isSorted = true; int index = 0; next : for (int i = 0; i < length; i++) { char[][] qualifiedName = qualifiedNames[i]; int qLength = qualifiedName.length; for (int j = 0, m = WellKnownQualifiedNames.length; j < m; j++) { char[][] wellKnownName = WellKnownQualifiedNames[j]; if (qLength > wellKnownName.length) break; if (CharOperation.equals(qualifiedName, wellKnownName)) { if (keepWellKnown) { if (isSorted) { if (prev == null) { prev = qualifiedName; } else { if (compareCharCharArray(prev, wellKnownName) > 0) { isSorted = false; } prev = qualifiedName; } } keepers[index++] = wellKnownName; } continue next; } } QualifiedNameSet internedNames = InternedQualifiedNames[qLength <= MaxQualifiedNames ? qLength - 1 : 0]; qualifiedName = internSimpleNames(qualifiedName, false, false); if (isSorted) { if (prev == null) { prev = qualifiedName; } else { if (compareCharCharArray(prev, qualifiedName) > 0) { isSorted = false; } prev = qualifiedName; } } keepers[index++] = internedNames.add(qualifiedName); } if (length > index) { if (index == 0) return EmptyQualifiedNames; System.arraycopy(keepers, 0, keepers = new char[index][][], 0, index); } if (!isSorted) { Arrays.sort(keepers, CHAR_CHAR_ARR_COMPARATOR); } return keepers; }

Target:
public static char[][][] internQualifiedNames(char[][][] qualifiedNames, boolean keepWellKnown) { if (qualifiedNames == null) return EmptyQualifiedNames; int length = qualifiedNames.length; if (length == 0) return EmptyQualifiedNames; char[][][] keepers = new char[length][][]; char[][] prev = null; boolean isSorted = true; int index = 0; next : for (int i = 0; i < length; i++) { char[][] qualifiedName = qualifiedNames[i]; int qLength = qualifiedName.length; for (int j = 0, m = WellKnownQualifiedNames.length; j < m; j++) { char[][] wellKnownName = WellKnownQualifiedNames[j]; if (qLength > wellKnownName.length) break; if (CharOperation.equals(qualifiedName, wellKnownName)) { if (keepWellKnown) { if (isSorted) { if (prev != null && compareCharCharArray(prev, qualifiedName) > 0) { isSorted = false; } prev = qualifiedName; } keepers[index++] = wellKnownName; } continue next; } } QualifiedNameSet internedNames = InternedQualifiedNames[qLength <= MaxQualifiedNames ? qLength - 1 : 0]; qualifiedName = internSimpleNames(qualifiedName, false, false); if (isSorted) { if (prev != null && compareCharCharArray(prev, qualifiedName) > 0) { isSorted = false; } prev = qualifiedName; } keepers[index++] = internedNames.add(qualifiedName); } if (length > index) { if (index == 0) return EmptyQualifiedNames; System.arraycopy(keepers, 0, keepers = new char[index][][], 0, index); } if (!isSorted) { Arrays.sort(keepers, CHAR_CHAR_ARR_COMPARATOR); } return keepers; }
Source:
private SymbolStatsEstimate estimateCoalesce(SymbolStatsEstimate left, SymbolStatsEstimate right) { if (left.getNullsFraction() == 0) { return left; } else if (left.getNullsFraction() == 1.0) { return right; } else { return SymbolStatsEstimate.builder() .setLowValue(min(left.getLowValue(), right.getLowValue())) .setHighValue(max(left.getHighValue(), right.getLowValue())) .setDistinctValuesCount(left.getDistinctValuesCount() + min(right.getDistinctValuesCount(), input.getOutputRowCount() * left.getNullsFraction())) .setNullsFraction(left.getNullsFraction() * right.getNullsFraction()) .setAverageRowSize(max(left.getAverageRowSize(), right.getAverageRowSize())) .build(); } }

Target:
private SymbolStatsEstimate estimateCoalesce(SymbolStatsEstimate left, SymbolStatsEstimate right) { if (left.getNullsFraction() == 0) { return left; } else if (left.getNullsFraction() == 1.0) { return right; } else { return SymbolStatsEstimate.builder() .setLowValue(min(left.getLowValue(), right.getLowValue())) .setHighValue(max(left.getHighValue(), right.getHighValue())) .setDistinctValuesCount(left.getDistinctValuesCount() + min(right.getDistinctValuesCount(), input.getOutputRowCount() * left.getNullsFraction())) .setNullsFraction(left.getNullsFraction() * right.getNullsFraction()) .setAverageRowSize(max(left.getAverageRowSize(), right.getAverageRowSize())) .build(); } }
Source:
public void login() { }

Target:
public void login() throws Exception { URL url = new URL(repositoryUrl + "api/json/authorize"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); LoginCredentialParams credentials = new LoginCredentialParams(); credentials.setUsername(username); credentials.setPassword(password); ObjectMapper objectMapper = new ObjectMapper(); conn.setRequestMethod("POST"); conn.setRequestProperty("Authentication", "Bearer " + token.getToken()); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(objectMapper.writeValueAsString(credentials)); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = in.readLine(); in.close(); token = objectMapper.readValue(response, AuthenticationResult.class); } else { throw new LoginException(); } }
Source:
public void nodesAdded(Collection<DiscoveryDruidNode> nodesDiscovered) { synchronized (lock) { List<DiscoveryDruidNode> nodesAdded = new ArrayList<>(); for (DiscoveryDruidNode node : nodesDiscovered) { if (node.getServices().containsKey(service)) { DiscoveryDruidNode prev = nodes.putIfAbsent(node.getDruidNode().getHostAndPortToUse(), node); if (prev == null) { nodesAdded.add(node); } else { log.warn("Node[%s] discovered but already exists [%s].", node, prev); } } else { log.warn("Node[%s] discovered but doesn't have service[%s]. Ignored.", node, service); } } if (!nodesAdded.isEmpty()) { Collection<DiscoveryDruidNode> unmodifiableNodesAdded = Collections.unmodifiableCollection(nodesAdded); for (Listener listener : listeners) { try { listener.nodesAdded(unmodifiableNodesAdded); } catch (Exception ex) { log.error(ex, "Listener[%s].nodesAdded(%s) threw exception. Ignored.", listener, nodesAdded); } } } } }

Target:
public void nodesAdded(Collection<DiscoveryDruidNode> nodesDiscovered) { synchronized (lock) { List<DiscoveryDruidNode> nodesAdded = new ArrayList<>(); for (DiscoveryDruidNode node : nodesDiscovered) { if (node.getServices().containsKey(service)) { DiscoveryDruidNode prev = nodes.putIfAbsent(node.getDruidNode().getHostAndPortToUse(), node); if (prev == null) { nodesAdded.add(node); } else { log.warn("Node[%s] discovered but already exists [%s].", node, prev); } } else { log.warn("Node[%s] discovered but doesn't have service[%s]. Ignored.", node, service); } } if (nodesAdded.isEmpty()) { return; } Collection<DiscoveryDruidNode> unmodifiableNodesAdded = Collections.unmodifiableCollection(nodesAdded); for (Listener listener : listeners) { try { listener.nodesAdded(unmodifiableNodesAdded); } catch (Exception ex) { log.error(ex, "Listener[%s].nodesAdded(%s) threw exception. Ignored.", listener, nodesAdded); } } } }
Source:
public static CustomRestClient get() { if (INSTANCE == null) { synchronized (CustomRestClientFactory.class) { if (INSTANCE == null) { try { final int httpRequestTimeout = HelixUtil.getSystemPropertyAsInt(RestSystemPropertyKeys.HTTP_TIMEOUT_MS, 60 * 1000); HttpClient httpClient; RequestConfig config = RequestConfig.custom().setConnectTimeout(httpRequestTimeout) .setConnectionRequestTimeout(httpRequestTimeout) .setSocketTimeout(httpRequestTimeout).build(); if (HelixRestServer.REST_SERVER_SSL_CONTEXT != null) { httpClient = HttpClients.custom().setSSLContext(HelixRestServer.REST_SERVER_SSL_CONTEXT) .setSSLSocketFactory(new SSLConnectionSocketFactory( HelixRestServer.REST_SERVER_SSL_CONTEXT, new NoopHostnameVerifier())) .setDefaultRequestConfig(config).build(); } else { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } INSTANCE = new CustomRestClientImpl(httpClient); return INSTANCE; } catch (Exception e) { LOG.error("Exception when initializing CustomRestClient", e); } } } } return INSTANCE; }

Target:
public static CustomRestClient get() { if (INSTANCE == null) { synchronized (CustomRestClientFactory.class) { if (INSTANCE == null) { try { HttpClient httpClient; RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_REQUEST_TIMEOUT) .setConnectionRequestTimeout(HTTP_REQUEST_TIMEOUT) .setSocketTimeout(HTTP_REQUEST_TIMEOUT).build(); if (HelixRestServer.REST_SERVER_SSL_CONTEXT != null) { httpClient = HttpClients.custom().setSSLContext(HelixRestServer.REST_SERVER_SSL_CONTEXT) .setSSLSocketFactory(new SSLConnectionSocketFactory( HelixRestServer.REST_SERVER_SSL_CONTEXT, new NoopHostnameVerifier())) .setDefaultRequestConfig(config).build(); } else { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } INSTANCE = new CustomRestClientImpl(httpClient); return INSTANCE; } catch (Exception e) { LOG.error("Exception when initializing CustomRestClient", e); } } } } return INSTANCE; }
Source:
protected CommandBase(T parameters) { _parameters = parameters; DbUser user = SessionDataContainer.getInstance().addUserToThreadContext(parameters.getSessionId(), true); if (user != null) { setCurrentUser(user); } else if (parameters.getParametersCurrentUser() != null) { setCurrentUser(parameters.getParametersCurrentUser()); } if (!parameters.getMultipleAction()) { ThreadLocalParamsContainer.setCorrelationId(parameters.getCorrelationId()); } setCorrelationId(parameters.getCorrelationId()); Guid commandIdFromParameters = parameters.getCommandId(); if (commandIdFromParameters == null) { commandIdFromParameters = Guid.newGuid(); getParameters().setCommandId(commandIdFromParameters); } commandId = commandIdFromParameters; taskHandlers = initTaskHandlers(); }

Target:
protected CommandBase(T parameters) { _parameters = parameters; DbUser user = SessionDataContainer.getInstance().addUserToThreadContext(parameters.getSessionId(), true); if (user != null) { setCurrentUser(user); } else if (parameters.getParametersCurrentUser() != null) { setCurrentUser(parameters.getParametersCurrentUser()); } setCorrelationId(parameters.getCorrelationId()); Guid commandIdFromParameters = parameters.getCommandId(); if (commandIdFromParameters == null) { commandIdFromParameters = Guid.newGuid(); getParameters().setCommandId(commandIdFromParameters); } commandId = commandIdFromParameters; taskHandlers = initTaskHandlers(); }
Source:
private static Set<Integer> determineRequiredIndexes(Annotation[][] typeAnnotations) { Set<Integer> result = new HashSet<Integer>(); for (int i = 0; i < typeAnnotations.length; i++) { boolean isOptional = false; Annotation[] typeAnnotation = typeAnnotations[i]; if (typeAnnotation.length > 0) { for (Annotation annotation: typeAnnotation) { if (annotation.annotationType().equals(Optional.class)) { isOptional = true; } } } if (!isOptional) { result.add(i); } } return result; }

Target:
private static Set<Integer> determineRequiredIndexes(Annotation[][] typeAnnotations) { Set<Integer> result = new HashSet<Integer>(); for (int i = 0; i < typeAnnotations.length; i++) { boolean isOptional = false; Annotation[] typeAnnotation = typeAnnotations[i]; if (typeAnnotation.length > 0) { for (Annotation annotation: typeAnnotation) { if (annotation.annotationType().equals(Optional.class)) { isOptional = true; break; } } } if (!isOptional) { result.add(i); } } return result; }
Source:
public CDPStructuredEventEntity convert(CDPStructuredEvent source) { try { CDPStructuredEventEntity structuredEventEntity = new CDPStructuredEventEntity(); structuredEventEntity.setStructuredEventJson(new Json(source)); CDPOperationDetails operationDetails = source.getOperation(); structuredEventEntity.setEventType(operationDetails.getEventType()); structuredEventEntity.setResourceType(operationDetails.getResourceType()); structuredEventEntity.setResourceCrn(operationDetails.getResourceCrn()); structuredEventEntity.setTimestamp(operationDetails.getTimestamp()); structuredEventEntity.setAccountId(source.getOperation().getAccountId()); return structuredEventEntity; } catch (IllegalArgumentException e) { LOGGER.error("Failed to parse structured event JSON", e); return null; } }

Target:
public CDPStructuredEventEntity convert(CDPStructuredEvent source) { try { CDPStructuredEventEntity structuredEventEntity = new CDPStructuredEventEntity(); structuredEventEntity.setStructuredEventJson(new Json(source)); CDPOperationDetails operationDetails = source.getOperation(); structuredEventEntity.setEventType(operationDetails.getEventType()); structuredEventEntity.setResourceType(operationDetails.getResourceType()); structuredEventEntity.setResourceCrn(operationDetails.getResourceCrn()); structuredEventEntity.setTimestamp(operationDetails.getTimestamp()); structuredEventEntity.setAccountId(source.getOperation().getAccountId()); return structuredEventEntity; } catch (IllegalArgumentException e) { LOGGER.error("Failed to parse structured event JSON, source: {}", source.getType(), e); return null; } }
Source:
public synchronized void addSharedInformerEventListener(SharedInformerEventListener event) { this.eventListeners.add(event); }

Target:
public void addSharedInformerEventListener(SharedInformerEventListener event) { this.eventListeners.add(event); }
Source:
public void returnArray(int[] array) { requireNonNull(array, "array is null"); checkState(outstandingArrays > 0, "Returned more arrays than leased"); outstandingArrays--; intArrays.push(array); }

Target:
public void returnArray(int[] array) { requireNonNull(array, "array is null"); checkArgument(borrowedIntArrays.remove(array), "Returned int array which was not borrowed"); intArrays.push(array); }
Source:
public int postZgloszenia(Zgloszenia zgloszenia) throws Exception { Statement statement; ResultSet resultSet; try { connection.establishConnection(); statement = connection.getConnection().createStatement(); resultSet = statement.executeQuery("SELECT addZgloszenie(" + zgloszenia.getId_uzytkownika() + ", " + zgloszenia.getId_typu() + ", " + zgloszenia.getId_disqus() + ", POINT(" + zgloszenia.getWspolrzedne().x + ", " + zgloszenia.getWspolrzedne().y + "))"); while (resultSet.next()) { } } catch (Exception ex) { if (!ex.toString().contains("Zapytanie nie zwróciło żadnych wyników.")) { System.out.println("Zapytanie nie zostalo wykonane: " + ex.toString()); connection.closeConnection(); return 500; } } connection.closeConnection(); System.out.println("Zapytanie wykonane pomyslenie"); return 200; }

Target:
public int postZgloszenia(Zgloszenia zgloszenia) throws Exception { Statement statement; ResultSet resultSet; try { connection.establishConnection(); statement = connection.getConnection().createStatement(); resultSet = statement.executeQuery("SELECT addZgloszenie(" + zgloszenia.getId_uzytkownika() + ", " + zgloszenia.getId_typu() + ", " + zgloszenia.getId_disqus() + ", POINT(" + zgloszenia.getWspolrzedne().x + ", " + zgloszenia.getWspolrzedne().y + "))"); } catch (Exception ex) { if (!ex.toString().contains("Zapytanie nie zwrocilo zadnych wynikow.")) { System.out.println("Zapytanie nie zostalo wykonane: " + ex.toString()); connection.closeConnection(); return 500; } } connection.closeConnection(); System.out.println("Zapytanie wykonane pomyslenie"); return 200; }
Source:
private void processQueuedFlows(long activeExecutorsRefreshWindow, int maxContinuousFlowProcessed) throws InterruptedException, ExecutorManagerException { long lastExecutorRefreshTime = 0; Pair<ExecutionReference, ExecutableFlow> runningCandidate; int currentContinuousFlowProcessed = 0; while (isActive() && (runningCandidate = queuedFlows.fetchHead()) != null) { ExecutionReference reference = runningCandidate.getFirst(); ExecutableFlow exflow = runningCandidate.getSecond(); long currentTime = System.currentTimeMillis(); if (currentTime - lastExecutorRefreshTime > activeExecutorsRefreshWindow || currentContinuousFlowProcessed >= maxContinuousFlowProcessed) { refreshExecutors(); lastExecutorRefreshTime = currentTime; currentContinuousFlowProcessed = 0; } if(exflow.getUpdateTime() > lastExecutorRefreshTime) { queuedFlows.enqueue(exflow, reference); long sleepInterval = activeExecutorsRefreshWindow - (currentTime - lastExecutorRefreshTime); sleep(sleepInterval); } else { exflow.setUpdateTime(currentTime); processFlow(reference, exflow, new HashSet<Executor>(activeExecutors)); } currentContinuousFlowProcessed++; } }

Target:
private void processQueuedFlows(long activeExecutorsRefreshWindow, int maxContinuousFlowProcessed) throws InterruptedException, ExecutorManagerException { long lastExecutorRefreshTime = 0; Pair<ExecutionReference, ExecutableFlow> runningCandidate; int currentContinuousFlowProcessed = 0; while (isActive() && (runningCandidate = queuedFlows.fetchHead()) != null) { ExecutionReference reference = runningCandidate.getFirst(); ExecutableFlow exflow = runningCandidate.getSecond(); long currentTime = System.currentTimeMillis(); if (currentTime - lastExecutorRefreshTime > activeExecutorsRefreshWindow || currentContinuousFlowProcessed >= maxContinuousFlowProcessed) { refreshExecutors(); lastExecutorRefreshTime = currentTime; currentContinuousFlowProcessed = 0; } if(exflow.getUpdateTime() > lastExecutorRefreshTime) { queuedFlows.enqueue(exflow, reference); long sleepInterval = activeExecutorsRefreshWindow - (currentTime - lastExecutorRefreshTime); sleep(sleepInterval); } else { exflow.setUpdateTime(currentTime); selectExecutorAndDispatchFlow(reference, exflow, new HashSet<Executor>(activeExecutors)); } currentContinuousFlowProcessed++; } }
Source:
public List<PluginInfo> allPluginInfos(String type) { List<PluginInfo> plugins = new ArrayList<>(); if (type != null) { return pluginExtensionToBuilder.containsKey(type) ? pluginExtensionToBuilder.get(type).allPluginInfos() : plugins; } for (ViewModelBuilder builder : pluginExtensionToBuilder.values()) { plugins.addAll(builder.allPluginInfos()); } return plugins; }

Target:
public List<PluginInfo> allPluginInfos(String type) { List<PluginInfo> plugins = new ArrayList<>(); if (type != null) { if (!pluginExtensionToBuilder.containsKey(type)) { throw new InvalidPluginTypeException(); } return pluginExtensionToBuilder.get(type).allPluginInfos(); } for (ViewModelBuilder builder : pluginExtensionToBuilder.values()) { plugins.addAll(builder.allPluginInfos()); } return plugins; }
Source:
private void packHeads(ProgressMonitor pm, HashSet<ObjectId> allHeads) throws IOException { if (allHeads.isEmpty()) return; PackWriter pw = new PackWriter(repo); try { pw.preparePack(pm, allHeads, Collections.<ObjectId> emptySet()); if (0 < pw.getObjectCount()) { ObjectId id = pw.computeName(); File pack = nameFor(objdb, id, ".pack"); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(pack)); try { pw.writePack(pm, pm, out); } finally { out.close(); } pack.setReadOnly(); File idx = nameFor(objdb, id, ".idx"); out = new BufferedOutputStream(new FileOutputStream(idx)); try { pw.writeIndex(out); } finally { out.close(); } idx.setReadOnly(); objdb.openPack(pack, idx); } } finally { pw.release(); } }

Target:
private PackFile packHeads(ProgressMonitor pm, HashSet<ObjectId> allHeads) throws IOException { if (allHeads.isEmpty()) return null; return writePack(pm, allHeads, Collections.<ObjectId> emptySet()); }
Source:
private void readProjectWizardActions() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = win.getActivePage(); String[] wizardIds = page.getNewWizardShortcuts(); projectWizardActions.clear(); for (String wizardId : wizardIds) { IWizardDescriptor wizardDesc = WorkbenchPlugin.getDefault().getNewWizardRegistry().findWizard(wizardId); if (wizardDesc == null) continue; String[] tags = wizardDesc.getTags(); for (String tag : tags) { if (WorkbenchWizardElement.TAG_PROJECT.equals(tag)) { IAction action = getAction(WorkbenchPlugin.getDefault().getNewWizardRegistry(), wizardId); projectWizardActions.add(action); } } } }

Target:
private void readProjectWizardActions() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = win.getActivePage(); String[] wizardIds = page.getNewWizardShortcuts(); projectWizardActions.clear(); for (String wizardId : wizardIds) { IWizardRegistry newWizardRegistry = WorkbenchPlugin.getDefault().getNewWizardRegistry(); IWizardDescriptor wizardDesc = newWizardRegistry.findWizard(wizardId); if (wizardDesc == null) { continue; } String[] tags = wizardDesc.getTags(); for (String tag : tags) { if (WorkbenchWizardElement.TAG_PROJECT.equals(tag)) { IAction action = getAction(newWizardRegistry, wizardId); projectWizardActions.add(action); } } } }
Source:
public ObjectLockConfiguration(RetentionMode mode, RetentionDuration duration) throws IllegalArgumentException { if (mode != null && duration != null) { this.rule = new Rule(mode, duration); } if (mode == null || duration == null) { throw new IllegalArgumentException("mode or duration is null"); } }

Target:
public ObjectLockConfiguration(RetentionMode mode, RetentionDuration duration) throws IllegalArgumentException { if (mode != null && duration != null) { this.rule = new Rule(mode, duration); } else if (mode != null || duration != null) { if (mode == null) { throw new IllegalArgumentException("mode is null"); } throw new IllegalArgumentException("duration is null"); } }
Source:
public Set<Object> getProviderInstances() { if (providerInstances == null && parent != null) return parent.getProviderInstances(); return providerInstances; }

Target:
public Set<Object> getProviderInstances() { if(initialized) { return providerInstances; } Set<Object> set = new HashSet<Object>(); if (parent != null) set.addAll(parent.getProviderInstances()); set.addAll(providerInstances); return set; }
Source:
public void testArchiveAction() throws Exception { Url coursesUrl = createUrl(Const.ActionURIs.INSTRUCTOR_COURSES_PAGE) .withUserId(testData.accounts.get("instructorWithCourses").googleId); coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); ______TS("archive action success"); String courseId = "CCAddUiTest.CS1101"; coursesPage.archiveCourse(courseId); coursesPage.verifyHtml("/instructorCourseArchiveSuccessful.html"); ______TS("unarchive action success"); coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); coursesPage.unarchiveCourse(courseId); coursesPage.verifyHtml("/instructorCourseUnarchiveSuccessful.html"); ______TS("archive action failed"); String anotherCourseId = "CCAddUiTest.CS2104"; coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); BackDoor.deleteCourse(anotherCourseId); coursesPage.archiveCourse(anotherCourseId); coursesPage.verifyHtml("/instructorCourseArchiveFailed.html"); ______TS("unarchive action failed"); coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); coursesPage.archiveCourse(courseId); BackDoor.deleteCourse(courseId); coursesPage.unarchiveCourse(courseId); coursesPage.verifyHtml("/instructorCourseArchiveFailed.html"); }

Target:
public void testArchiveAction() throws Exception { Url coursesUrl = createUrl(Const.ActionURIs.INSTRUCTOR_COURSES_PAGE) .withUserId(testData.accounts.get("instructorWithCourses").googleId); coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); ______TS("archive action success"); String courseId = "CCAddUiTest.CS1101"; coursesPage.archiveCourse(courseId); coursesPage.verifyHtml("/instructorCourseArchiveSuccessful.html"); ______TS("unarchive action success"); coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); coursesPage.unarchiveCourse(courseId); coursesPage.verifyHtml("/instructorCourseUnarchiveSuccessful.html"); ______TS("archive action failed"); String anotherCourseId = "CCAddUiTest.CS2104"; coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); BackDoor.deleteCourse(anotherCourseId); coursesPage.archiveCourse(anotherCourseId); coursesPage.verifyContains("You are not authorized to view this page."); ______TS("unarchive action failed"); coursesPage = loginAdminToPage(browser, coursesUrl, InstructorCoursesPage.class); coursesPage.archiveCourse(courseId); BackDoor.deleteCourse(courseId); coursesPage.unarchiveCourse(courseId); coursesPage.verifyContains("You are not authorized to view this page."); }
Source:
private String getAdminTenantId (ClaudiaData data) { try { OpenStackAccess openStackAccess = this.openStackRegion.getTokenAdmin(); return openStackAccess.getTenantId(); } catch (Exception e) { return null; } }

Target:
private String getAdminTenantId (ClaudiaData data) { String tenantAdminId = null; try { OpenStackAccess openStackAccess = this.openStackRegion.getTokenAdmin(); tenantAdminId = openStackAccess.getTenantId(); } catch (Exception e) { log.warn("No admin token found"); } return tenantAdminId; }
Source:
public int compare(Declaration d1, Declaration d2) { if (equals(d1, d2)) { return 0; } SourcePosition p1 = d1.getPosition(); SourcePosition p2 = d2.getPosition(); if (p1 == null && p2 != null) { return 1; } else if (p1 != null && p2 == null) { return -1; } else if (p1 == null && p2 == null) { return compareEqualPosition(d1, d2); } assert p1 != null && p2 != null; int fileComp = p1.file().compareTo(p2.file()) ; if (fileComp == 0) { long diff = (long)p1.line() - (long)p2.line(); if (diff == 0) { diff = Long.signum((long)p1.column() - (long)p2.column()); if (diff != 0) { return (int)diff; } else { return compareEqualPosition(d1, d2); } } else { return (diff<0)? -1 : 1; } } else return fileComp; }

Target:
public int compare(Declaration d1, Declaration d2) { if (equals(d1, d2)) return 0; SourcePosition p1 = d1.getPosition(); SourcePosition p2 = d2.getPosition(); if (p1 == null && p2 != null) return 1; else if (p1 != null && p2 == null) return -1; else if(p1 == null && p2 == null) return compareEqualPosition(d1, d2); else { assert p1 != null && p2 != null; int fileComp = p1.file().compareTo(p2.file()) ; if (fileComp == 0) { long diff = (long)p1.line() - (long)p2.line(); if (diff == 0) { diff = Long.signum((long)p1.column() - (long)p2.column()); if (diff != 0) return (int)diff; else { return compareEqualPosition(d1, d2); } } else return (diff<0)? -1:1; } else return fileComp; } }
Source:
private void onCallControllerAction(final String controllerId, final String actionName, final Map<String, Object> params) { Assert.requireNonBlank(controllerId, "controllerId"); Assert.requireNonBlank(actionName, "actionName"); Assert.requireNonNull(params, "params"); final ServerControllerActionCallBean bean = platformBeanRepository.getControllerActionCallBean(); Assert.requireNonNull(bean, "bean"); if (platformBeanRepository == null) { throw new IllegalStateException("An action was called before the init-command was sent."); } final Metric metric = ServerTimingFilter.getCurrentTiming().start("RemotingActionCall:"+actionName, "Remote action call"); try { controllerHandler.invokeAction(controllerId, actionName, params); } catch (Exception e) { LOG.error("Unexpected exception while invoking action on controller {}", actionName, controllerId, e); bean.setError(true); } finally { metric.stop(); } }

Target:
private void onCallControllerAction(final String controllerId, final String actionName, final Map<String, Object> params) { Assert.requireNonBlank(controllerId, "controllerId"); Assert.requireNonBlank(actionName, "actionName"); Assert.requireNonNull(params, "params"); final ServerControllerActionCallBean bean = platformBeanRepository.getControllerActionCallBean(); Assert.requireNonNull(bean, "bean"); if (platformBeanRepository == null) { throw new IllegalStateException("An action was called before the init-command was sent."); } final Metric metric = ServerTimingFilter.getCurrentTiming().start("RemotingActionCall:"+actionName, "Remote action call"); try { controllerHandler.invokeAction(controllerId, actionName, params); } catch (final Exception e) { LOG.error("Unexpected exception while invoking action on controller {}", actionName, controllerId, e); bean.setError(true); } finally { metric.stop(); } }
Source:
public Map<String, String> allocate( Network network, VnicProfile vnicProfile, VmNic nic, VDS host, boolean ignoreSecurityGroupsOnUpdate, String hostBindingId) { Port port = locatePort(nic); List<String> securityGroups = getSecurityGroups(vnicProfile); if (port == null) { com.woorea.openstack.quantum.model.Network externalNetwork = getExternalNetwork(network.getProvidedBy()); Port portForCreate = createNewPortForAllocate(nic, securityGroups, hostBindingId, externalNetwork); port = execute(getClient().ports().create(portForCreate)); } else { boolean securityGroupsChanged = !ignoreSecurityGroupsOnUpdate && securityGroupsChanged(port.getSecurityGroups(), securityGroups); updatePort(port, securityGroupsChanged, securityGroups, hostBindingId, nic); } Map<String, String> runtimeProperties = createPortAllocationRuntimeProperties(port); return runtimeProperties; }

Target:
public Map<String, String> allocate( Network network, VnicProfile vnicProfile, VmNic nic, VDS host, boolean ignoreSecurityGroupsOnUpdate, String hostBindingId) { if (hostBindingId==null) { hostBindingId = getHostId(host); log.warn("Host binding id for external network on host is null, using host id to allocate vNIC " + " instead. Please provide an after_get_caps hook for the plugin type on host {}", network.getName(), host.getName(), hostBindingId, nic.getName(), getProvider().getAdditionalProperties().getPluginType() , host.getName()); } Port port = locatePort(nic); List<String> securityGroups = getSecurityGroups(vnicProfile); if (port == null) { com.woorea.openstack.quantum.model.Network externalNetwork = getExternalNetwork(network.getProvidedBy()); Port portForCreate = createNewPortForAllocate(nic, securityGroups, hostBindingId, externalNetwork); port = execute(getClient().ports().create(portForCreate)); } else { boolean securityGroupsChanged = !ignoreSecurityGroupsOnUpdate && securityGroupsChanged(port.getSecurityGroups(), securityGroups); updatePort(port, securityGroupsChanged, securityGroups, hostBindingId, nic); } Map<String, String> runtimeProperties = createPortAllocationRuntimeProperties(port); return runtimeProperties; }
Source:
public synchronized void playVideoModel(final DownloadEntry video) { try { if (playerFragment.isPlaying()) { if (video.getVideoId().equals(playerFragment.getPlayingVideo().getVideoId())) { logger.debug("this video is already being played, skipping play event"); return; } } } catch (Exception ex) { logger.debug(ex.toString()); } try { environment.getStorage().reloadDownloadEntry(video); logger.debug("Resumed= " + playerFragment.isResumed()); if (!playerFragment.isResumed()) { if (playPending != null) { playHandler.removeCallbacks(playPending); } playPending = new Runnable() { public void run() { playVideoModel(video); } }; playHandler.postDelayed(playPending, 200); return; } else { if (playPending != null) { playHandler.removeCallbacks(playPending); } } TranscriptModel transcript = getTranscriptModel(video); String filepath = getVideoPath(video); playerFragment.prepare(filepath, video.lastPlayedOffset, video.getTitle(), transcript, video); try { if (chapterName == null) { chapterName = video.chapter; } videoModel = video; } catch (Exception e) { logger.error(e); } } catch (Exception ex) { logger.error(ex); } }

Target:
public synchronized void playVideoModel(final DownloadEntry video) { try { if (playerFragment.isPlaying()) { if (video.getVideoId().equals(playerFragment.getPlayingVideo().getVideoId())) { logger.debug("this video is already being played, skipping play event"); return; } } } catch (Exception ex) { logger.debug(ex.toString()); } try { environment.getStorage().reloadDownloadEntry(video); logger.debug("Resumed= " + playerFragment.isResumed()); if (!playerFragment.isResumed()) { if (playPending != null) { playHandler.removeCallbacks(playPending); } playPending = () -> playVideoModel(video); playHandler.postDelayed(playPending, 200); return; } else { if (playPending != null) { playHandler.removeCallbacks(playPending); } } TranscriptModel transcript = getTranscriptModel(); String filepath = getVideoPath(video); playerFragment.prepare(filepath, video.lastPlayedOffset, video.getTitle(), transcript, video); try { if (chapterName == null) { chapterName = video.chapter; } videoModel = video; } catch (Exception e) { logger.error(e); } } catch (Exception ex) { logger.error(ex); } }
Source:
private PartitionStatistics updatePartitionStatistics(PartitionStatistics oldPartitionStats, PartitionStatistics newPartitionStats) { HiveBasicStatistics oldBasicStatistics = oldPartitionStats.getBasicStatistics(); HiveBasicStatistics newBasicStats = newPartitionStats.getBasicStatistics(); HiveBasicStatistics basicStatistics = new HiveBasicStatistics( newBasicStats.getFileCount().isPresent() ? newBasicStats.getFileCount() : oldBasicStatistics.getFileCount(), newBasicStats.getRowCount().isPresent() ? newBasicStats.getRowCount() : oldBasicStatistics.getRowCount(), newBasicStats.getInMemoryDataSizeInBytes().isPresent() ? newBasicStats.getInMemoryDataSizeInBytes() : oldBasicStatistics.getInMemoryDataSizeInBytes(), newBasicStats.getOnDiskDataSizeInBytes().isPresent() ? newBasicStats.getOnDiskDataSizeInBytes() : oldBasicStatistics.getOnDiskDataSizeInBytes()); return new PartitionStatistics(basicStatistics, newPartitionStats.getColumnStatistics()); }

Target:
private PartitionStatistics updatePartitionStatistics(PartitionStatistics oldPartitionStats, PartitionStatistics newPartitionStats) { HiveBasicStatistics oldBasicStatistics = oldPartitionStats.getBasicStatistics(); HiveBasicStatistics newBasicStatistics = newPartitionStats.getBasicStatistics(); HiveBasicStatistics updatedBasicStatistics = new HiveBasicStatistics( firstPresent(newBasicStatistics.getFileCount(), oldBasicStatistics.getFileCount()), firstPresent(newBasicStatistics.getRowCount(), oldBasicStatistics.getRowCount()), firstPresent(newBasicStatistics.getInMemoryDataSizeInBytes(), oldBasicStatistics.getInMemoryDataSizeInBytes()), firstPresent(newBasicStatistics.getOnDiskDataSizeInBytes(), oldBasicStatistics.getOnDiskDataSizeInBytes())); return new PartitionStatistics(updatedBasicStatistics, newPartitionStats.getColumnStatistics()); }
Source:
public void assertExecute() { AtomicInteger counter = new AtomicInteger(0); final OneOffJobBootstrap oneOffJobBootstrap = new OneOffJobBootstrap(zkRegCenter, (SimpleJob) shardingContext -> { counter.incrementAndGet(); }, JobConfiguration.newBuilder("test_one_off_job_execute", SHARDING_TOTAL_COUNT).build()); oneOffJobBootstrap.execute(); blockUtilFinish(oneOffJobBootstrap); assertThat(SHARDING_TOTAL_COUNT, is(counter.get())); getJobScheduler(oneOffJobBootstrap).shutdown(); }

Target:
public void assertExecute() { AtomicInteger counter = new AtomicInteger(0); final OneOffJobBootstrap oneOffJobBootstrap = new OneOffJobBootstrap(zkRegCenter, (SimpleJob) shardingContext -> { counter.incrementAndGet(); }, JobConfiguration.newBuilder("test_one_off_job_execute", SHARDING_TOTAL_COUNT).build()); oneOffJobBootstrap.execute(); blockUtilFinish(oneOffJobBootstrap); assertThat(counter.get(), is(SHARDING_TOTAL_COUNT)); getJobScheduler(oneOffJobBootstrap).shutdown(); }
Source:
protected void eventHandle(@NonNull ITmfEvent event) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); long t = event.getTimestamp().toNanos(); String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); if (ss == null || !ACCEPTED.contains(phase)) { return; } String nameField = event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME); String idField = event.getContent().getFieldValue(String.class, ITraceEventConstants.ID); String catField = event.getContent().getFieldValue(String.class, ITraceEventConstants.CATEGORY); if (Objects.equals(phase, "(")) { int quark = ss.getQuarkAbsoluteAndAdd(catField, nameField, idField); ss.modifyAttribute(t, 1, quark); } if (Objects.equals(phase, ")")) { int quark = ss.getQuarkAbsoluteAndAdd(catField, nameField, idField); ss.modifyAttribute(t, (Object)null, quark); } }

Target:
protected void eventHandle(@NonNull ITmfEvent event) { ITmfStateSystemBuilder ss = getStateSystemBuilder(); long t = event.getTimestamp().toNanos(); String phase = event.getContent().getFieldValue(String.class, ITraceEventConstants.PHASE); if (ss == null || !ACCEPTED.contains(phase)) { return; } String nameField = event.getContent().getFieldValue(String.class, ITraceEventConstants.NAME); String idField = event.getContent().getFieldValue(String.class, ITraceEventConstants.ID); String catField = event.getContent().getFieldValue(String.class, ITraceEventConstants.CATEGORY); if (Objects.equals(phase, TraceEventPhases.CONTEXT_START)) { int quark = ss.getQuarkAbsoluteAndAdd(catField, nameField, idField); ss.modifyAttribute(t, 1, quark); } if (Objects.equals(phase, TraceEventPhases.CONTEXT_END)) { int quark = ss.getQuarkAbsoluteAndAdd(catField, nameField, idField); ss.modifyAttribute(t, (Object) null, quark); } }
Source:
SecurityAdvisor getChannelAdvisor(final String channelReference) { if (ServerConfigurationService.getBoolean("announcement.merge.visibility.strict", false)) { return (userId, function, reference) -> SecurityAdvisor.SecurityAdvice.PASS; } else { return (userId, function, reference) -> { if (userId.equals(userDirectoryService.getCurrentUser().getId()) && AnnouncementService.SECURE_ANNC_READ.equals(function) && channelReference.equals(reference)) { return SecurityAdvisor.SecurityAdvice.ALLOWED; } else { return SecurityAdvisor.SecurityAdvice.PASS; } }; } }

Target:
SecurityAdvisor getChannelAdvisor(final String channelReference) { if (serverConfigurationService.getBoolean("announcement.merge.visibility.strict", false)) { return (userId, function, reference) -> SecurityAdvisor.SecurityAdvice.PASS; } else { return (userId, function, reference) -> { if (userId.equals(userDirectoryService.getCurrentUser().getId()) && AnnouncementService.SECURE_ANNC_READ.equals(function) && channelReference.equals(reference)) { return SecurityAdvisor.SecurityAdvice.ALLOWED; } else { return SecurityAdvisor.SecurityAdvice.PASS; } }; } }
Source:
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messageList = new ArrayList<>(); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); Assertions.assertTrue(messageList.add(message)); }); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(any(Message.class))).thenReturn(Mono.empty()); when(sendLink.send(anyList())).thenReturn(Mono.empty()); StepVerifier.create(sender.send(messageList)) .verifyComplete(); verify(sendLink).send(messagesCaptor.capture()); final List<org.apache.qpid.proton.message.Message> messagesSent = messagesCaptor.getValue(); Assertions.assertEquals(count, messagesSent.size()); messagesSent.forEach(message -> Assertions.assertEquals(Section.SectionType.Data, message.getBody().getType())); }

Target:
void sendMessagesList() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final List<ServiceBusMessage> messages = TestUtils.getServiceBusMessages(count, UUID.randomUUID().toString()); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(any(Message.class))).thenReturn(Mono.empty()); when(sendLink.send(anyList())).thenReturn(Mono.empty()); StepVerifier.create(sender.send(messages)) .verifyComplete(); verify(sendLink).send(messagesCaptor.capture()); final List<Message> messagesSent = messagesCaptor.getValue(); Assertions.assertEquals(count, messagesSent.size()); messagesSent.forEach(message -> Assertions.assertEquals(Section.SectionType.Data, message.getBody().getType())); }