auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new JettyHttpClientModule("druid.router.http", Router.class), new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/router"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8888); JsonConfigProvider.bind(binder, "druid.router", TieredBrokerConfig.class); binder.bind(CoordinatorRuleManager.class); LifecycleModule.register(binder, CoordinatorRuleManager.class); binder.bind(TieredBrokerHostSelector.class).in(ManageLifecycle.class); binder.bind(QueryHostFinder.class).in(LazySingleton.class); binder.bind(new TypeLiteral<List<TieredBrokerSelectorStrategy>>(){}) .toProvider(TieredBrokerSelectorStrategiesProvider.class) .in(LazySingleton.class); binder.bind(JettyServerInitializer.class).to(RouterJettyServerInitializer.class).in(LazySingleton.class); LifecycleModule.register(binder, Server.class); DiscoveryModule.register(binder, Self.class); binder.install(new LookupModule()); } @Provides @ManageLifecycle public ServerDiscoverySelector getCoordinatorServerDiscoverySelector( TieredBrokerConfig config, ServerDiscoveryFactory factory ) { return factory.createSelector(config.getCoordinatorServiceName()); } } ); }

Target:
protected List<? extends Module> getModules() { return ImmutableList.<Module>of( new JettyHttpClientModule("druid.router.http", Router.class), new Module() { @Override public void configure(Binder binder) { binder.bindConstant().annotatedWith(Names.named("serviceName")).to("druid/router"); binder.bindConstant().annotatedWith(Names.named("servicePort")).to(8888); JsonConfigProvider.bind(binder, "druid.router", TieredBrokerConfig.class); binder.bind(CoordinatorRuleManager.class); LifecycleModule.register(binder, CoordinatorRuleManager.class); binder.bind(TieredBrokerHostSelector.class).in(ManageLifecycle.class); binder.bind(QueryHostFinder.class).in(LazySingleton.class); binder.bind(new TypeLiteral<List<TieredBrokerSelectorStrategy>>() { }) .toProvider(TieredBrokerSelectorStrategiesProvider.class) .in(LazySingleton.class); binder.bind(JettyServerInitializer.class).to(RouterJettyServerInitializer.class).in(LazySingleton.class); LifecycleModule.register(binder, Server.class); DiscoveryModule.register(binder, Self.class); } @Provides @ManageLifecycle public ServerDiscoverySelector getCoordinatorServerDiscoverySelector( TieredBrokerConfig config, ServerDiscoveryFactory factory ) { return factory.createSelector(config.getCoordinatorServiceName()); } }, new LookupModule() ); }
Source:
public void verifyKeyValues(String slotName, String adapter, String size, String price) { WebElement slotContainer = driver.findElement( By.cssSelector(AdsContent.getSlotSelector(slotName)) ); WebElement gptNode = slotContainer.findElement(By.cssSelector(GPT_NODE)); try { JSONObject keyValues = new JSONObject(gptNode.getAttribute("data-gpt-slot-params")); assertKeyValue(keyValues, "hb_bidder", adapter, "Bidder passed in slot key-values"); assertKeyValue(keyValues, "hb_size", size, "Size passed in slot key-values"); assertKeyValue(keyValues, "hb_pb", price, "Price passed in slot key-values"); } catch (JSONException exception) { PageObjectLogging.log("Prebid.js key-values", exception, false); } }

Target:
public void verifyKeyValues(String slotName, String adapter, String size, String price) { WebElement slotContainer = driver.findElement( By.cssSelector(AdsContent.getSlotSelector(slotName)) ); WebElement gptNode = slotContainer.findElement(By.cssSelector(GPT_NODE)); try { JSONObject keyValues = new JSONObject(gptNode.getAttribute("data-gpt-slot-params")); assertKeyValue(keyValues, "hb_bidder", adapter, "Bidder passed in slot key-values"); assertKeyValue(keyValues, "hb_size", size, "Size passed in slot key-values"); assertKeyValue(keyValues, "hb_pb", price, "Price passed in slot key-values"); } catch (JSONException exception) { PageObjectLogging .log("Prebid.js key-values", "Prebid.js key-values not found in slot div", false); PageObjectLogging.log("Prebid.js key-values", exception, false); } }
Source:
public void fillPushAttribute(long t, Object value, int attributeQuark) throws TimeRangeException, StateValueTypeException { int stackDepth; int subAttributeQuark; Object previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV == null) { stackDepth = 0; } else if (previousSV instanceof Integer) { stackDepth = (int) previousSV; } else { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getClass() + ", Expected:" + Type.INTEGER); } if (stackDepth >= MAX_STACK_DEPTH) { String message = " Stack limit reached, not pushing"; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } int freeSpaceDepth = stackDepth + 1; for (int i = 1; i <= stackDepth; i++) { try { ITmfStateValue stateValue = queryOngoingState(getQuarkRelative(attributeQuark, String.valueOf(i))); if (stateValue.isNull()) { freeSpaceDepth = i; break; } } catch (AttributeNotFoundException e) { } } stackDepth++; subAttributeQuark = getQuarkRelativeAndAdd(attributeQuark, String.valueOf(freeSpaceDepth)); modifyAttribute(t, stackDepth, attributeQuark); modifyAttribute(t, value, subAttributeQuark); }

Target:
public void fillPushAttribute(long t, Object value, int attributeQuark) throws TimeRangeException, StateValueTypeException { int stackDepth; int subAttributeQuark; Object previousSV = transState.getOngoingStateValue(attributeQuark); if (previousSV == null) { stackDepth = 0; } else if (previousSV instanceof Integer) { stackDepth = (int) previousSV; } else { throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark + ", Type:" + previousSV.getClass() + ", Expected:" + Type.INTEGER); } if (stackDepth >= MAX_STACK_DEPTH) { String message = " Stack limit reached, not pushing"; throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark + message); } int emptySpaceDepth = stackDepth + 1; for (int i = 1; i <= stackDepth; i++) { try { ITmfStateValue stateValue = queryOngoingState(getQuarkRelative(attributeQuark, String.valueOf(i))); if (stateValue.isNull()) { emptySpaceDepth = i; break; } } catch (AttributeNotFoundException e) { } } stackDepth++; subAttributeQuark = getQuarkRelativeAndAdd(attributeQuark, String.valueOf(emptySpaceDepth)); modifyAttribute(t, stackDepth, attributeQuark); modifyAttribute(t, value, subAttributeQuark); }
Source:
private String convertPartitionKeyToString(Object partitionKey) { String ret; if (partitionKey instanceof String) { ret = (String) partitionKey; } else if (partitionKey instanceof Integer) { ret = String.valueOf(partitionKey); } else if (partitionKey instanceof byte[]) { ret = new String((byte[]) partitionKey, Charset.defaultCharset()); } else { throw new SamzaException("Unsupported key type: " + partitionKey.getClass().toString()); } if (ret != null && ret.length() > ClientConstants.MAX_PARTITION_KEY_LENGTH) { LOG.debug("length of partitioning key ({}) exceeds limit: {}. Will truncate the key...", ret.length(), ClientConstants.MAX_PARTITION_KEY_LENGTH); ret = ret.substring(0, ClientConstants.MAX_PARTITION_KEY_LENGTH); } return ret; }

Target:
private String convertPartitionKeyToString(Object partitionKey) { String partitionKeyStr; if (partitionKey instanceof String) { partitionKeyStr = (String) partitionKey; } else if (partitionKey instanceof Integer) { partitionKeyStr = String.valueOf(partitionKey); } else if (partitionKey instanceof byte[]) { partitionKeyStr = new String((byte[]) partitionKey, Charset.defaultCharset()); } else { throw new SamzaException("Unsupported key type: " + partitionKey.getClass().toString()); } if (partitionKeyStr != null && partitionKeyStr.length() > ClientConstants.MAX_PARTITION_KEY_LENGTH) { LOG.debug("Length of partition key: exceeds limit: {}. Truncating.", partitionKeyStr.length(), ClientConstants.MAX_PARTITION_KEY_LENGTH); partitionKeyStr = partitionKeyStr.substring(0, ClientConstants.MAX_PARTITION_KEY_LENGTH); } return partitionKeyStr; }
Source:
private static void loadRules(URI uri, List<String> scriptNames, List<String> scripts) throws IOException { FileSystem fs = null; String entryName = uri.toString(); int separator = entryName.indexOf(PATH_JAR_SEPARATOR); if (separator != -1) { fs = FileSystems.newFileSystem(URI.create(entryName.substring(0, separator)), Collections.<String, Object>emptyMap()); entryName = entryName.substring(separator + PATH_JAR_SEPARATOR.length()); } else if (entryName.startsWith(FILE_SCHEME)) { fs = FileSystems.getFileSystem(URI.create(FILE_SCHEME + File.separator)); entryName = entryName.substring(5); } if (fs != null) { try { Path rules = fs.getPath(entryName); Files.walk(rules).filter(f -> f.toString().endsWith(RULE_FILE_EXTENSION)).forEach(f -> { try { scripts.add(new String(Files.readAllBytes(f))); scriptNames.add(f.toString()); } catch (IOException ioe) { log.log(Level.SEVERE, "Failed to load rule file: " + f.toString(), ioe); } }); } finally { if (separator != -1) { fs.close(); } } } }

Target:
private static void loadRules(URI uri, List<String> scriptNames, List<String> scripts) throws IOException { FileSystem fs = null; String entryName = uri.toString(); int separator = entryName.indexOf(PATH_JAR_SEPARATOR); if (separator != -1) { fs = FileSystems.newFileSystem(URI.create(entryName.substring(0, separator)), Collections.<String, Object>emptyMap()); entryName = entryName.substring(separator + PATH_JAR_SEPARATOR.length()); } else if (entryName.startsWith(FILE_SCHEME)) { fs = FileSystems.getFileSystem(URI.create(FILE_SCHEME + File.separator)); entryName = entryName.substring(FILE_SCHEME.length()); } if (fs != null) { try { Path rules = fs.getPath(entryName); Files.walk(rules).filter(f -> f.toString().endsWith(RULE_FILE_EXTENSION)).forEach(f -> { try { scripts.add(new String(Files.readAllBytes(f))); scriptNames.add(f.toString()); } catch (IOException ioe) { log.log(Level.SEVERE, "Failed to load rule file: " + f.toString(), ioe); } }); } finally { if (separator != -1) { fs.close(); } } } }
Source:
public static MeasurementUnits bestFitUnits(double[] values, MeasurementUnits originalUnits) { Double average = 0.0; for (int i = 0, sz = values.length; i < sz; i++) { average += (values[i] / sz); } MeasurementNumericValueAndUnits fittedAverage = fit(average, originalUnits); return fittedAverage.getUnits(); }

Target:
public static MeasurementUnits bestFitUnits(double[] values, MeasurementUnits originalUnits) { Double average = 0.0; for (int i = 0; i < values.length; i++) { average += (values[i] / values.length); } MeasurementNumericValueAndUnits fittedAverage = fit(average, originalUnits); return fittedAverage.getUnits(); }
Source:
protected void getFollowing(Long id) { Preconditions.checkArgument(endpoint.equals("friends") || endpoint.equals("followers")); if( ids_only == true ) collectIds(id); else collectUsers(id); }

Target:
protected void getFollowing(Long id) { Preconditions.checkArgument(endpoint.equals("friends") || endpoint.equals("followers")); if( idsOnly ) collectIds(id); else collectUsers(id); }
Source:
public void should_create_error_message_for_file_not_has_size() { ErrorMessageFactory factory = shouldHaveSize(new FakeFile("abc"), 3L); String expectedErrorMessage = format("[Test] %n" + "Expecting file%n" + " <abc>%n" + "to have size:%n" + " <3L>%n" + "but had:%n" + " <0L>"); assertThat(factory.create(new TextDescription("Test"), new StandardRepresentation())).isEqualTo(expectedErrorMessage); }

Target:
public void should_create_error_message_for_file_not_has_size() { ErrorMessageFactory factory = shouldHaveSize(new FakeFile("abc"), 3L); String expectedErrorMessage = format("[Test] %n" + "Expecting file%n" + " <abc>%n" + "to have size of:%n" + " 3L bytes%n" + "but had:%n" + " 0L bytes"); String actualErrorMessage = factory.create(new TextDescription("Test"), new StandardRepresentation()); assertThat(actualErrorMessage).isEqualTo(expectedErrorMessage); }
Source:
public static boolean isCssEnabled(){ try{ SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); return properties.getString(CSS_ENABLED, BuildConfig.DEBUG ? CommCarePreferences.YES : CommCarePreferences.NO).equals(CommCarePreferences.YES); } catch(NullPointerException e){ return false; } }

Target:
public static boolean isCssEnabled(){ return doesPropertyMatch(CSS_ENABLED, CommCarePreferences.NO, CommCarePreferences.YES); }
Source:
public Predicate<EngineVersionDTO> createFilter(EngineCategoryDTO engineCategory, EngineSubCategoryDTO engineSubCategory) { return engineVersion -> { return searchTerm .map(searchTerm -> engineVersion.getVersion().toLowerCase().contains(searchTerm.toLowerCase())) .orElse(true) && ((this.showInstalled.getValue() && isInstalled(engineCategory, engineSubCategory, engineVersion)) || (this.showNotInstalled.getValue() && !isInstalled(engineCategory, engineSubCategory, engineVersion))); }; }

Target:
public Predicate<EngineVersionDTO> createFilter(EngineCategoryDTO engineCategory, EngineSubCategoryDTO engineSubCategory) { return engineVersion -> { final boolean containsSearchTerm = searchTerm .map(searchTerm -> engineVersion.getVersion().toLowerCase().contains(searchTerm.toLowerCase())) .orElse(true); final boolean fulfillsShowInstalled = this.showInstalled.getValue() && isInstalled(engineCategory, engineSubCategory, engineVersion); final boolean fulfillsShowNotInstalled = this.showNotInstalled.getValue() && !isInstalled(engineCategory, engineSubCategory, engineVersion); return containsSearchTerm && (fulfillsShowInstalled || fulfillsShowNotInstalled); }; }
Source:
public ProtocolMessageEnum deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { int intValue = jsonParser.getIntValue(); Class<?> enumClass = Preconditions.checkNotNull(javaType, "javaType").getRawClass(); try { return (ProtocolMessageEnum) enumClass.getMethod("forNumber", int.class).invoke(null, intValue); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { context.reportWrongTokenException(ProtocolMessageEnum.class, JsonToken.VALUE_NUMBER_INT, wrongTokenMessage(context)); throw new AssertionError(); } }

Target:
public ProtocolMessageEnum deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { int intValue = jsonParser.getIntValue(); try { return (ProtocolMessageEnum) Preconditions.checkNotNull(forNumberMethod, "forNumberMethod").invoke(null, intValue); } catch (IllegalAccessException | InvocationTargetException e) { context.reportWrongTokenException(ProtocolMessageEnum.class, JsonToken.VALUE_NUMBER_INT, wrongTokenMessage(context)); throw new AssertionError(); } }
Source:
private void assignInstancesToContainers( ArrayList<Container> containers, Map<Integer, List<InstanceId>> allocation, Map<String, Integer> parallelismMap, int firstTaskIndex) { ArrayList<RamRequirement> ramRequirements = getSortedRAMInstances(parallelismMap); int globalTaskIndex = firstTaskIndex; for (RamRequirement ramRequirement : ramRequirements) { String component = ramRequirement.getComponentName(); int numInstance = parallelismMap.get(component); for (int j = 0; j < numInstance; j++) { Resource instanceResource = this.defaultInstanceResources.cloneWithRam(ramRequirement.getRamRequirement()); int containerId = placeFFDInstance(containers, instanceResource, new InstanceId( component, globalTaskIndex, j)); List<InstanceId> instances = allocation.get(containerId); if (instances == null) { instances = new ArrayList<>(); } instances.add(new InstanceId(component, globalTaskIndex++, j)); allocation.put(containerId, instances); } } }

Target:
private void assignInstancesToContainers( ArrayList<Container> containers, Map<Integer, List<InstanceId>> allocation, Map<String, Integer> parallelismMap, int firstTaskIndex) { ArrayList<RamRequirement> ramRequirements = getSortedRAMInstances(parallelismMap); int globalTaskIndex = firstTaskIndex; for (RamRequirement ramRequirement : ramRequirements) { String component = ramRequirement.getComponentName(); int numInstance = parallelismMap.get(component); for (int j = 0; j < numInstance; j++) { Resource instanceResource = this.defaultInstanceResources.cloneWithRam(ramRequirement.getRamRequirement()); int containerId = placeFFDInstance(containers, new PackingPlan.InstancePlan(new InstanceId( component, globalTaskIndex, j), instanceResource)); List<InstanceId> instances = allocation.get(containerId); if (instances == null) { instances = new ArrayList<>(); } instances.add(new InstanceId(component, globalTaskIndex++, j)); allocation.put(containerId, instances); } } }
Source:
private void dumpLongRunningTransaction(IgniteInternalTx tx) { if (cctx.tm().txOwnerDumpRequestsAllowed() && tx.local() && tx.state() == TransactionState.ACTIVE) { Collection<UUID> masterNodeIds = tx.masterNodeIds(); if (masterNodeIds.size() == 1) { UUID nearNodeId = masterNodeIds.iterator().next(); long txOwnerThreadId = tx.threadId(); Ignite ignite = cctx.kernalContext().grid(); ClusterGroup nearNode = ignite.cluster().forNodeId(nearNodeId); if (allNodesSupports(nearNode.nodes(), TRANSACTION_OWNER_THREAD_DUMP_PROVIDING)) { IgniteCompute compute = ignite.compute(ignite.cluster().forNodeId(nearNodeId)); try { compute .callAsync(new FetchActiveTxOwnerTraceClosure(txOwnerThreadId)) .listen(new IgniteInClosure<IgniteFuture<String>>() { @Override public void apply(IgniteFuture<String> strIgniteFut) { String traceDump = null; try { traceDump = strIgniteFut.get(); } catch (Exception e) { U.warn( diagnosticLog, "Could not get thread dump from transaction owner near node: " + e.getMessage() ); } if (traceDump != null) { U.warn( diagnosticLog, String.format( "Dumping the near node thread that started transaction [xidVer=%s]\n%s", tx.xidVersion().toString(), traceDump ) ); } } }); } catch (Exception e) { U.warn(diagnosticLog, "Could not send dump request to transaction owner near node: " + e.getMessage()); } } else { U.warn( diagnosticLog, "Could not send dump request to transaction owner near node: node does not support this feature." ); } } } }

Target:
private void dumpLongRunningTransaction(IgniteInternalTx tx) { if (cctx.tm().txOwnerDumpRequestsAllowed() && tx.local() && tx.state() == TransactionState.ACTIVE) { Collection<UUID> masterNodeIds = tx.masterNodeIds(); if (masterNodeIds.size() == 1) { UUID nearNodeId = masterNodeIds.iterator().next(); long txOwnerThreadId = tx.threadId(); Ignite ignite = cctx.kernalContext().grid(); ClusterGroup nearNode = ignite.cluster().forNodeId(nearNodeId); if (allNodesSupports(nearNode.nodes(), TRANSACTION_OWNER_THREAD_DUMP_PROVIDING)) { IgniteCompute compute = ignite.compute(ignite.cluster().forNodeId(nearNodeId)); try { compute .callAsync(new FetchActiveTxOwnerTraceClosure(txOwnerThreadId)) .listen(new IgniteInClosure<IgniteFuture<String>>() { @Override public void apply(IgniteFuture<String> strIgniteFut) { String traceDump = null; try { traceDump = strIgniteFut.get(); } catch (Exception e) { U.error( diagnosticLog, "Could not get thread dump from transaction owner near node: ", e ); } if (traceDump != null) { U.warn( diagnosticLog, String.format( "Dumping the near node thread that started transaction [xidVer=%s]\n%s", tx.xidVersion().toString(), traceDump ) ); } } }); } catch (Exception e) { U.error(diagnosticLog, "Could not send dump request to transaction owner near node: ", e); } } else { U.warn( diagnosticLog, "Could not send dump request to transaction owner near node: node does not support this feature." ); } } } }
Source:
public List<String> getApplicableCallOwners() { return Arrays.asList( JAVAX_CRYPTO_KEY_GENERATOR, JAVA_SECURITY_KEY_PAIR_GENERATOR, JAVAX_CRYPTO_KEY_AGREEMENT, OWNER_SECURE_RANDOM ); }

Target:
public List<String> getApplicableCallOwners() { return Arrays.asList( JAVAX_CRYPTO_KEY_GENERATOR, JAVA_SECURITY_KEY_PAIR_GENERATOR, JAVAX_CRYPTO_KEY_AGREEMENT, OWNER_SECURE_RANDOM, JAVAX_NET_SSL_SSLENGINE, JAVAX_CRYPTO_SIGNATURE, JAVAX_CRYPTO_CIPHER ); }
Source:
public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } CourseSignup entity = courseService.signup(courseId, components, email, message); ResponseBuilderImpl builder = new ResponseBuilderImpl(); builder.status(201); builder.entity(entity); return builder.build(); }

Target:
public Response signup(@FormParam("courseId") String courseId, @FormParam("components")Set<String> components, @FormParam("email")String email, @FormParam("message")String message) { if (UserDirectoryService.getAnonymousUser().equals(UserDirectoryService.getCurrentUser())) { throw new WebApplicationException(Response.Status.FORBIDDEN); } CourseSignup entity = courseService.signup(courseId, components, email, message); ResponseBuilder builder = new ResponseBuilderImpl(); builder.status(201); builder.entity(entity); return builder.build(); }
Source:
public T call() throws Exception { Exception lastException = null; do { try { logger.fine(String.format("%d tries remaining for task %s", triesRemaining, task)); T t = task.call(); logger.fine(String.format("Success with %d tries remaining for task %s", triesRemaining, task)); return t; } catch (RetryException re) { throw re; } catch (InterruptedException e) { throw e; } catch (Exception e) { lastException = e; Thread.sleep(timeToWait); } } while (--triesRemaining > 0); throw new RetryException(String.format("Failed after %d attempts for task %s", totalRetries, task), lastException); }

Target:
public T call() throws Exception { Exception lastException = null; do { try { logger.fine(String.format("%d tries remaining for task %s", triesRemaining, task)); T t = task.call(); return t; } catch (RetryException re) { throw re; } catch (InterruptedException e) { throw e; } catch (Exception e) { lastException = e; Thread.sleep(timeToWait); } } while (--triesRemaining > 0); throw new RetryException(String.format("Failed after %d attempts for task %s", totalTries, task), lastException); }
Source:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); boolean checkForInstructorAccess = logic.getInstructorForGoogleId(courseId, userInfo.getId()) != null; if (userInfo.isInstructor && checkForInstructorAccess) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(courseId, userInfo.getId()), logic.getCourse(courseId)); return; } boolean checkForStudentAccess = logic.getStudentForGoogleId(courseId, userInfo.getId()) != null; if (userInfo.isStudent && checkForStudentAccess) { CourseAttributes course = logic.getCourse(courseId); gateKeeper.verifyAccessible(logic.getStudentForGoogleId(courseId, userInfo.id), course); return; } throw new UnauthorizedAccessException("Student or instructor account is required to access this resource."); }

Target:
public void checkSpecificAccessControl() { String courseId = getNonNullRequestParamValue(Const.ParamsNames.COURSE_ID); String entityType = getNonNullRequestParamValue(Const.ParamsNames.ENTITY_TYPE); if (userInfo.isInstructor && Const.EntityType.INSTRUCTOR.equals(entityType)) { gateKeeper.verifyAccessible( logic.getInstructorForGoogleId(courseId, userInfo.getId()), logic.getCourse(courseId)); return; } if (userInfo.isStudent && Const.EntityType.STUDENT.equals(entityType)) { CourseAttributes course = logic.getCourse(courseId); gateKeeper.verifyAccessible(logic.getStudentForGoogleId(courseId, userInfo.id), course); return; } throw new UnauthorizedAccessException("Student or instructor account is required to access this resource."); }
Source:
private ResultScanner<Row> streamRows(ReadRowsRequest request) { PooledChannel reservedChannel = channelPool.reserveChannel(); final ClientCall<ReadRowsRequest, ReadRowsResponse> readRowsCall = reservedChannel.newCall(BigtableServiceGrpc.METHOD_READ_ROWS, CallOptions.DEFAULT); CancellationToken cancellationToken = new CancellationToken(); cancellationToken.addListener(new Runnable() { @Override public void run() { readRowsCall.cancel(); } }, executorService); int timeout = retryOptions.getReadPartialRowTimeoutMillis(); int streamingBufferSize = retryOptions.getStreamingBufferSize(); int batchRequestSize = retryOptions.getStreamingBatchSize(); ResponseQueueReader responseQueueReader = new ResponseQueueReader(timeout, streamingBufferSize, batchRequestSize, batchRequestSize, readRowsCall); System.out.println(String.format("Buffer size: %d, Batch size: %d", streamingBufferSize, batchRequestSize)); StreamingBigtableResultScanner resultScanner = new StreamingBigtableResultScanner(reservedChannel, responseQueueReader, cancellationToken); clientCallService.asyncServerStreamingCall( readRowsCall, request, createClientCallListener(resultScanner)); if (batchRequestSize > 1) { readRowsCall.request(batchRequestSize - 1); } return resultScanner; }

Target:
private ResultScanner<Row> streamRows(ReadRowsRequest request) { PooledChannel reservedChannel = channelPool.reserveChannel(); final ClientCall<ReadRowsRequest, ReadRowsResponse> readRowsCall = reservedChannel.newCall(BigtableServiceGrpc.METHOD_READ_ROWS, CallOptions.DEFAULT); CancellationToken cancellationToken = new CancellationToken(); cancellationToken.addListener(new Runnable() { @Override public void run() { readRowsCall.cancel(); } }, executorService); int timeout = retryOptions.getReadPartialRowTimeoutMillis(); int streamingBufferSize = retryOptions.getStreamingBufferSize(); int batchRequestSize = retryOptions.getStreamingBatchSize(); ResponseQueueReader responseQueueReader = new ResponseQueueReader(timeout, streamingBufferSize, batchRequestSize, batchRequestSize, readRowsCall); StreamingBigtableResultScanner resultScanner = new StreamingBigtableResultScanner(reservedChannel, responseQueueReader, cancellationToken); clientCallService.asyncServerStreamingCall( readRowsCall, request, createClientCallListener(resultScanner)); if (batchRequestSize > 1) { readRowsCall.request(batchRequestSize - 1); } return resultScanner; }
Source:
private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); if (destinationPath == PathManager.getInstance().getRecordingPath("")) { return false; } return !StringUtils.isBlank(name); }

Target:
private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); return !destinationPath.equals(PathManager.getInstance().getRecordingPath("")); }
Source:
public CommandWrapper() { command = null; }

Target:
public CommandWrapper() { this(null); }
Source:
public ByAll(By[] bys) { super(bys); checkNotNull(bys); if (bys.length == 0) { throw new IllegalArgumentException("By array should not be empty"); } this.bys = bys; }

Target:
public ByAll(By[] bys) { super(bys); checkNotNull(bys); this.bys = Arrays.asList(bys); checkArgument(this.bys.isEmpty(), "By array should not be empty"); }
Source:
RecoveryTestClusterManager(StaticClusterManager staticClusterManager, HelixClusterManager helixClusterManager) { this.staticClusterManager = staticClusterManager; this.helixClusterManager = helixClusterManager; ambryDataNodeToDataNodeMap = new HashMap<>(); ambryDiskToDiskMap = new HashMap<>(); }

Target:
RecoveryTestClusterManager(StaticClusterManager staticClusterManager, HelixClusterManager helixClusterManager) { this.staticClusterManager = Objects.requireNonNull(staticClusterManager); this.helixClusterManager = Objects.requireNonNull(helixClusterManager); ambryDataNodeToDataNodeMap = new HashMap<>(); ambryDiskToDiskMap = new HashMap<>(); }
Source:
public String createAvatarHtml() { StringWriter string = new StringWriter(); HtmlWriter html = new HtmlWriter(string); try { String name = getName(); html.writeStart("span", "class", "ToolUserAvatar", "title", name); { StringBuilder initials = new StringBuilder(); String[] nameParts = name.split("\\s+"); for (int i = 0, length = nameParts.length; i < length; ++ i) { String namePart = nameParts[i]; if (!StringUtils.isBlank(namePart)) { char initial = namePart.charAt(0); if (Character.isLetter(initial)) { initials.append(initial); if (initials.length() >= 2) { break; } } } } html.writeHtml(initials); StorageItem avatar = getAvatar(); if (avatar != null) { html.writeElement("img", "src", ImageEditor.Static.resize(ImageEditor.Static.getDefault(), avatar, null, 100, 100).getPublicUrl()); } else { String email = getEmail(); if (!ObjectUtils.isBlank(email)) { String hash = StringUtils.hex(StringUtils.md5(email.trim().toLowerCase(Locale.ENGLISH))); html.writeElement("img", "src", StringUtils.addQueryParameters( "<LINK_0>" + hash, "s", 100, "d", "blank")); } } } html.writeEnd(); return string.toString(); } catch (IOException error) { throw new IllegalStateException(error); } }

Target:
public String createAvatarHtml() { StringWriter string = new StringWriter(); HtmlWriter html = new HtmlWriter(string); try { String name = getName(); html.writeStart("span", "class", "ToolUserAvatar", "title", name); { StringBuilder initials = new StringBuilder(); if (StringUtils.isBlank(name)) { initials.append("?"); } else { String[] nameParts = name.trim().split("\\s+"); for (int i = 0, length = nameParts.length; i < length; ++i) { char initial = nameParts[i].charAt(0); if (Character.isLetter(initial)) { initials.append(initial); if (initials.length() >= 2) { break; } } } } html.writeHtml(initials); StorageItem avatar = getAvatar(); if (avatar != null) { html.writeElement("img", "src", ImageEditor.Static.resize(ImageEditor.Static.getDefault(), avatar, null, 100, 100).getPublicUrl()); } else { String email = getEmail(); if (!ObjectUtils.isBlank(email)) { String hash = StringUtils.hex(StringUtils.md5(email.trim().toLowerCase(Locale.ENGLISH))); html.writeElement("img", "src", StringUtils.addQueryParameters( "<LINK_0>" + hash, "s", 100, "d", "blank")); } } } html.writeEnd(); return string.toString(); } catch (IOException error) { throw new IllegalStateException(error); } }
Source:
public void addCommonWhereConditions(final Optional<Integer> gid, final StringBuilder builder) { builder.append("WHERE g.deleted = 0 AND g.gpid1 = :femaleParentId "); if(gid.isPresent()) { builder.append("AND g.gid <> :gid "); } }

Target:
private void addCommonWhereConditions(final Optional<Integer> gid, final StringBuilder builder) { builder.append("WHERE g.deleted = 0 AND g.gpid1 = :femaleParentId "); if(gid.isPresent()) { builder.append("AND g.gid <> :gid "); } }
Source:
void insertProperties(final DataObject dataObject) { final DataType existing = findDataTypeByName(dataObject.getClassType()); final DataTypeListItem item = findItem(existing).get(); for (final DataObjectProperty property : dataObject.getProperties()) { final DataType newDataType = createNewDataType(property); item.insertNestedField(newDataType); } }

Target:
void insertProperties(final DataObject dataObject) { final Optional<DataType> existing = findDataTypeByName(dataObject.getClassType()); existing.ifPresent(dataType -> { findItem(dataType).ifPresent(item -> { for (final DataObjectProperty property : dataObject.getProperties()) { final DataType newDataType = createNewDataType(property); item.insertNestedField(newDataType); } }); }); }
Source:
protected HttpURLConnection configureRequest(final HttpURLConnection request) { GitHubAccount account = accountProvider.get(); if (Log.isLoggable(TAG, DEBUG)) Log.d(TAG, "Authenticating using " + account); if(account.authToken != null) setOAuth2Token(account.authToken); else setCredentials(account.username, account.password); return super.configureRequest(request); }

Target:
protected HttpURLConnection configureRequest(final HttpURLConnection request) { GitHubAccount account = accountProvider.get(); if (Log.isLoggable(TAG, DEBUG)) Log.d(TAG, "Authenticating using " + account); if(!TextUtils.isEmpty(account.authToken)) setOAuth2Token(account.authToken); else setCredentials(account.username, account.password); return super.configureRequest(request); }
Source:
public boolean isItemRangeMeetingDisplayed() { WebElement elem = driver.findElement(By.xpath(" + "/descendant::div[contains(@class,'item range meeting')]")); return elem.isDisplayed(); }

Target:
public boolean isItemRangeMeetingDisplayed() { return itemRangeMeeting.isDisplayed(); }
Source:
private ListenableFuture<Void> deinitInternal() { synchronized (mInitDeinitLock) { switch (mInitState) { case UNINITIALIZED: return Futures.immediateFuture(null); case INITIALIZING: throw new IllegalStateException( "CameraX could not be deinitialized when it is initializing."); case INITIALIZED: mInitState = InternalInitState.DEINITIALIZED; mDeinitInternalFuture = CallbackToFutureAdapter.getFuture( completer -> { ListenableFuture<Void> future = mCameraRepository.deinit(); future.addListener(() -> { if (mCameraExecutor instanceof CameraExecutor) { CameraExecutor executor = (CameraExecutor) mCameraExecutor; executor.deinit(); } completer.set(null); }, mCameraExecutor); return "CameraX deinitInternal"; } ); return mDeinitInternalFuture; case DEINITIALIZED: return mDeinitInternalFuture; default: throw new IllegalStateException( "deinitInternal() should not be possible from state: " + mInitState); } } }

Target:
private ListenableFuture<Void> deinitInternal() { synchronized (mInitDeinitLock) { switch (mInitState) { case UNINITIALIZED: mInitState = InternalInitState.DEINITIALIZED; return Futures.immediateFuture(null); case INITIALIZING: throw new IllegalStateException( "CameraX could not be deinitialized when it is initializing."); case INITIALIZED: mInitState = InternalInitState.DEINITIALIZED; mDeinitInternalFuture = CallbackToFutureAdapter.getFuture( completer -> { ListenableFuture<Void> future = mCameraRepository.deinit(); future.addListener(() -> { if (mCameraExecutor instanceof CameraExecutor) { CameraExecutor executor = (CameraExecutor) mCameraExecutor; executor.deinit(); } completer.set(null); }, mCameraExecutor); return "CameraX deinitInternal"; } ); case DEINITIALIZED: break; } } return mDeinitInternalFuture; }
Source:
public void setName(String name) { if(!PodTemplateUtils.validateContainerName(name)) { throw new IllegalArgumentException(String.format("Container Names MUST match RFC 1123 - They can only contain lowercase letters, numbers or dashes. ContainerName-%s",name)); } this.name = name; }

Target:
public void setName(String name) { this.name = name; }
Source:
public NetworkDispatcher(NetworkManager manager) { super(false); this.manager = manager; this.scm = null; this.side = Side.CLIENT; this.modList = new HashMap<>(); this.handshakeChannel = new EmbeddedChannel(new HandshakeInjector(this), new ChannelRegistrationHandler(), new FMLHandshakeCodec(), new HandshakeMessageHandler<FMLHandshakeClientState>(FMLHandshakeClientState.class)); this.handshakeChannel.attr(FML_DISPATCHER).set(this); this.handshakeChannel.attr(NetworkRegistry.CHANNEL_SOURCE).set(Side.SERVER); this.handshakeChannel.attr(NetworkRegistry.FML_CHANNEL).set("FML|HS"); this.handshakeChannel.attr(IS_LOCAL).set(manager.isLocalChannel()); if (DEBUG_HANDSHAKE) PacketLoggingHandler.register(manager); }

Target:
public NetworkDispatcher(NetworkManager manager) { super(false); this.manager = manager; this.scm = null; this.side = Side.CLIENT; this.handshakeChannel = new EmbeddedChannel(new HandshakeInjector(this), new ChannelRegistrationHandler(), new FMLHandshakeCodec(), new HandshakeMessageHandler<FMLHandshakeClientState>(FMLHandshakeClientState.class)); this.handshakeChannel.attr(FML_DISPATCHER).set(this); this.handshakeChannel.attr(NetworkRegistry.CHANNEL_SOURCE).set(Side.SERVER); this.handshakeChannel.attr(NetworkRegistry.FML_CHANNEL).set("FML|HS"); this.handshakeChannel.attr(IS_LOCAL).set(manager.isLocalChannel()); if (DEBUG_HANDSHAKE) PacketLoggingHandler.register(manager); }
Source:
public final void onSensorChanged(SensorEvent sensorEvent) { JsonObject jsonObject = new JsonObject(); if (timestampZeroReferenceNanos <= 0) { timestampZeroReferenceNanos = sensorEvent.timestamp; long uptimeNanos; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { uptimeNanos = SystemClock.elapsedRealtimeNanos(); } else { uptimeNanos = SystemClock.elapsedRealtime() * 100000; } long timestampReferenceMillis = System.currentTimeMillis() + ((timestampZeroReferenceNanos - uptimeNanos) / 1000000L); Date timestampReferenceDate = new Date(timestampReferenceMillis); jsonObject.addProperty(TIMESTAMP_DATE_KEY, new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601, Locale.getDefault()) .format(timestampReferenceDate)); } jsonObject.addProperty(TIMESTAMP_IN_SECONDS_KEY, (sensorEvent.timestamp - timestampZeroReferenceNanos) * 1e-9); jsonObject.addProperty(UPTIME_IN_SECONDS_KEY, sensorEvent.timestamp * 1e-9); recordSensorEvent(sensorEvent, jsonObject); writeJsonObjectToFile(jsonObject); }

Target:
public final void onSensorChanged(SensorEvent sensorEvent) { JsonObject jsonObject = new JsonObject(); if (timestampZeroReferenceNanos <= 0) { timestampZeroReferenceNanos = sensorEvent.timestamp; long uptimeNanos; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { uptimeNanos = SystemClock.elapsedRealtimeNanos(); } else { uptimeNanos = (long) (SystemClock.elapsedRealtime() * 1e6); } long timestampReferenceMillis = System.currentTimeMillis() + (long) ((timestampZeroReferenceNanos - uptimeNanos) * 1e-6d); Date timestampReferenceDate = new Date(timestampReferenceMillis); jsonObject.addProperty(TIMESTAMP_DATE_KEY, new SimpleDateFormat(FormatHelper.DATE_FORMAT_ISO_8601, Locale.getDefault()) .format(timestampReferenceDate)); } jsonObject.addProperty(TIMESTAMP_IN_SECONDS_KEY, (sensorEvent.timestamp - timestampZeroReferenceNanos) * 1e-9); jsonObject.addProperty(UPTIME_IN_SECONDS_KEY, sensorEvent.timestamp * 1e-9); recordSensorEvent(sensorEvent, jsonObject); writeJsonObjectToFile(jsonObject); }
Source:
private static <T> ClassLoadingStrategy<ClassLoader> chooseClassLoadingStrategy(Class<T> type) { try { final ClassLoadingStrategy<ClassLoader> strategy; if (ClassInjector.UsingLookup.isAvailable() && privateLookupIn != null && lookup != null) { Object privateLookup = privateLookupIn.invoke(null, type, lookup); strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); } else if (ClassInjector.UsingReflection.isAvailable()) { strategy = ClassLoadingStrategy.Default.INJECTION; } else { throw new IllegalStateException("No code generation strategy available"); } return strategy; } catch (Exception e) { return null; } }

Target:
private static <T> ClassLoadingStrategy<ClassLoader> chooseClassLoadingStrategy(Class<T> type) { try { final ClassLoadingStrategy<ClassLoader> strategy; if (ClassInjector.UsingLookup.isAvailable() && PRIVATE_LOOKUP_IN != null && LOOKUP != null) { Object privateLookup = PRIVATE_LOOKUP_IN.invoke(null, type, LOOKUP); strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); } else if (ClassInjector.UsingReflection.isAvailable()) { strategy = ClassLoadingStrategy.Default.INJECTION; } else { throw new IllegalStateException("No code generation strategy available"); } return strategy; } catch (InvocationTargetException e) { throw new IllegalStateException("Failed to invoke 'privateLookupIn' method from java.lang.invoke.MethodHandles$Lookup.", e); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to invoke 'privateLookupIn' method from java.lang.invoke.MethodHandles$Lookup.", e); } }
Source:
public String getInstanceID() { context.ensureOpen(); final String instanceName = context.info.getInstanceName(); if (context.instanceId == null) { String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + instanceName; byte[] iidb = context.zooCache.get(instanceNamePath); if (iidb == null) { throw new RuntimeException( "Instance name " + instanceName + " does not exist in zookeeper. " + "Run \"accumulo org.apache.accumulo.server.util.ListInstances\" to see a list."); } context.instanceId = new String(iidb, UTF_8); } if (context.zooCache.get(Constants.ZROOT + "/" + context.instanceId) == null) { if (instanceName == null) throw new RuntimeException( "Instance id " + context.instanceId + " does not exist in zookeeper"); throw new RuntimeException("Instance id " + context.instanceId + " pointed to by the name " + instanceName + " does not exist in zookeeper"); } return context.instanceId; }

Target:
public String getInstanceID() { return context.getInstanceID(); }
Source:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { final CachedAsset cachedAsset = loadAsset(req.getRequestURI()); if (cachedAsset == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (isCachedClientSide(req, cachedAsset)) { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime()); resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag()); final Buffer mimeType = mimeTypes.getMimeByExtension(req.getRequestURI()); MediaType mediaType = DEFAULT_MEDIA_TYPE; if (mimeType != null) { try { mediaType = MediaType.parse( mimeType.toString() ); if (defaultCharset != null && mediaType.is( MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } } catch ( IllegalArgumentException ignore ) } resp.setContentType( mediaType.type() + "/" + mediaType.subtype() ); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding( mediaType.charset().get().toString() ); } final ServletOutputStream output = resp.getOutputStream(); try { output.write(cachedAsset.getResource()); } finally { output.close(); } } catch (RuntimeException ignored) {ignored.printStackTrace(); resp.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (URISyntaxException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { final CachedAsset cachedAsset = loadAsset(req.getRequestURI()); if (cachedAsset == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (isCachedClientSide(req, cachedAsset)) { resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } resp.setDateHeader(HttpHeaders.LAST_MODIFIED, cachedAsset.getLastModifiedTime()); resp.setHeader(HttpHeaders.ETAG, cachedAsset.getETag()); final Buffer mimeTypeOfExtension = mimeTypes.getMimeByExtension(req.getRequestURI()); MediaType mediaType = DEFAULT_MEDIA_TYPE; if (mimeTypeOfExtension != null) { try { mediaType = MediaType.parse(mimeTypeOfExtension.toString()); if (defaultCharset != null && mediaType.is(MediaType.ANY_TEXT_TYPE)) { mediaType = mediaType.withCharset(defaultCharset); } } catch (IllegalArgumentException ignore) } resp.setContentType(mediaType.type() + "/" + mediaType.subtype()); if (mediaType.charset().isPresent()) { resp.setCharacterEncoding(mediaType.charset().get().toString()); } final ServletOutputStream output = resp.getOutputStream(); try { output.write(cachedAsset.getResource()); } finally { output.close(); } } catch (RuntimeException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (URISyntaxException ignored) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Source:
public Iterable<Object> loadObjects(EntityProjection entityProjection, RequestScope scope) { Query query = buildQuery(entityProjection, scope); return queryEngine.executeQuery(query); }

Target:
public Iterable<Object> loadObjects(EntityProjection entityProjection, RequestScope scope) { Query query = buildQuery(entityProjection, scope); QueryResult result = null; String cacheKey = null; if (cache != null && !query.isBypassingCache()) { String tableVersion = queryEngine.getTableVersion(query.getTable(), queryEngineTransaction); if (tableVersion != null) { cacheKey = tableVersion + ';' + QueryKeyExtractor.extractKey(query); result = cache.get(cacheKey); } } if (result == null) { result = queryEngine.executeQuery(query, queryEngineTransaction); if (cacheKey != null) { cache.put(cacheKey, result); } } if (entityProjection.getPagination() != null && entityProjection.getPagination().returnPageTotals()) { entityProjection.getPagination().setPageTotals(result.getPageTotals()); } return result.getData(); }
Source:
private synchronized void startZkServer() { lastCommitted = zk.getZxid(); LOG.info("Have quorum of supporters, sids: [{}]; starting up and setting last processed zxid: 0x{}", newLeaderProposal.ackSetsToString(), Long.toHexString(zk.getZxid())); if (QuorumPeerConfig.isReconfigEnabled()) { QuorumVerifier newQV = self.getLastSeenQuorumVerifier(); Long designatedLeader = getDesignatedLeader(newLeaderProposal, zk.getZxid()); self.processReconfig(newQV, designatedLeader, zk.getZxid(), true); if (designatedLeader != self.getId()) { LOG.warn("This leader is not the designated leader, it will be initialized with allowedToCommit = false"); allowedToCommit = false; } } else { LOG.debug("Reconfig feature is disabled, skip designatedLeader calculation and reconfig processing."); } leaderStartTime = Time.currentElapsedTime(); zk.startup(); self.updateElectionVote(getEpoch()); zk.getZKDatabase().setlastProcessedZxid(zk.getZxid()); }

Target:
private synchronized void startZkServer() { lastCommitted = zk.getZxid(); LOG.info("Have quorum of supporters, sids: [{}]; starting up and setting last processed zxid: 0x{}", newLeaderProposal.ackSetsToString(), Long.toHexString(zk.getZxid())); if (self.isReconfigEnabled()) { QuorumVerifier newQV = self.getLastSeenQuorumVerifier(); Long designatedLeader = getDesignatedLeader(newLeaderProposal, zk.getZxid()); self.processReconfig(newQV, designatedLeader, zk.getZxid(), true); if (designatedLeader != self.getId()) { LOG.warn("This leader is not the designated leader, it will be initialized with allowedToCommit = false"); allowedToCommit = false; } } else { LOG.info("Dynamic reconfig feature is disabled, skip designatedLeader calculation and reconfig processing."); } leaderStartTime = Time.currentElapsedTime(); zk.startup(); self.updateElectionVote(getEpoch()); zk.getZKDatabase().setlastProcessedZxid(zk.getZxid()); }
Source:
public static void validateRefPattern(String refPattern) throws InvalidNameException { if (refPattern.startsWith(ProjectConfigSection.REGEX_PREFIX)) { if (!Repository.isValidRefName(RefControl.shortestExample(refPattern))) { throw new InvalidNameException(); } } else if (refPattern.equals(ProjectConfigSection.ALL)) { } else if (refPattern.endsWith("/*")) { String prefix = refPattern.substring(0, refPattern.length() - 2); if (!Repository.isValidRefName(prefix)) { throw new InvalidNameException(refPattern); } } else if (!Repository.isValidRefName(refPattern)) { throw new InvalidNameException(refPattern); } }

Target:
public static void validateRefPattern(String refPattern) throws InvalidNameException { if (refPattern.startsWith(RefConfigSection.REGEX_PREFIX)) { if (!Repository.isValidRefName(RefControl.shortestExample(refPattern))) { throw new InvalidNameException(refPattern); } } else if (refPattern.equals(RefConfigSection.ALL)) { } else if (refPattern.endsWith("/*")) { String prefix = refPattern.substring(0, refPattern.length() - 2); if (!Repository.isValidRefName(prefix)) { throw new InvalidNameException(refPattern); } } else if (!Repository.isValidRefName(refPattern)) { throw new InvalidNameException(refPattern); } }