auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public WrapperHelper compile(Class<?> wrapperType, Method[] setMethods, Method[] getMethods, Method[] jaxbMethods, Field[] fields, Object objectFactory) { int count = 1; String newClassName = wrapperType.getName() + "_WrapperTypeHelper" + count; Class<?> cls = loadClass(newClassName, WrapperHelperClassLoader.class); while (cls != null) { try { WrapperHelper helper = WrapperHelper.class.cast(cls.getDeclaredConstructor().newInstance()); if (!helper.getSignature().equals(WrapperHelperCompiler.computeSignature(setMethods, getMethods))) { count++; newClassName = wrapperType.getName() + "_WrapperTypeHelper" + count; cls = loadClass(newClassName, WrapperHelperClassLoader.class); } else { return helper; } } catch (Exception e) { return null; } } return null; }

Target:
public WrapperHelper compile(Class<?> wrapperType, Method[] setMethods, Method[] getMethods, Method[] jaxbMethods, Field[] fields, Object objectFactory) { int count = 1; String newClassName = wrapperType.getName() + "_WrapperTypeHelper" + count; Class<?> cls = findClass(newClassName, wrapperType); while (cls != null) { try { WrapperHelper helper = WrapperHelper.class.cast(cls.getDeclaredConstructor().newInstance()); if (!helper.getSignature().equals( WrapperHelperClassGenerator.computeSignature(setMethods, getMethods))) { count++; newClassName = wrapperType.getName() + "_WrapperTypeHelper" + count; cls = findClass(newClassName, wrapperType); } else { return helper; } } catch (Exception e) { return null; } } return null; }
Source:
protected Object doExecute() throws Exception { printInitCommand("Shows GRE tunnels"); try { IResource router = getResourceFromFriendlyName(resourceId); IGRETunnelCapability tunnelCapability = (IGRETunnelCapability) router.getCapabilityByInterface(IGRETunnelCapability.class); tunnelCapability.showGRETunnelConfiguration(); List<GRETunnelService> lGRETunnelService = tunnelCapability.showGRETunnelConfiguration(); if (lGRETunnelService == null || lGRETunnelService.isEmpty()) { printInfo("No GRE tunnels configured on the router"); } else { printGRETunnelConfiguration(lGRETunnelService); } return null; } catch (ResourceException e) { printError(e); printEndCommand(); return -1; } catch (Exception e) { printError("Error showing GRE tunnels"); printError(e); printEndCommand(); return -1; } }

Target:
protected Object doExecute() throws Exception { printInitCommand("Shows GRE tunnels"); try { IResource router = getResourceFromFriendlyName(resourceId); IGRETunnelCapability tunnelCapability = (IGRETunnelCapability) router.getCapabilityByInterface(IGRETunnelCapability.class); List<GRETunnelService> lGRETunnelService = tunnelCapability.showGRETunnelConfiguration(); if (lGRETunnelService == null || lGRETunnelService.isEmpty()) { printInfo("No GRE tunnels configured on the router"); } else { printGRETunnelConfiguration(lGRETunnelService); } return null; } catch (ResourceException e) { printError(e); printEndCommand(); return -1; } catch (Exception e) { printError("Error showing GRE tunnels"); printError(e); printEndCommand(); return -1; } }
Source:
private void waitForSilence() { PartitionedRegion region = (PartitionedRegion) cacheRule.getCache().getRegion(REGION_NAME); await().untilAsserted(() -> { PartitionedRegionStats prStats = region.getPrStats(); assertThat(prStats.getVolunteeringInProgress()).isEqualTo(0); assertThat(prStats.getBucketCreatesInProgress()).isEqualTo(0); assertThat(prStats.getPrimaryTransfersInProgress()).isEqualTo(0); assertThat(prStats.getRebalanceBucketCreatesInProgress()).isEqualTo(0); assertThat(prStats.getRebalancePrimaryTransfersInProgress()).isEqualTo(0); }); }

Target:
private void waitForSilence() { DMStats dmStats = cacheRule.getSystem().getDistributionManager().getStats(); PartitionedRegion region = (PartitionedRegion) cacheRule.getCache().getRegion(REGION_NAME); PartitionedRegionStats partitionedRegionStats = region.getPrStats(); await().untilAsserted(() -> { assertThat(dmStats.getReplyWaitsInProgress()).isEqualTo(0); assertThat(partitionedRegionStats.getVolunteeringInProgress()).isEqualTo(0); assertThat(partitionedRegionStats.getBucketCreatesInProgress()).isEqualTo(0); assertThat(partitionedRegionStats.getPrimaryTransfersInProgress()).isEqualTo(0); assertThat(partitionedRegionStats.getRebalanceBucketCreatesInProgress()).isEqualTo(0); assertThat(partitionedRegionStats.getRebalancePrimaryTransfersInProgress()).isEqualTo(0); }); }
Source:
@Override public boolean isNullable() { for (RelDataTypeField field : getFieldList()) { if (!field.getType().isNullable()) { return false; } } return true; }

Target:
@Override public boolean isNullable() { return nullable; }
Source:
ModelResolverDescriptor(IModelResolver resolver, String id, String label, String description) { super(); Preconditions.checkArgument(resolver != null && id != null); final String fLabel; if (label == null) { fLabel = id; } else { fLabel = label; } final String fDescription; if (description == null) { fDescription = ""; } else { fDescription = description; } this.label = fLabel; this.description = fDescription; this.resolver = resolver; this.id = id; }

Target:
ModelResolverDescriptor(IModelResolver resolver, String id, String label, String description) { super(); Preconditions.checkArgument(resolver != null); Preconditions.checkArgument(id != null); final String fLabel; if (label == null) { fLabel = id; } else { fLabel = label; } this.label = fLabel; this.description = Strings.nullToEmpty(description); this.resolver = resolver; this.id = id; }
Source:
public long commit() { long commitAddress; try { txBeginInternal(); operations.forEach(Runnable::run); } finally { commitAddress = endTxn(); } return commitAddress; }

Target:
public void commit() { commit(null); }
Source:
private static CheckpointedInputGate buildGate(TestInvokable target, int numChannels) { SingleInputGate gate = new SingleInputGateBuilder().setNumberOfChannels(numChannels).build(); TestInputChannel[] channels = new TestInputChannel[numChannels]; for (int i = 0; i < numChannels; i++) { channels[i] = new TestInputChannel(gate, i); } gate.setInputChannels(channels); return new CheckpointedInputGate(gate, barrierHandler(gate, target), 0); }

Target:
private static CheckpointedInputGate buildGate(TestInvokable target, int numChannels) { SingleInputGate gate = new SingleInputGateBuilder().setNumberOfChannels(numChannels).build(); TestInputChannel[] channels = new TestInputChannel[numChannels]; for (int i = 0; i < numChannels; i++) { channels[i] = new TestInputChannel(gate, i, false, true); } gate.setInputChannels(channels); return new CheckpointedInputGate(gate, barrierHandler(gate, target), 0); }
Source:
public VersionedCommitCommand() { super(ByteString.emptyString()); }

Target:
public VersionedCommitCommand() { super(null); }
Source:
public Expr apply(final List<Expr> args) { if (args.size() < 2 || args.size() > 3) { throw new IAE("'%s' must have 2 or 3 arguments", name()); } final Expr arg = args.get(0); final Expr patternExpr = args.get(1); final Expr escapeExpr = args.size() > 2 ? args.get(2) : null; if (!patternExpr.isLiteral() || (escapeExpr != null && !escapeExpr.isLiteral())) { throw new IAE("pattern and escape must be literals"); } final String escape = escapeExpr == null ? null : (String) escapeExpr.getLiteralValue(); final Character escapeChar; if (escape != null && escape.length() != 1) { throw new IllegalArgumentException("Escape must be null or a single character"); } else { escapeChar = (escape == null || escape.isEmpty()) ? null : escape.charAt(0); } final LikeDimFilter.LikeMatcher likeMatcher = LikeDimFilter.LikeMatcher.from( (String) patternExpr.getLiteralValue(), escapeChar ); class LikeExtractExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { return ExprEval.of(likeMatcher.matches(arg.eval(bindings).asString()), ExprType.LONG); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new LikeExtractExpr(); }

Target:
public Expr apply(final List<Expr> args) { if (args.size() < 2 || args.size() > 3) { throw new IAE("Function[%s] must have 2 or 3 arguments", name()); } final Expr arg = args.get(0); final Expr patternExpr = args.get(1); final Expr escapeExpr = args.size() > 2 ? args.get(2) : null; if (!patternExpr.isLiteral() || (escapeExpr != null && !escapeExpr.isLiteral())) { throw new IAE("pattern and escape must be literals"); } final String escape = escapeExpr == null ? null : (String) escapeExpr.getLiteralValue(); final Character escapeChar; if (escape != null && escape.length() != 1) { throw new IllegalArgumentException("Escape must be null or a single character"); } else { escapeChar = escape == null ? null : escape.charAt(0); } final LikeDimFilter.LikeMatcher likeMatcher = LikeDimFilter.LikeMatcher.from( (String) patternExpr.getLiteralValue(), escapeChar ); class LikeExtractExpr implements Expr { @Nonnull @Override public ExprEval eval(final ObjectBinding bindings) { return ExprEval.of(likeMatcher.matches(arg.eval(bindings).asString()), ExprType.LONG); } @Override public void visit(final Visitor visitor) { arg.visit(visitor); visitor.visit(this); } } return new LikeExtractExpr(); }
Source:
public Void visitCall(CallExpression call, AtomicBoolean result) { FunctionMetadata function = functionManager.getFunctionMetadata(call.getFunctionHandle()); Optional<OperatorType> operator = function.getOperatorType(); if (operator.isPresent()) { switch (operator.get()) { case CAST: { checkArgument(call.getArguments().size() == 1); Type sourceType = call.getArguments().get(0).getType(); Type targetType = call.getType(); if (!typeManager.isTypeOnlyCoercion(sourceType, targetType)) { result.set(true); } } case SUBSCRIPT: result.set(true); } } else if (!functionReturnsNullForNotNullInput(function)) { result.set(true); } return super.visitCall(call, result); }

Target:
public Void visitCall(CallExpression call, AtomicBoolean result) { FunctionMetadata function = functionManager.getFunctionMetadata(call.getFunctionHandle()); Optional<OperatorType> operator = function.getOperatorType(); if (operator.isPresent()) { switch (operator.get()) { case SATURATED_FLOOR_CAST: case CAST: { checkArgument(call.getArguments().size() == 1); Type sourceType = call.getArguments().get(0).getType(); Type targetType = call.getType(); if (!typeManager.isTypeOnlyCoercion(sourceType, targetType)) { result.set(true); } } case SUBSCRIPT: result.set(true); } } else if (!functionReturnsNullForNotNullInput(function)) { result.set(true); } call.getArguments().forEach(argument -> argument.accept(this, result)); return null; }
Source:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); String description = "Vimal's testCreateFolder"; File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); fileService.deleteFolder(folder.getFileId()); }

Target:
public void testCreateDeleteFolder() throws Exception { FileService fileService = new FileService(); authenticateEndpoint(fileService.getEndpoint(), USERNAME, PASSWORD); String name = "testCreateFolder" + System.currentTimeMillis(); String description = "testCreateFolder"; File folder = fileService.createFolder(name, description, ""); assertEquals(folder.getTitle(), name); fileService.deleteFolder(folder.getFileId()); }
Source:
public void service(HttpRequest request, HttpResponse response) throws IOException { System.out.println("I am an info log to stdout!"); System.err.println("I am an info log to stderr!"); LOGGER.info("I am an info log to Stackdriver!"); LOGGER.warning("I am an info log to Stackdriver!"); BufferedWriter writer = response.getWriter(); writer.write("Messages successfully logged!"); }

Target:
public void service(HttpRequest request, HttpResponse response) throws IOException { System.out.println("I am a log to stdout!"); System.err.println("I am a log to stderr!"); LOGGER.info("I am an info log!"); LOGGER.warning("I am a warning log!"); BufferedWriter writer = response.getWriter(); writer.write("Messages successfully logged!"); }
Source:
public FilterExpression parseGlobalExpression(String path, MultivaluedMap<String, String> filterParams) throws ParseException { List<FilterPredicate> filterPredicates; filterPredicates = extractPredicates(filterParams); String normalizedPath = JsonApiParser.normalizePath(path); String[] pathComponents = normalizedPath.split("/"); String firstPathComponent = ""; if (pathComponents.length > 0) { firstPathComponent = pathComponents[0]; } FilterExpression joinedExpression = null; for (FilterPredicate filterPredicate : filterPredicates) { Class firstClass = filterPredicate.getPath().getPathElements().get(0).getType(); if (!dictionary.getJsonAliasFor(firstClass).equals(firstPathComponent)) { throw new ParseException(String.format("Invalid predicate: %s", filterPredicate)); } if ((filterPredicate.getOperator().equals(Operator.HASMEMBER) || filterPredicate.getOperator().equals(Operator.HASNOMEMBER)) && !FilterPredicate.checkLastPathElementType(dictionary, filterPredicate.getPath(), Collection.class)) { throw new ParseException("Invalid Path: Last Path Element has to be a collection type"); } if (joinedExpression == null) { joinedExpression = filterPredicate; } else { joinedExpression = new AndFilterExpression(joinedExpression, filterPredicate); } } return joinedExpression; }

Target:
public FilterExpression parseGlobalExpression(String path, MultivaluedMap<String, String> filterParams) throws ParseException { List<FilterPredicate> filterPredicates; filterPredicates = extractPredicates(filterParams); String normalizedPath = JsonApiParser.normalizePath(path); String[] pathComponents = normalizedPath.split("/"); String firstPathComponent = ""; if (pathComponents.length > 0) { firstPathComponent = pathComponents[0]; } FilterExpression joinedExpression = null; for (FilterPredicate filterPredicate : filterPredicates) { Class firstClass = filterPredicate.getPath().getPathElements().get(0).getType(); if (!dictionary.getJsonAliasFor(firstClass).equals(firstPathComponent)) { throw new ParseException(String.format("Invalid predicate: %s", filterPredicate)); } if ((filterPredicate.getOperator().equals(Operator.HASMEMBER) || filterPredicate.getOperator().equals(Operator.HASNOMEMBER)) && !FilterPredicate.isLastPathElementAssignableFrom( dictionary, filterPredicate.getPath(), Collection.class)) { throw new ParseException("Invalid Path: Last Path Element has to be a collection type"); } if (joinedExpression == null) { joinedExpression = filterPredicate; } else { joinedExpression = new AndFilterExpression(joinedExpression, filterPredicate); } } return joinedExpression; }
Source:
public static void deleteNonLocalClientsAndTabs(Context context) { final String LOG_TAG = "FennecTabsRepository"; final String nonLocalTabsSelection = BrowserContract.Tabs.CLIENT_GUID + " IS NOT NULL"; ContentProviderClient tabsProvider = context.getContentResolver() .acquireContentProviderClient(BrowserContractHelpers.TABS_CONTENT_URI); if (tabsProvider == null) { Logger.warn(LOG_TAG, "Unable to create tabsProvider!"); return; } try { Logger.info(LOG_TAG, "Clearing all non-local tabs."); tabsProvider.delete(BrowserContractHelpers.TABS_CONTENT_URI, nonLocalTabsSelection, null); } catch (RemoteException e) { Logger.warn(LOG_TAG, "Error while deleting", e); return; } finally { try { tabsProvider.release(); } catch (Exception e) { Logger.warn(LOG_TAG, "Got exception releasing tabsProvider!", e); } } }

Target:
public static void deleteNonLocalClientsAndTabs(Context context) { final String nonLocalTabsSelection = BrowserContract.Tabs.CLIENT_GUID + " IS NOT NULL"; ContentProviderClient tabsProvider = context.getContentResolver() .acquireContentProviderClient(BrowserContractHelpers.TABS_CONTENT_URI); if (tabsProvider == null) { Logger.warn(LOG_TAG, "Unable to create tabsProvider!"); return; } try { Logger.info(LOG_TAG, "Clearing all non-local tabs for default profile."); tabsProvider.delete(BrowserContractHelpers.TABS_CONTENT_URI, nonLocalTabsSelection, null); } catch (RemoteException e) { Logger.warn(LOG_TAG, "Error while deleting", e); } finally { try { tabsProvider.release(); } catch (Exception e) { Logger.warn(LOG_TAG, "Got exception releasing tabsProvider!", e); } } }
Source:
public static Collection<MdbValidityStatus> assertMDBClassValidity(final ClassInfo mdbClass) throws DeploymentUnitProcessingException { Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length); final String className = mdbClass.name().toString(); verifyModifiers(className, mdbClass.flags(), mdbComplianceIssueList); for (MethodInfo method : mdbClass.methods()) { final String methodName = method.name(); if ("onMessage".equals(methodName)) { verifyOnMessageMethod(className, methodName, method.flags(), mdbComplianceIssueList); } if ("finalize".equals(method.name())) { EjbLogger.DEPLOYMENT_LOGGER.mdbCantHaveFinalizeMethod(className); mdbComplianceIssueList.add(MdbValidityStatus.MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD); } } return mdbComplianceIssueList; }

Target:
public static Collection<MdbValidityStatus> assertMDBClassValidity(final ClassInfo mdbClass) throws DeploymentUnitProcessingException { Collection<MdbValidityStatus> mdbComplianceIssueList = new ArrayList<>(MdbValidityStatus.values().length); final String className = mdbClass.name().toString(); verifyModifiers(className, mdbClass.flags(), mdbComplianceIssueList); for (MethodInfo method : mdbClass.methods()) { if ("onMessage".equals(method.name())) { verifyOnMessageMethod(className, method.flags(), mdbComplianceIssueList); } if ("finalize".equals(method.name())) { EjbLogger.DEPLOYMENT_LOGGER.mdbCantHaveFinalizeMethod(className); mdbComplianceIssueList.add(MdbValidityStatus.MDB_SHOULD_NOT_HAVE_FINALIZE_METHOD); } } return mdbComplianceIssueList; }
Source:
public String get() { if (Strings.isNullOrEmpty(javaOpts)) { return ""; } return DockerInstanceRuntimeInfo.JAVA_OPTS_VARIABLE + "=" + javaOpts; }

Target:
public String get() { return DockerInstanceRuntimeInfo.JAVA_OPTS_VARIABLE + '=' + javaOpts; }
Source:
protected void doMergeDiffWithConflicts(boolean leftToRight, Registry mergerRegistry, List<Diff> affectedDiffs, Monitor emfMonitor, Diff diff) { if (diff.getState() != MERGED) { affectedDiffs.add(diff); final IMerger merger = mergerRegistry.getHighestRankingMerger(diff); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "mergeWithConflicts(Collection<Diff>, boolean, Registry) - Selected merger for diff " + diff.hashCode() + ": " + merger.getClass().getSimpleName()); } if (getMergeMode() == LEFT_TO_RIGHT) { merger.copyLeftToRight(diff, emfMonitor); } else if (getMergeMode() == RIGHT_TO_LEFT) { merger.copyRightToLeft(diff, emfMonitor); } else if (getMergeMode() == ACCEPT || getMergeMode() == REJECT) { MergeOperation mergeAction = getMergeOperation(diff); if (mergeAction == MARK_AS_MERGE) { markAsMerged(diff, getMergeMode(), leftToRight, mergerRegistry); } else { if (isLeftEditable() && !leftToRight) { merger.copyRightToLeft(diff, emfMonitor); } else if (isRightEditable() && leftToRight) { merger.copyLeftToRight(diff, emfMonitor); } } } else { throw new IllegalStateException(); } } }

Target:
protected void doMergeDiffWithConflicts(boolean leftToRight, Registry mergerRegistry, List<Diff> affectedDiffs, Monitor emfMonitor, Diff diff) { if (isInTerminalState(diff)) { affectedDiffs.add(diff); final IMerger merger = mergerRegistry.getHighestRankingMerger(diff); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "mergeWithConflicts(Collection<Diff>, boolean, Registry) - Selected merger for diff " + diff.hashCode() + ": " + merger.getClass().getSimpleName()); } if (getMergeMode() == LEFT_TO_RIGHT) { merger.copyLeftToRight(diff, emfMonitor); } else if (getMergeMode() == RIGHT_TO_LEFT) { merger.copyRightToLeft(diff, emfMonitor); } else if (getMergeMode() == ACCEPT || getMergeMode() == REJECT) { MergeOperation mergeAction = getMergeOperation(diff); if (mergeAction == MARK_AS_MERGE) { markAsMerged(diff, getMergeMode(), leftToRight, mergerRegistry); } else { if (isLeftEditable() && !leftToRight) { merger.copyRightToLeft(diff, emfMonitor); } else if (isRightEditable() && leftToRight) { merger.copyLeftToRight(diff, emfMonitor); } } } else { throw new IllegalStateException(); } } }
Source:
private void connect() throws ConnectionException { if( clusterUri != null){ clusterConnection = LeasedConnectionFactory.connect(clusterUri, connectionProperties); } else { clusterConnection = LeasedConnectionFactory.connect(servers, connectionProperties); } entityFactory = new ClusterTierManagerClientEntityFactory(clusterConnection, timeouts); }

Target:
private void connect() throws ConnectionException { clusterConnection = connectionSource.connect(connectionProperties); entityFactory = new ClusterTierManagerClientEntityFactory(clusterConnection, timeouts); }
Source:
public void start() throws Exception { if (trace) { log.tracef("Starting StateTransferManager of cache %s on node %s", cacheName, rpcManager.getAddress()); } Hash hashFunction = configuration.clustering().hash().hash(); componentRegistry.registerComponent(hashFunction, Hash.class); CacheJoinInfo joinInfo = new CacheJoinInfo( pickConsistentHashFactory(), hashFunction, configuration.clustering().hash().numSegments(), configuration.clustering().hash().numOwners(), configuration.clustering().stateTransfer().timeout(), configuration.transaction().transactionProtocol().isTotalOrder(), configuration.clustering().cacheMode().isDistributed(), configuration.clustering().hash().capacityFactor()); CacheTopology initialTopology = localTopologyManager.join(cacheName, joinInfo, new CacheTopologyHandler() { @Override public void updateConsistentHash(CacheTopology cacheTopology) { doTopologyUpdate(cacheTopology, false); } @Override public void rebalance(CacheTopology cacheTopology) { doTopologyUpdate(cacheTopology, true); } }, partitionHandlingManager); if (trace) { log.tracef("StateTransferManager of cache %s on node %s received initial topology %s", cacheName, rpcManager.getAddress(), initialTopology); } }

Target:
public void start() throws Exception { if (trace) { log.tracef("Starting StateTransferManager of cache %s on node %s", cacheName, rpcManager.getAddress()); } CacheJoinInfo joinInfo = new CacheJoinInfo( pickConsistentHashFactory(), hash, configuration.clustering().hash().numSegments(), configuration.clustering().hash().numOwners(), configuration.clustering().stateTransfer().timeout(), configuration.transaction().transactionProtocol().isTotalOrder(), configuration.clustering().cacheMode().isDistributed(), configuration.clustering().hash().capacityFactor()); CacheTopology initialTopology = localTopologyManager.join(cacheName, joinInfo, new CacheTopologyHandler() { @Override public void updateConsistentHash(CacheTopology cacheTopology) { doTopologyUpdate(cacheTopology, false); } @Override public void rebalance(CacheTopology cacheTopology) { doTopologyUpdate(cacheTopology, true); } }, partitionHandlingManager); if (trace) { log.tracef("StateTransferManager of cache %s on node %s received initial topology %s", cacheName, rpcManager.getAddress(), initialTopology); } }
Source:
private void validateAuditLogDir() { List<String> nodesWithNoAuditLogDirs = cluster.getStripes() .stream() .flatMap(s -> s.getNodes().stream()) .filter(node -> !node.getSecurityAuditLogDir().asOptional().isPresent()) .map(Node::getName) .collect(toList()); if (nodesWithNoAuditLogDirs.size() != 0 && nodesWithNoAuditLogDirs.size() != cluster.getNodeCount()) { throw new MalformedClusterException("Nodes with names: " + nodesWithNoAuditLogDirs + " don't have audit log directories " + "defined, but other nodes in the cluster do. Audit log directories, if configured, need to be defined on all nodes in the cluster"); } }

Target:
private void validateAuditLogDir() { List<String> nodesWithNoAuditLogDirs = cluster.getStripes() .stream() .flatMap(s -> s.getNodes().stream()) .filter(node -> !node.getSecurityAuditLogDir().isConfigured()) .map(Node::getName) .collect(toList()); if (nodesWithNoAuditLogDirs.size() != 0 && nodesWithNoAuditLogDirs.size() != cluster.getNodeCount()) { throw new MalformedClusterException("Nodes with names: " + nodesWithNoAuditLogDirs + " don't have audit log directories " + "defined, but other nodes in the cluster do. Audit log directories, if configured, need to be defined on all nodes in the cluster"); } }
Source:
public List<CertificateDTO> getCertificateInfo() { List<CertificateDTO> certs = new ArrayList<CertificateDTO>(); List<CertificateDTO> expiredCerts = new ArrayList<CertificateDTO>(); List<CertificateDTO> warnningCerts = new ArrayList<CertificateDTO>(); try { certs.addAll(certificateService.fetchKeyStores()); certs.addAll(certificateService.fetchTrustStores()); for (CertificateDTO dto : certs) { if (dto.getExpiresInDays() <= 30) { dto.setExpiryColorCoding(COLOR_CODING_CSS.RED.toString()); expiredCerts.add(dto); } else if (dto.getExpiresInDays() > 30 && dto.getExpiresInDays() <= 90) { dto.setExpiryColorCoding(COLOR_CODING_CSS.YELLOW.toString()); warnningCerts.add(dto); } } certDTOs.addAll(expiredCerts); certDTOs.addAll(warnningCerts); } catch (CertificateManagerException e) { LOG.error("Unable to get certificate details {}", e.getLocalizedMessage(), e); HelperUtil.addMessageError(KEY_STORE_MSG, "Unable to fetch certificate details"); } return certDTOs; }

Target:
public List<CertificateDTO> getCertificateInfo() { try { certificateList = new ArrayList<>(); addCertificates(certificateService.fetchKeyStores(), certificateList); addCertificates(certificateService.fetchTrustStores(), certificateList); Collections.sort(certificateList, new Comparator<CertificateDTO>() { @Override public int compare(CertificateDTO o1, CertificateDTO o2) { return (int) o1.getExpiresInDays() - (int) o2.getExpiresInDays(); } }); return certificateList; } catch (CertificateManagerException e) { LOG.error("Unable to get certificate details {}", e.getLocalizedMessage(), e); HelperUtil.addMessageError(GET_CERT_STORE_MSG, "Unable to fetch certificate details"); } return new ArrayList<>(); }
Source:
private <T extends Message, F extends MessageField> Map<String, Map<String, String>> doList(Class<T> entityType, List<String> entityNames) { if (entityNames.size() == 0) return doListAll(entityType); final Map<String,Map<String,String>> result = new LinkedHashMap<String, Map<String, String>>(); for(String entityName : entityNames) { T config = null; Exception thrown = null; try { config = (T) getDaoByObjectType(entityType).get(entityName).getOrElse(null); } catch (Exception e) { thrown = e; } final String errMgs = thrown != null ? thrown.getMessage() : config == null ? CONFIG_NOT_FOUND : null; result.put(entityName, errMgs != null ? new HashMap<String, String>() {{ put(ERR_MSG_FIELD, errMgs); }} : JavaConversions.mapAsJavaMap(config)); } return result; }

Target:
private <T extends Message> Map<String, Map<String, String>> doList(Class<T> entityType, List<String> entityNames) { if (entityNames.size() == 0) return doListAll(entityType); final Map<String,Map<String,String>> result = new LinkedHashMap<String, Map<String, String>>(); for(String entityName : entityNames) { T config = null; Exception thrown = null; try { config = (T) getDaoByObjectType(entityType).get(entityName).getOrElse(null); } catch (Exception e) { thrown = e; } final String errMgs = thrown != null ? thrown.getMessage() : config == null ? CONFIG_NOT_FOUND : null; result.put(entityName, errMgs != null ? new HashMap<String, String>() {{ put(ERR_MSG_FIELD, errMgs); }} : JavaConversions.mapAsJavaMap(config)); } return result; }
Source:
private boolean branchExists(String branchName) throws GerritException { BranchInfo[] branches = reviewHarness.getAdminClient().getRemoteProjectBranches("org.eclipse.mylyn.test", new NullProgressMonitor()); for (BranchInfo branch : branches) { if (branch.getRef().endsWith(branchName)) { return true; } } return false; }

Target:
private boolean branchExists(String branchName) throws GerritException { BranchInfo[] branches = reviewHarness.getAdminClient().getRemoteProjectBranches("org.eclipse.mylyn.test", new NullProgressMonitor()); for (BranchInfo branch : branches) { String branchRef = StringUtils.trimToEmpty(StringUtils.substringAfterLast(branch.getRef(), "/")); if (branchRef.equals(branchName)) { return true; } } return false; }
Source:
public synchronized void dispose() { if (getIndexer() != null) { getIndexer().dispose(); } @NonNull Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); }

Target:
public synchronized void dispose() { if (getIndexer() != null) { getIndexer().dispose(); } Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); }
Source:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.filterDisksBasedOnCinder(getDiskDao().getAllForVm(vm.getId()))); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.filterDisksBasedOnCinder(getDiskDao().getAllForVm(vm.getId()), true)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().ExportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }
Source:
public TreeHash(HashCode treeHash, HashCode linearHash) { this.treeHash = treeHash; this.linearHash = linearHash; }

Target:
private TreeHash(HashCode treeHash, HashCode linearHash) { this.treeHash = checkNotNull(treeHash, "treeHash"); this.linearHash = checkNotNull(linearHash, "linearHash"); }
Source:
default String[] entityTokensGetNames( EntityType type, int[] entityTokenIds ) { IntFunction<String> mapper; if ( type == EntityType.NODE ) { mapper = this::labelGetName; } else if ( type == EntityType.RELATIONSHIP ) { mapper = this::relationshipTypeGetName; } else { return new String[0]; } String[] tokenNames = new String[entityTokenIds.length]; for ( int i = 0; i < entityTokenIds.length; i++ ) { tokenNames[i] = mapper.apply( entityTokenIds[i] ); } return tokenNames; }

Target:
default String[] entityTokensGetNames( EntityType type, int[] entityTokenIds ) { IntFunction<String> mapper; switch ( type ) { case NODE: mapper = this::labelGetName; break; case RELATIONSHIP: mapper = this::relationshipTypeGetName; break; default: throw new IllegalArgumentException( "Cannot lookup names for tokens of type: " + type ); } String[] tokenNames = new String[entityTokenIds.length]; for ( int i = 0; i < entityTokenIds.length; i++ ) { tokenNames[i] = mapper.apply( entityTokenIds[i] ); } return tokenNames; }
Source:
public ClusterEventService getEventService() { return eventingService; }

Target:
public ClusterEventService getEventService() { return eventService; }
Source:
public void init() { if (mDbHelper == null || mDbHelper.getAppId() != ProviderUtils.getSeatedOrInstallingAppId()) { String dbName = ProviderUtils.getProviderDbName( ProviderUtils.ProviderType.FORMS, ProviderUtils.getSeatedOrInstallingAppId()); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName); } }

Target:
public void init() { String appId = ProviderUtils.getSandboxedAppId(); if (mDbHelper == null || mDbHelper.getAppId() != appId) { String dbName = ProviderUtils.getProviderDbName(ProviderUtils.ProviderType.FORMS, appId); mDbHelper = new DatabaseHelper(CommCareApplication._(), dbName, appId); } }
Source:
private void toggleNature(final IProject project) { try { PlatformUI.getWorkbench().getProgressService().run(true, false, new WorkspaceModifyOperation(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())) { @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { try { if (ModelingProject.hasModelingProjectNature(project)) { ModelingProjectManager.INSTANCE.removeModelingNature(project, monitor); } else { ModelingProjectManager.INSTANCE.convertToModelingProject(project, monitor); } } catch (CoreException e) { UICallBack uiCallback = SiriusEditPlugin.getPlugin().getUiCallback(); if (uiCallback != null) { uiCallback.openError(Messages.ModelingToggleNatureAction_errorDialogTitle, MessageFormat.format(Messages.ModelingToggleNatureAction_errorDialogMessage, e.getMessage())); } } } }); } catch (final InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e); } catch (final InterruptedException e) { throw new RuntimeException(e); } }

Target:
private void toggleNature(final IProject project) { try { PlatformUI.getWorkbench().getProgressService().run(true, false, new WorkspaceModifyOperation(ResourcesPlugin.getWorkspace().getRoot()) { @Override protected void execute(IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { try { if (ModelingProject.hasModelingProjectNature(project)) { ModelingProjectManager.INSTANCE.removeModelingNature(project, monitor); } else { ModelingProjectManager.INSTANCE.convertToModelingProject(project, monitor); } } catch (CoreException e) { UICallBack uiCallback = SiriusEditPlugin.getPlugin().getUiCallback(); if (uiCallback != null) { uiCallback.openError(Messages.ModelingToggleNatureAction_errorDialogTitle, MessageFormat.format(Messages.ModelingToggleNatureAction_errorDialogMessage, e.getMessage())); } } } }); } catch (final InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } throw new RuntimeException(e); } catch (final InterruptedException e) { throw new RuntimeException(e); } }
Source:
public static void assumeGoVersionAtLeast(String minimumVersion) { List<Integer> minimumVersionNumbers = getVersionNumbers(minimumVersion); Assume.assumeTrue( "Expect minimum version string in the form of x.y.z, got" + minimumVersion, minimumVersionNumbers.size() == 3); Throwable exception = null; String actualVersion = "0.0.0"; ProcessExecutor processExecutor = new DefaultProcessExecutor(new TestConsole()); try { ProcessExecutor.Result goToolResult = processExecutor.launchAndExecute( ProcessExecutorParams.builder().addCommand("go", "version").build(), EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_OUT), Optional.empty(), Optional.empty(), Optional.empty()); if (goToolResult.getExitCode() == 0) { actualVersion = goToolResult.getStdout().get().substring(13, 18); } else { exception = new HumanReadableException(goToolResult.getStderr().get()); } } catch (Exception e) { exception = e; } assumeNoException(exception); List<Integer> actualVersionNumbers = getVersionNumbers(actualVersion); Assume.assumeTrue( "Expect actual version string in the form of x.y.z, got" + actualVersion, actualVersionNumbers.size() == 3); boolean versionSatisfied = true; for (int i = 0; i < 3; i++) { if (actualVersionNumbers.get(i) < minimumVersionNumbers.get(i)) { versionSatisfied = false; break; } else if (actualVersionNumbers.get(i) > minimumVersionNumbers.get(i)) { versionSatisfied = true; break; } } Assume.assumeTrue("Actual Go version is lower than the required version", versionSatisfied); }

Target:
public static void assumeGoVersionAtLeast(String minimumVersion) { List<Integer> minimumVersionNumbers = Arrays.stream(minimumVersion.split("\\.")) .map(Integer::valueOf) .collect(Collectors.toList()); Assume.assumeTrue( "Expect minimum version string in the form of x.y.z, got: " + minimumVersion, minimumVersionNumbers.size() == 3); Throwable exception = null; List<Integer> actualVersionNumbers = null; ProcessExecutor processExecutor = new DefaultProcessExecutor(new TestConsole()); try { ProcessExecutor.Result goToolResult = processExecutor.launchAndExecute( ProcessExecutorParams.builder().addCommand("go", "version").build(), EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_OUT), Optional.empty(), Optional.empty(), Optional.empty()); if (goToolResult.getExitCode() == 0) { String versionOut = goToolResult.getStdout().get().trim(); Matcher matcher = VERSION_PATTERN.matcher(versionOut); if (matcher.matches()) { actualVersionNumbers = IntStream.range(1, 4) .mapToObj(matcher::group) .map(Integer::valueOf) .collect(Collectors.toList()); } else { exception = new HumanReadableException("Unknown version: " + versionOut); } } else { exception = new HumanReadableException(goToolResult.getStderr().get()); } } catch (Exception e) { exception = e; } assumeNoException(exception); boolean versionSatisfied = true; for (int i = 0; i < 3; i++) { if (actualVersionNumbers.get(i) < minimumVersionNumbers.get(i)) { versionSatisfied = false; break; } else if (actualVersionNumbers.get(i) > minimumVersionNumbers.get(i)) { versionSatisfied = true; break; } } Assume.assumeTrue("Actual Go version is lower than the required version", versionSatisfied); }
Source:
public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> ci) { if (!this.isCubicWorld()) return; ICube cube = this.getCubeCache().getLoadedCube(Coords.blockToCube(pos.getX()),Coords.blockToCube(pos.getY()),Coords.blockToCube(pos.getZ())); if (cube == null) return; Biome biome = cube.getBiome(pos, provider.getBiomeProvider()); ci.setReturnValue(biome); ci.cancel(); }

Target:
public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> ci) { if (!this.isCubicWorld()) return; ICube cube = this.getCubeCache().getLoadedCube(Coords.blockToCube(pos.getX()),Coords.blockToCube(pos.getY()),Coords.blockToCube(pos.getZ())); if (cube == null) return; Biome biome = cube.getBiome(pos); ci.setReturnValue(biome); ci.cancel(); }
Source:
public <T> T readValue(@Nonnull final IMAPResponse[] content, @Nonnull final Class<T> valueType, @Nonnull final FetchItem[] extensionItems) throws ImapAsyncClientException { if (valueType == StoreResult.class) { return (T) parser.parseToStoreResult(content, extensionItems); } if (valueType == FetchResult.class) { return (T) parser.parseToFetchResult(content, extensionItems); } throw new ImapAsyncClientException(FailureType.UNKNOWN_PARSE_RESULT_TYPE); }

Target:
public <T> T readValue(@Nonnull final IMAPResponse[] content, @Nonnull final Class<T> valueType, @Nonnull final FetchItem[] extensionItems) throws ImapAsyncClientException { if (valueType == FetchResult.class) { return (T) parser.parseToFetchResult(content, extensionItems); } throw new ImapAsyncClientException(FailureType.UNKNOWN_PARSE_RESULT_TYPE); }
Source:
public void testCreatingNewVariable() { final String variableName = "testVariable"; final int intToChange = 28; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(setBrickPosition, R.string.brick_ask_label); checkIfBrickAtPositionShowsString(setBrickPosition, R.string.brick_ask_store); onView(withId(R.id.brick_ask_spinner)).perform(click()); onView(withId(R.id.dialog_formula_editor_data_name_edit_text)).perform(typeText(variableName)); onView(withText(R.string.ok)).perform(click()); }

Target:
public void testCreatingNewVariable() { final String firstVariableName = "firstVariable"; final String secondVariableName = "secondVariable"; checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_ask_label); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_ask_store); createNewVariableOnSpinnerInitial(R.id.brick_ask_spinner, brickPosition, firstVariableName); createNewVariableOnSpinner(R.id.brick_ask_spinner, brickPosition, secondVariableName); }
Source:
private Guid mockSourceImage() { Guid imageId = Guid.NewGuid(); DiskImage image = new DiskImage(); image.setImageId(imageId); ArrayList<Guid> list = new ArrayList<Guid>(); list.add(STORAGE_DOMAIN_ID); image.setstorage_ids(list); image.setActualSize(4); image.setsize(40); doReturn(Collections.singletonList(image)).when(cmd).getSourceImages(); return imageId; }

Target:
private Guid mockSourceImage() { Guid imageId = Guid.NewGuid(); DiskImage image = new DiskImage(); image.setImageId(imageId); ArrayList<Guid> list = new ArrayList<Guid>(); list.add(STORAGE_DOMAIN_ID); image.setstorage_ids(list); image.setActualSize(IMAGE_ACTUAL_SIZE_GB); image.setsize(40); doReturn(Collections.singletonList(image)).when(cmd).getSourceImages(); return imageId; }
Source:
private void validateAgentBody(Body body) throws ParamValidationException, PropertyValidationException { if (!(body instanceof EdmAgentBody)) { throw new ParamValidationException(I18nConstants.INVALID_PROPERTY_VALUE, I18nConstants.INVALID_PROPERTY_VALUE, new String[] { "tag.body.type", ResourceTypes.AGENT.getJsonValue() }); } validateAgentEntityBody(body); }

Target:
private void validateAgentBody(Body body) throws ParamValidationException, PropertyValidationException { if (body.getType() == null || !(body.getType().size() == 1)) { } else if (!ResourceTypes.AGENT.hasJsonValue(body.getType().get(0))) { throw new PropertyValidationException(I18nConstants.INVALID_PROPERTY_VALUE, I18nConstants.INVALID_PROPERTY_VALUE, new String[] { "agent.body.type" }); } validateAgentEntityBody(body); }
Source:
private String compose(String str, Map<String, Pair<String, String>> stringParts, int maxNumericSuffixLength) { if (str != null && stringParts.containsKey(str)) { final Pair<String, String> stringPartsPair = stringParts.get(str); return lpadSuffixWithZeroes(stringPartsPair.getFirst(), stringPartsPair.getSecond(), maxNumericSuffixLength); } else { return str; } }

Target:
private String compose(String str, Map<String, Pair<String, String>> stringParts, int maxNumericSuffixLength) { final Pair<String, String> stringPartsPair = str == null ? null : stringParts.get(str); if (stringPartsPair == null) { return str; } else { return lpadSuffixWithZeroes(stringPartsPair.getFirst(), stringPartsPair.getSecond(), maxNumericSuffixLength); } }
Source:
public ISYActiveBindingConfig(Map<Object, Object> config) { this.logger.info( "OpenHab Binding Configuration(refresh='{}',upnp='{}',uuid='{}',ip='{}',port='{}',user='{}',password='{}')", config.get("refresh"), config.get("upnp"), config.get("uuid"), config.get("ip"), config.get("port"), config.get("user"), "xxxxxx"); if (isNotBlank((String) config.get("refresh"))) { refreshInterval = Long.parseLong((String) config.get("refresh")); } if (isNotBlank((String) config.get("user")) && isNotBlank((String) config.get("password"))) { this.user = (String) config.get("user"); this.password = (String) config.get("password"); } else { this.logger.warn("No user/password specified"); } if (isNotBlank((String) config.get("upnp"))) { useUpnp = Boolean.parseBoolean((String) config.get("upnp")); } if (!useUpnp && isNotBlank((String) config.get("uuid")) && isNotBlank((String) config.get("ip")) && isNotBlank((String) config.get("port"))) { this.uuid = (String) config.get("uuid"); this.ipAddress = (String) config.get("ip"); try { this.port = Integer.parseInt((String) config.get("port")); } catch (NumberFormatException ne) { this.logger.error("Not a valid port number"); throw new RuntimeException("Not a valid port number", ne); } if (this.port < 0 || this.port > 65535) { this.logger.error("Port out of range (0-65535)"); throw new NumberFormatException("Invalid port"); } } else { this.logger.info("Using UPNP for ISY connection."); } }

Target:
public ISYActiveBindingConfig(Map<Object, Object> config) { this.logger.info( "OpenHab Binding Configuration(refresh='{}',upnp='{}',uuid='{}',ip='{}',port='{}',user='{}',password='{}')", config.get("refresh"), config.get("upnp"), config.get("uuid"), config.get("ip"), config.get("port"), config.get("user"), "xxxxxx"); if (isNotBlank((String) config.get("refresh"))) { refreshInterval = Long.parseLong((String) config.get("refresh")); } if (isNotBlank((String) config.get("user")) && isNotBlank((String) config.get("password"))) { this.user = (String) config.get("user"); this.password = (String) config.get("password"); } else { this.logger.warn("No user/password specified"); } if (isNotBlank((String) config.get("upnp"))) { useUpnp = Boolean.parseBoolean((String) config.get("upnp")); } if (!useUpnp && isNotBlank((String) config.get("uuid")) && isNotBlank((String) config.get("ip")) && isNotBlank((String) config.get("port"))) { this.uuid = (String) config.get("uuid"); this.ipAddress = (String) config.get("ip"); try { this.port = Integer.parseInt((String) config.get("port")); } catch (NumberFormatException ne) { this.logger.warn("Not a valid port number"); throw new RuntimeException("Not a valid port number", ne); } if (this.port < 0 || this.port > 65535) { this.logger.warn("Port out of range (0-65535)"); throw new NumberFormatException("Invalid port"); } } else { this.logger.info("Using UPNP for ISY connection."); } }
Source:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, new TychoContextFinder(contextFinder.getParent()), surefireClassLoader); }

Target:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, surefireClassLoader, new TychoContextFinder(contextFinder.getParent())); }