auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void contribute(IndexSchemaFieldDefinitionHelper<String> helper, LuceneIndexSchemaNodeCollector collector, LuceneIndexSchemaObjectNode parentNode) { if ( Sortable.YES.equals( sortable ) && analyzer != null ) { throw log.cannotUseAnalyzerOnSortableField( getSchemaContext().getEventContext() ); } if ( analyzer != null && normalizer != null ) { throw log.cannotApplyAnalyzerAndNormalizer( getSchemaContext().getEventContext() ); } Analyzer analyzerOrNormalizer = analyzer != null ? analyzer : normalizer; QueryBuilder queryBuilder = analyzerOrNormalizer != null ? new QueryBuilder( analyzerOrNormalizer ) : null; StringFieldConverter converter = new StringFieldConverter( helper.createUserIndexFieldConverter(), analyzerOrNormalizer ); LuceneIndexSchemaFieldNode<String> schemaNode = new LuceneIndexSchemaFieldNode<>( parentNode, getRelativeFieldName(), converter, new StringFieldCodec( sortable, getFieldType( getStore(), analyzer != null ), analyzerOrNormalizer ), new StringFieldPredicateBuilderFactory( converter, analyzer != null, queryBuilder ), StringFieldSortContributor.INSTANCE ); helper.initialize( new LuceneIndexFieldAccessor<>( schemaNode ) ); collector.collectFieldNode( schemaNode.getAbsoluteFieldPath(), schemaNode ); if ( analyzerOrNormalizer != null ) { collector.collectAnalyzer( schemaNode.getAbsoluteFieldPath(), analyzerOrNormalizer ); } }

Target:
protected void contribute(IndexSchemaFieldDefinitionHelper<String> helper, LuceneIndexSchemaNodeCollector collector, LuceneIndexSchemaObjectNode parentNode) { if ( analyzer != null ) { switch ( sortable ) { case DEFAULT: case NO: break; case YES: throw log.cannotUseAnalyzerOnSortableField( analyzerName, getSchemaContext().getEventContext() ); } if ( normalizer != null ) { throw log.cannotApplyAnalyzerAndNormalizer( analyzerName, normalizerName, getSchemaContext().getEventContext() ); } } Analyzer analyzerOrNormalizer = analyzer != null ? analyzer : normalizer; QueryBuilder queryBuilder = analyzerOrNormalizer != null ? new QueryBuilder( analyzerOrNormalizer ) : null; StringFieldConverter converter = new StringFieldConverter( helper.createUserIndexFieldConverter(), analyzerOrNormalizer ); LuceneIndexSchemaFieldNode<String> schemaNode = new LuceneIndexSchemaFieldNode<>( parentNode, getRelativeFieldName(), converter, new StringFieldCodec( sortable, getFieldType( getStore(), analyzer != null ), analyzerOrNormalizer ), new StringFieldPredicateBuilderFactory( converter, analyzer != null, queryBuilder ), StringFieldSortContributor.INSTANCE ); helper.initialize( new LuceneIndexFieldAccessor<>( schemaNode ) ); collector.collectFieldNode( schemaNode.getAbsoluteFieldPath(), schemaNode ); if ( analyzerOrNormalizer != null ) { collector.collectAnalyzer( schemaNode.getAbsoluteFieldPath(), analyzerOrNormalizer ); } }
Source:
protected List<String> deleteTemporaryFilesCommand() { if (!Boolean.TRUE.equals(noDeleteAfterExec)) { return ImmutableList.of( "rm -f "+scriptPath+" < /dev/null", "rm -f "+stdoutPath+" < /dev/null", "rm -f "+stderrPath+" < /dev/null", "rm -f "+exitStatusPath+" < /dev/null", "rm -f "+pidPath+" < /dev/null"); } else { return ImmutableList.<String>of(); } }

Target:
protected List<String> deleteTemporaryFilesCommand() { if (!Boolean.TRUE.equals(noDeleteAfterExec)) { return ImmutableList.of( "rm -f "+scriptPath+" "+stdoutPath+" "+stderrPath+" "+exitStatusPath+" "+pidPath+" < /dev/null"); } else { return ImmutableList.<String>of(); } }
Source:
public void display() { setShowLoginProgress(false); LoginPrefs loginPrefs = preferencesService.getPreferences().getLogin(); String username = loginPrefs.getUsername(); String password = ""; try { password = loginPrefs.getPassword(); } catch (Exception e) { loginPrefs.setPassword(""); loginPrefs.setAutoLogin(false); logger.warn("Error during password decryption, password was thrown away:", e); } boolean isAutoLogin = loginPrefs.getAutoLogin(); usernameInput.setText(Strings.nullToEmpty(username)); autoLoginCheckBox.setSelected(isAutoLogin); if (loginPrefs.getAutoLogin() && !isNullOrEmpty(username) && !isNullOrEmpty(password)) { login(username, password, true); } else if (isNullOrEmpty(username)) { usernameInput.requestFocus(); } else { passwordInput.requestFocus(); } }

Target:
public void display() { setShowLoginProgress(false); LoginPrefs loginPrefs = preferencesService.getPreferences().getLogin(); String username = loginPrefs.getUsername(); String password = loginPrefs.getPassword(); boolean isAutoLogin = loginPrefs.getAutoLogin(); usernameInput.setText(Strings.nullToEmpty(username)); autoLoginCheckBox.setSelected(isAutoLogin); if (loginPrefs.getAutoLogin() && !isNullOrEmpty(username) && !isNullOrEmpty(password)) { login(username, password, true); } else if (isNullOrEmpty(username)) { usernameInput.requestFocus(); } else { passwordInput.requestFocus(); } }
Source:
public void work() { openUserSession(); List<Blob> blobList = new ArrayList<Blob>(); DownloadService downloadService = Framework.getService(DownloadService.class); for (String docId : docIds) { DocumentRef docRef = new IdRef(docId); if (!session.exists(docRef)) { log.info(String.format("Cannot retrieve document '%s', probably deleted in the meanwhile", docId)); continue; } DocumentModel doc = session.getDocument(docRef); Blob blob = downloadService.resolveBlob(doc); if (blob == null) { log.trace("Not able to resolve blob"); continue; } else if (!downloadService.checkPermission(doc, null, blob, "download", Collections.emptyMap())) { log.debug(String.format("Not allowed to bulk download blob for document %s", doc.getId())); continue; } blobList.add(blob); } if (blobList.isEmpty()) { log.info("No blob to be zipped"); updateAndCompleteStoreEntry(Collections.emptyList()); } AutomationService as = Framework.getLocalService(AutomationService.class); try (OperationContext oc = new OperationContext(session)) { Blob blob; if (blobList.size() == 1) { blob = blobList.get(0); blob.setFilename(StringUtils.isNotBlank(this.filename) ? this.filename : this.id); } else { oc.push("filename", StringUtils.isNotBlank(this.filename) ? this.filename : this.id); oc.setInput(new BlobList(blobList)); blob = (Blob) as.run(oc, CreateZip.ID); } updateAndCompleteStoreEntry(Collections.singletonList(blob)); } catch (OperationException e) { TransientStore ts = getTransientStore(); ts.putParameter(key, DownloadService.TRANSIENT_STORE_PARAM_ERROR, e.getMessage()); throw new NuxeoException("Exception while zipping blob list", e); } }

Target:
public void work() { openUserSession(); List<Blob> blobList = new ArrayList<>(); DownloadService downloadService = Framework.getService(DownloadService.class); for (String docId : docIds) { DocumentRef docRef = new IdRef(docId); if (!session.exists(docRef)) { if (log.isDebugEnabled()) { log.debug(String.format("Cannot retrieve document '%s', probably deleted in the meanwhile", docId)); } continue; } DocumentModel doc = session.getDocument(docRef); Blob blob = downloadService.resolveBlob(doc); if (blob == null) { log.trace("Not able to resolve blob"); continue; } else if (!downloadService.checkPermission(doc, null, blob, "download", Collections.emptyMap())) { if (log.isDebugEnabled()) { log.debug( String.format("Not allowed to bulk download blob for document %s", doc.getPathAsString())); } continue; } blobList.add(blob); } if (blobList.isEmpty()) { log.debug("No blob to be zipped"); updateAndCompleteStoreEntry(Collections.emptyList()); return; } Blob blob; String finalFilename = StringUtils.isNotBlank(this.filename) ? this.filename : this.id; if (blobList.size() == 1) { blob = blobList.get(0); blob.setFilename(finalFilename); } else { try { blob = BlobUtils.zip(blobList, finalFilename); } catch (IOException e) { TransientStore ts = getTransientStore(); ts.putParameter(key, DownloadService.TRANSIENT_STORE_PARAM_ERROR, e.getMessage()); throw new NuxeoException("Exception while zipping blob list", e); } } updateAndCompleteStoreEntry(Collections.singletonList(blob)); }
Source:
public void testRegexRecordsAreProcessedAfterReassignment() throws Exception { final String topic1 = "TEST-TOPIC-1"; final String topic2 = "TEST-TOPIC-2"; CLUSTER.createTopic(topic1); final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> pattern1Stream = builder.stream(Pattern.compile("TEST-TOPIC-\\d")); pattern1Stream.to(outputTopic, Produced.with(Serdes.String(), Serdes.String())); streams = new KafkaStreams(builder.build(), streamsConfiguration); streams.start(); CLUSTER.createTopic(topic2); final KeyValue<String, String> record1 = new KeyValue<>("1", "1"); final KeyValue<String, String> record2 = new KeyValue<>("2", "2"); IntegrationTestUtils.produceKeyValuesSynchronously( topic1, Collections.singletonList(record1), TestUtils.producerConfig(CLUSTER.bootstrapServers(), StringSerializer.class, StringSerializer.class), CLUSTER.time ); IntegrationTestUtils.produceKeyValuesSynchronously( topic2, Collections.singletonList(record2), TestUtils.producerConfig(CLUSTER.bootstrapServers(), StringSerializer.class, StringSerializer.class), CLUSTER.time ); IntegrationTestUtils.waitUntilFinalKeyValueRecordsReceived( TestUtils.consumerConfig(CLUSTER.bootstrapServers(), StringDeserializer.class, StringDeserializer.class), outputTopic, Arrays.asList(record1, record2) ); CLUSTER.deleteTopicsAndWait(topic1, topic2); }

Target:
public void testRegexRecordsAreProcessedAfterReassignment() throws Exception { final String topic1 = "TEST-TOPIC-1"; CLUSTER.createTopic(topic1); final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> pattern1Stream = builder.stream(Pattern.compile("TEST-TOPIC-\\d")); pattern1Stream.to(outputTopic, Produced.with(Serdes.String(), Serdes.String())); streams = new KafkaStreams(builder.build(), streamsConfiguration); final String topic2 = "TEST-TOPIC-2"; streams.start(); CLUSTER.createTopic(topic2); final KeyValue<String, String> record1 = new KeyValue<>("1", "1"); final KeyValue<String, String> record2 = new KeyValue<>("2", "2"); IntegrationTestUtils.produceKeyValuesSynchronously( topic1, Collections.singletonList(record1), TestUtils.producerConfig(CLUSTER.bootstrapServers(), StringSerializer.class, StringSerializer.class), CLUSTER.time ); IntegrationTestUtils.produceKeyValuesSynchronously( topic2, Collections.singletonList(record2), TestUtils.producerConfig(CLUSTER.bootstrapServers(), StringSerializer.class, StringSerializer.class), CLUSTER.time ); IntegrationTestUtils.waitUntilFinalKeyValueRecordsReceived( TestUtils.consumerConfig(CLUSTER.bootstrapServers(), StringDeserializer.class, StringDeserializer.class), outputTopic, Arrays.asList(record1, record2) ); streams.close(); CLUSTER.deleteTopicsAndWait(topic1, topic2); }
Source:
public void setList_unmanagedObjectThrows() { RealmResults<AllTypes> collection = realm.where(AllTypes.class).findAll(); realm.beginTransaction(); try { collection.setList(AllTypes.FIELD_REALMLIST, new RealmList<>(new Dog())); fail(); } catch (IllegalArgumentException e) { assertTrue("Wrong error message: " + e.getMessage(), e.getMessage().contains("is not a valid a valid, managed Realm object.")); } }

Target:
public void setList_unmanagedObjectThrows() { RealmResults<AllTypes> collection = realm.where(AllTypes.class).findAll(); realm.beginTransaction(); try { collection.setList(AllTypes.FIELD_REALMLIST, new RealmList<>(new Dog())); fail(); } catch (IllegalArgumentException e) { assertTrue("Wrong error message: " + e.getMessage(), e.getMessage().contains("is not a valid, managed Realm object.")); } }
Source:
protected JoinNode rewrite(Context context, JoinNode joinNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { Assignments.Builder leftSideDereferences = Assignments.builder(); Assignments.Builder rightSideDereferences = Assignments.builder(); for (Map.Entry<VariableReferenceExpression, DereferenceExpression> entry : expressions.inverse().entrySet()) { VariableReferenceExpression baseSymbol = getBase(entry.getValue(), context.getVariableAllocator().getTypes()); if (joinNode.getLeft().getOutputVariables().contains(baseSymbol)) { leftSideDereferences.put(entry.getKey(), castToRowExpression(entry.getValue())); } else { rightSideDereferences.put(entry.getKey(), castToRowExpression(entry.getValue())); } } PlanNode leftNode = createProjectBelow(joinNode.getLeft(), leftSideDereferences.build(), context.getIdAllocator()); PlanNode rightNode = createProjectBelow(joinNode.getRight(), rightSideDereferences.build(), context.getIdAllocator()); return new JoinNode( context.getIdAllocator().getNextId(), joinNode.getType(), leftNode, rightNode, joinNode.getCriteria(), ImmutableList.<VariableReferenceExpression>builder().addAll(leftNode.getOutputVariables()).addAll(rightNode.getOutputVariables()).build(), joinNode.getFilter().map(expression -> castToRowExpression(ExpressionTreeRewriter.rewriteWith(new PushDownDereferences.DereferenceReplacer(expressions), castToExpression(expression)))), joinNode.getLeftHashVariable(), joinNode.getRightHashVariable(), joinNode.getDistributionType()); }

Target:
protected JoinNode rewrite(Context context, JoinNode joinNode, BiMap<DereferenceExpression, VariableReferenceExpression> expressions) { Assignments.Builder leftSideDereferences = Assignments.builder(); Assignments.Builder rightSideDereferences = Assignments.builder(); for (Map.Entry<VariableReferenceExpression, DereferenceExpression> entry : expressions.inverse().entrySet()) { VariableReferenceExpression baseSymbol = getBase(entry.getValue(), context.getVariableAllocator().getTypes()); if (joinNode.getLeft().getOutputVariables().contains(baseSymbol)) { leftSideDereferences.put(entry.getKey(), castToRowExpression(entry.getValue())); } else { rightSideDereferences.put(entry.getKey(), castToRowExpression(entry.getValue())); } } PlanNode leftNode = createProject(joinNode.getLeft(), leftSideDereferences.build(), context.getIdAllocator()); PlanNode rightNode = createProject(joinNode.getRight(), rightSideDereferences.build(), context.getIdAllocator()); return new JoinNode( context.getIdAllocator().getNextId(), joinNode.getType(), leftNode, rightNode, joinNode.getCriteria(), ImmutableList.<VariableReferenceExpression>builder() .addAll(leftNode.getOutputVariables()) .addAll(rightNode.getOutputVariables()) .build(), joinNode.getFilter().map(expression -> replaceDereferences(expression, expressions)), joinNode.getLeftHashVariable(), joinNode.getRightHashVariable(), joinNode.getDistributionType()); }
Source:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(AtomProviderTest.class.getSimpleName()); war.addClass(AtomProviderTest.class); war.addAsManifestResource(PermissionUtil.createPermissionsXmlAsset( new FilePermission("<<ALL FILES>>", "read"), new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("getClassLoader")), "permissions.xml"); return TestUtil.finishContainerPrepare(war, null, AtomProviderResource.class, AtomProviderCustomer.class, AtomProviderDataCollectionRecord.class, ObjectFactory.class); }

Target:
public static Archive<?> deploy() { WebArchive war = TestUtil.prepareArchive(AtomProviderTest.class.getSimpleName()); war.addClass(AtomProviderTest.class); return TestUtil.finishContainerPrepare(war, null, AtomProviderResource.class, AtomProviderCustomer.class, AtomProviderDataCollectionRecord.class, ObjectFactory.class); }
Source:
public void tick(WallClockTimestamp timestamp) { operationType = OperationType.COMMAND; long unixTimestamp = timestamp.unixTimestamp(); if (!scheduledTasks.isEmpty()) { Iterator<ScheduledTask> iterator = scheduledTasks.iterator(); while (iterator.hasNext()) { ScheduledTask task = iterator.next(); if (task.isRunnable(unixTimestamp)) { this.timestamp = task.time; this.operationType = OperationType.COMMAND; log.trace("Executing scheduled task {}", task); task.execute(); complete.add(task); iterator.remove(); } else { break; } } for (ScheduledTask task : complete) { task.reschedule(this.timestamp); } complete.clear(); } }

Target:
public void tick(WallClockTimestamp timestamp) { long unixTimestamp = timestamp.unixTimestamp(); if (!scheduledTasks.isEmpty()) { Iterator<ScheduledTask> iterator = scheduledTasks.iterator(); while (iterator.hasNext()) { ScheduledTask task = iterator.next(); if (task.isRunnable(unixTimestamp)) { this.timestamp = task.time; this.operationType = OperationType.COMMAND; log.trace("Executing scheduled task {}", task); task.execute(); complete.add(task); iterator.remove(); } else { break; } } for (ScheduledTask task : complete) { task.reschedule(this.timestamp); } complete.clear(); } }
Source:
public void testPermissionCheck() throws NameAlreadyUsedException, NoSuchProjectException, ProjectRenamingFailedException { reset(capabilityControl); expect(capabilityControl.canRenameProject()).andReturn(false).anyTimes(); replayMocks(); try { renameProject("dummysource", "dummydestination"); fail("No exception thrown, although user lacks permission to rename " + "projects"); } catch (PermissionDeniedException e) { assertTrue("PermissionDeniedException does not contain user name", e.getMessage().contains("dummyUserName")); } }

Target:
public void testPermissionCheck() throws NameAlreadyUsedException, NoSuchProjectException, ProjectRenamingFailedException { reset(capabilityControl); expect(capabilityControl.canAdministrateServer()).andReturn(false).anyTimes(); replayMocks(); try { renameProject("dummysource", "dummydestination"); fail("No exception thrown, although user lacks permission to rename " + "projects"); } catch (PermissionDeniedException e) { assertTrue("PermissionDeniedException does not contain user name", e.getMessage().contains("dummyUserName")); } }
Source:
public void testWithoutFilter() throws Exception { Config config = createConfig(false); Hazelcast.newHazelcastInstance(config); sendJoinDatagram(new TestDeserialized()); Thread.sleep(500L); assertTrueEventually(() -> assertTrue("Object was not deserializaed", TestDeserialized.isDeserialized)); }

Target:
public void testWithoutFilter() throws Exception { Config config = createConfig(false); Hazelcast.newHazelcastInstance(config); sendJoinDatagram(new TestDeserialized()); assertTrueEventually(() -> assertTrue("Object was not deserialized", TestDeserialized.isDeserialized)); }
Source:
public void testUpdateVmDevicesBootOrder() { Map<Guid, Disk> idTodisk = new HashMap<Guid, Disk>(); List<VmNetworkInterface> interfaces = new LinkedList<VmNetworkInterface>(); VmDevice nic1 = createNetworkInterface(NIC_1_ID, true, NIC_1_NAME, interfaces); VmDevice nic2 = createNetworkInterface(NIC_2_ID, true, NIC_2_NAME, interfaces); VmDevice nic3 = createNetworkInterface(NIC_3_ID, false, "", interfaces); VmDevice disk1 = createDiskDevice(DISK_1_ID, true, idTodisk); VmDevice disk2 = createDiskDevice(DISK_2_ID, false, idTodisk); VmDevice cd = createCdRomDevice(CD_ID); doReturn(idTodisk).when(vm).getDiskMap(); doReturn(interfaces).when(vm).getInterfaces(); doReturn(false).when(vm).isRunOnce(); doReturn(BootSequence.DNC).when(vm).getDefaultBootSequence(); VmDeviceCommonUtils.updateVmDevicesBootOrder( vm, Arrays.asList(disk1, nic2, cd, nic1, disk2), false); int index = 1; assertTrue(String.format("CD should have boot order = %d, actual = %d", index, cd.getBootOrder()), cd.getBootOrder() == index); ++index; assertTrue(String.format("NIC 1 should have boot order = %d, actual = %d", index, nic1.getBootOrder()), nic1.getBootOrder() == index); ++index; assertTrue(String.format("NIC 2 should have boot order = %d, actual = %d", index, nic2.getBootOrder()), nic2.getBootOrder() == index); ++index; assertTrue("NIC 3 should have boot order = 0", nic3.getBootOrder() == 0); assertTrue(String.format("Disk 1 should have boot order = %d, actual = %d", index, disk1.getBootOrder()), disk1.getBootOrder() == index); assertTrue("Disk 2 should have boot order = 0", disk2.getBootOrder() == 0); }

Target:
public void testUpdateVmDevicesBootOrder() { Map<Guid, Disk> idToDisk = new HashMap<Guid, Disk>(); List<VmNetworkInterface> interfaces = new LinkedList<VmNetworkInterface>(); VmDevice nic1 = createNetworkInterface(true, NIC_1_NAME, interfaces); VmDevice nic2 = createNetworkInterface(true, NIC_2_NAME, interfaces); VmDevice nonBootableNic = createNetworkInterface(false, "", interfaces); VmDevice bootableDisk = createDiskDevice(true, idToDisk); VmDevice nonBootableDisk = createDiskDevice(false, idToDisk); VmDevice cd = createCdRomDevice(); doReturn(idToDisk).when(vm).getDiskMap(); doReturn(interfaces).when(vm).getInterfaces(); doReturn(false).when(vm).isRunOnce(); doReturn(BootSequence.DNC).when(vm).getDefaultBootSequence(); VmDeviceCommonUtils.updateVmDevicesBootOrder( vm, Arrays.asList(bootableDisk, nic2, cd, nic1, nonBootableDisk), false); int index = 1; assertEquals("Wrong boot order for CD", index++, cd.getBootOrder()); assertEquals("Wrong boot order for nic1", index++, nic1.getBootOrder()); assertEquals("Wrong boot order for nic2", index++, nic2.getBootOrder()); assertEquals("Wrong boot order for non bootable nic", 0, nonBootableNic.getBootOrder()); assertEquals("Wrong boot order for bootable disk", index++, bootableDisk.getBootOrder()); assertEquals("Wrong boot order for non bootable disk", 0, nonBootableDisk.getBootOrder()); }
Source:
private boolean mutateSystemSetting(String name, String value, int runAsUserId, int operation) { if (!hasWriteSecureSettingsPermission()) { if (!Settings.checkAndNoteWriteSettingsOperation(getContext(), Binder.getCallingUid(), getCallingPackage(), true)) { return false; } } enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, runAsUserId); final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId); final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name); if (owningUserId != callingUserId) { return false; } synchronized (mLock) { switch (operation) { case MUTATION_OPERATION_INSERT: { validateSystemSettingValue(name, value); return mSettingsRegistry .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name, value, getCallingPackage()); } case MUTATION_OPERATION_DELETE: { return mSettingsRegistry.deleteSettingLocked( SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name); } case MUTATION_OPERATION_UPDATE: { validateSystemSettingValue(name, value); return mSettingsRegistry .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name, value, getCallingPackage()); } } return false; } }

Target:
private boolean mutateSystemSetting(String name, String value, int runAsUserId, int operation) { if (!hasWriteSecureSettingsPermission()) { if (!Settings.checkAndNoteWriteSettingsOperation(getContext(), Binder.getCallingUid(), getCallingPackage(), true)) { return false; } } final int callingUserId = resolveCallingUserIdEnforcingPermissionsLocked(runAsUserId); enforceRestrictedSystemSettingsMutationForCallingPackage(operation, name, callingUserId); final int owningUserId = resolveOwningUserIdForSystemSettingLocked(callingUserId, name); if (owningUserId != callingUserId) { return false; } synchronized (mLock) { switch (operation) { case MUTATION_OPERATION_INSERT: { validateSystemSettingValue(name, value); return mSettingsRegistry .insertSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name, value, getCallingPackage()); } case MUTATION_OPERATION_DELETE: { return mSettingsRegistry.deleteSettingLocked( SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name); } case MUTATION_OPERATION_UPDATE: { validateSystemSettingValue(name, value); return mSettingsRegistry .updateSettingLocked(SettingsRegistry.SETTINGS_TYPE_SYSTEM, owningUserId, name, value, getCallingPackage()); } } return false; } }
Source:
protected BlobHelper() { }

Target:
private BlobHelper() { }
Source:
public static int decodeHexNibble(final char c) { final int index = c; assert index >= 0; if (index >= HEX2B.length) { return -1; } if (PlatformDependent.hasUnsafe()) { return PlatformDependent.getByte(HEX2B, index); } else { return HEX2B[index]; } }

Target:
public static int decodeHexNibble(final char c) { assert HEX2B.length == (Character.MAX_VALUE + 1); final int index = c; return HEX2B[index]; }
Source:
public Path(String pathString) throws IllegalArgumentException { checkPathArg( pathString ); if (hasWindowsDrive(pathString) && pathString.charAt(0) != '/') { pathString = "/" + pathString; } String scheme = null; String authority = null; int start = 0; int colon = pathString.indexOf(':'); int slash = pathString.indexOf('/'); if ((colon != -1) && (colon == (slash-1))) { scheme = pathString.substring(0, colon); start = colon+1; } if (pathString.startsWith(" (pathString.length()-start > 2)) { int nextSlash = pathString.indexOf('/', start+2); int authEnd = nextSlash > 0 ? nextSlash : pathString.length(); authority = pathString.substring(start+2, authEnd); start = authEnd; } String path = pathString.substring(start, pathString.length()); if (!WINDOWS && !path.isEmpty() && path.charAt(0) != '/') { path = "./" + path; } initialize(scheme, authority, path, null); }

Target:
public Path(String pathString) throws IllegalArgumentException { checkPathArg( pathString ); if (hasWindowsDrive(pathString) && pathString.charAt(0) != '/') { pathString = "/" + pathString; } String scheme = null; String authority = null; int start = 0; int colon = pathString.indexOf(':'); int slash = pathString.indexOf('/'); if ((colon > 0) && (colon == (slash-1))) { scheme = pathString.substring(0, colon); start = colon+1; } if (pathString.startsWith(" (pathString.length()-start > 2)) { int nextSlash = pathString.indexOf('/', start+2); int authEnd = nextSlash > 0 ? nextSlash : pathString.length(); authority = pathString.substring(start+2, authEnd); start = authEnd; } String path = pathString.substring(start, pathString.length()); if (!WINDOWS && !path.isEmpty() && path.charAt(0) != '/') { path = "./" + path; } initialize(scheme, authority, path, null); }
Source:
public Optional<Error> validate(EventEnvelope envelope) { checkNotNull(envelope); final Event event = envelope.getOuterObject(); Throwable result = null; final List<ConstraintViolation> violations = messageValidator.validate(event); if (!violations.isEmpty()) { final InvalidEventException invalidEvent = onConstraintViolations(event, violations); result = invalidArgumentWithCause(invalidEvent, invalidEvent.getError()); } if (result == null) { return Optional.absent(); } else { return Optional.of(toError(result)); } }

Target:
public Optional<MessageInvalid> validate(EventEnvelope envelope) { checkNotNull(envelope); final Event event = envelope.getOuterObject(); MessageInvalid result = null; final List<ConstraintViolation> violations = messageValidator.validate(event); if (!violations.isEmpty()) { result = onConstraintViolations(event, violations); } return Optional.fromNullable(result); }
Source:
public static void clearSelection(Grid grid, VControl vControl, EMFFormsDatabindingEMF dataBinding) { if (grid.getCellSelection().length == 0 || !vControl.isEnabled() || vControl.isReadonly()) { return; } for (final Point itemCoord : grid.getCellSelection()) { final int column = itemCoord.x; final int row = itemCoord.y; final VDomainModelReference dmr = (VDomainModelReference) grid.getColumn(column) .getData(AbstractTableViewerComposite.DMR); if (vControl instanceof VTableControl && org.eclipse.emf.ecp.view.internal.table.swt.TableConfigurationHelper .isReadOnly((VTableControl) vControl, dmr)) { continue; } final EObject eObject = (EObject) grid.getItem(row).getData(); try { final Setting setting = dataBinding.getSetting(dmr, eObject); setting.unset(); } catch (final DatabindingFailedException ex) { } } }

Target:
public static void clearSelection(Grid grid, VControl vControl, EMFFormsDatabindingEMF dataBinding) { if (grid.getCellSelection().length == 0 || !vControl.isEnabled() || vControl.isReadonly()) { return; } for (final Point itemCoord : grid.getCellSelection()) { final int column = itemCoord.x; final int row = itemCoord.y; final VDomainModelReference dmr = (VDomainModelReference) grid.getColumn(column) .getData(AbstractTableViewerComposite.DMR); if (dmr == null || vControl instanceof VTableControl && org.eclipse.emf.ecp.view.internal.table.swt.TableConfigurationHelper .isReadOnly((VTableControl) vControl, dmr)) { continue; } final EObject eObject = (EObject) grid.getItem(row).getData(); try { final Setting setting = dataBinding.getSetting(dmr, eObject); setting.unset(); } catch (final DatabindingFailedException ex) { } } }
Source:
private void setCloudEndabled(boolean isCloudEnabled) { _isCloudEnabled = isCloudEnabled; }

Target:
public void setCloudEndabled(boolean isCloudEnabled) { _isCloudEnabled = isCloudEnabled; }
Source:
private void logEndpoint(RntbdEndpoint endpoint) { int executorPoolSize = endpoint.executorTaskQueueMetrics(); if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } if (executorPoolSize > 5_000 || endpoint.requestQueueLength() > 5_000 || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels()) { if (this.logger.isWarnEnabled()) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } } }

Target:
private void logEndpoint(RntbdEndpoint endpoint) { if (this.logger.isWarnEnabled() && (endpoint.executorTaskQueueMetrics() > MAX_TASK_LIMIT || endpoint.requestQueueLength() > MAX_TASK_LIMIT || endpoint.gettingEstablishedConnectionsMetrics() > 0 || endpoint.channelsMetrics() > endpoint.maxChannels())) { logger.warn("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } else if (this.logger.isDebugEnabled()) { logger.debug("RntbdEndpoint Identifier {}, Stat {}", getPoolId(endpoint), getPoolStat(endpoint)); } }
Source:
public String verifiedSources(@ApiParam(value = "Workflow id", required = true) @PathParam("workflowId") Long workflowId) { Workflow workflow = workflowDAO.findById(workflowId); Helper.checkEntry(workflow); Set<String> verifiedSourcesArray = new HashSet<>(); for (WorkflowVersion workflowVersion : workflow.getWorkflowVersions()) { if (workflowVersion.isVerified()) { verifiedSourcesArray.add(workflowVersion.getVerifiedSource()); } } JSONArray jsonArray = new JSONArray(); try { jsonArray = new JSONArray(verifiedSourcesArray.toArray()); } catch (JSONException ex) { ex.printStackTrace(); } return jsonArray.toString(); }

Target:
public String verifiedSources(@ApiParam(value = "Workflow id", required = true) @PathParam("workflowId") Long workflowId) { Workflow workflow = workflowDAO.findById(workflowId); Helper.checkEntry(workflow); Set<String> verifiedSourcesArray = new HashSet<>(); workflow.getWorkflowVersions() .stream() .filter((WorkflowVersion u) -> u.isVerified()) .forEach((WorkflowVersion v) -> verifiedSourcesArray.add(v.getVerifiedSource())); JSONArray jsonArray; try { jsonArray = new JSONArray(verifiedSourcesArray.toArray()); } catch (JSONException ex) { throw new CustomWebApplicationException("There was an error converting the array of verified sources to a JSON array.", HttpStatus.SC_INTERNAL_SERVER_ERROR); } return jsonArray.toString(); }
Source:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); configuration.set("hadoop.security.authentication", "kerberos"); try { HadoopKerberosName.setConfiguration(configuration); } catch (IOException exception) { throw new UncheckedIOException(exception); } UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }

Target:
public static KerberosHadoopAuthentication createKerberosHadoopAuthentication(KerberosAuthentication kerberosAuthentication, HdfsConfigurationUpdater updater) { Configuration configuration = getInitialConfiguration(); updater.updateConfiguration(configuration); configuration.set("hadoop.security.authentication", "kerberos"); UserGroupInformation.setConfiguration(configuration); return new KerberosHadoopAuthentication(kerberosAuthentication); }
Source:
private void reportMetrics(final EventTypeMetrics eventTypeMetrics, final EventPublishResult result, final String eventsAsString, final int eventCount) { if (result.getStatus() == EventPublishingStatus.SUBMITTED) { eventTypeMetrics.reportSizing(eventCount, eventsAsString.getBytes(StandardCharsets.UTF_8).length - 2); } else if (result.getStatus() == EventPublishingStatus.FAILED && eventCount != 0) { final int successfulEvents= result.getResponses() .stream() .filter(r -> r.getPublishingStatus() == EventPublishingStatus.SUBMITTED) .collect(Collectors.toList()) .size(); final double avgEventSize = eventsAsString.getBytes(StandardCharsets.UTF_8).length / eventCount; eventTypeMetrics.reportSizing(successfulEvents,(int)Math.round(avgEventSize * successfulEvents)); } }

Target:
private void reportMetrics(final EventTypeMetrics eventTypeMetrics, final EventPublishResult result, final String eventsAsString, final int eventCount) { if (result.getStatus() == EventPublishingStatus.SUBMITTED) { eventTypeMetrics.reportSizing(eventCount, eventsAsString.getBytes(StandardCharsets.UTF_8).length - eventCount - 1); } else if (result.getStatus() == EventPublishingStatus.FAILED && eventCount != 0) { final int successfulEvents= result.getResponses() .stream() .filter(r -> r.getPublishingStatus() == EventPublishingStatus.SUBMITTED) .collect(Collectors.toList()) .size(); final double avgEventSize = eventsAsString.getBytes(StandardCharsets.UTF_8).length / (double)eventCount; eventTypeMetrics.reportSizing(successfulEvents, (int)Math.round(avgEventSize * successfulEvents)); } }
Source:
private void setLoginToSponsoredUser(PerunSession sess, User sponsoredUser, String loginAttributeName, String login) throws InternalErrorException { try { Attribute a = getPerunBl().getAttributesManagerBl().getAttribute(sess, sponsoredUser, loginAttributeName); a.setValue(login); getPerunBl().getAttributesManagerBl().setAttribute(sess,sponsoredUser,a); } catch (WrongAttributeAssignmentException | AttributeNotExistsException e) { log.error("attribute not defined",loginAttributeName); } catch (WrongAttributeValueException | WrongReferenceAttributeValueException e) { log.error("cannot set attribute for sponsored user {}",loginAttributeName,sponsoredUser.getId()); } }

Target:
private void setLoginToSponsoredUser(PerunSession sess, User sponsoredUser, String loginAttributeName, String login) throws InternalErrorException { try { Attribute a = getPerunBl().getAttributesManagerBl().getAttribute(sess, sponsoredUser, loginAttributeName); a.setValue(login); getPerunBl().getAttributesManagerBl().setAttribute(sess,sponsoredUser,a); } catch (WrongAttributeAssignmentException | AttributeNotExistsException |WrongAttributeValueException | WrongReferenceAttributeValueException e) { throw new InternalErrorException("cannot set attribute "+loginAttributeName+" for user "+sponsoredUser.getId(),e); } }
Source:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { Supplier<Map<String, Supplier<URI>>> endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_STORE, null); if (region.isEmpty()) { return getLastValueInMap(endpointsSupplier); } else { return getValueInMapOrNull(endpointsSupplier, region); } }

Target:
protected Supplier<URI> provideStorageUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion, @Named(LocationConstants.PROPERTY_REGION) String region) { return getUriSupplier(ServiceType.OBJECT_STORE, null, factory, region); }
Source:
private boolean isField(Tree tree) { return tree.is(Kind.VARIABLE) && !((VariableTree) tree).modifiers().modifiers().containsAll(Lists.newArrayList(Modifier.FINAL, Modifier.STATIC)); }

Target:
private boolean isField(Tree tree) { return tree.is(Kind.VARIABLE) && !((VariableTree) tree).modifiers().modifiers().contains(Modifier.STATIC); }
Source:
public static void setLanguage(Context ctx, OsmandSettings settings) throws IOException { String lang = getPreferredLanguage(settings).getLanguage(); m = new HashMap<String,String>(); InputStream is = null; BufferedReader br = null; try{ try { is = ctx.getAssets().open("specialphrases/specialphrases_"+lang+".txt"); } catch (IOException ex) { is = ctx.getAssets().open("specialphrases/specialphrases_en.txt"); } br = new BufferedReader(new InputStreamReader(is)); String readLine = null; while ((readLine = br.readLine()) != null) { String[] arr = readLine.split(","); if (arr != null && arr.length == 2) { m.put(arr[0], arr[1]); } } is.close(); br.close(); } finally { Algoritms.closeStream(is); Algoritms.closeStream(br); } }

Target:
public static void setLanguage(Context ctx, OsmandSettings settings) throws IOException { String lang = getPreferredLanguage(settings).getLanguage(); m = new HashMap<String,String>(); InputStream is = null; BufferedReader br = null; try{ try { is = ctx.getAssets().open("specialphrases/specialphrases_"+lang+".txt"); } catch (IOException ex) { is = ctx.getAssets().open("specialphrases/specialphrases_en.txt"); } br = new BufferedReader(new InputStreamReader(is)); String readLine = null; while ((readLine = br.readLine()) != null) { String[] arr = readLine.split(","); if (arr != null && arr.length == 2) { m.put(arr[0], arr[1]); } } } finally { Algoritms.closeStream(is); Algoritms.closeStream(br); } }
Source:
private static Object createGetter(Class<?> pojoClass, String getterExpr, String exprObjectPlaceholder, Class<?> exprClass, Class<?> getterClass) { logger.debug("{} {}", pojoClass, getterExpr, exprClass, getterClass); JavaExpressionParser javaExpressionParser = new JavaExpressionParser(); javaExpressionParser.setInputObjectPlaceholder("$", PojoUtils.OBJECT); String code = javaExpressionParser.convertToCompilableExpression(getterExpr, pojoClass, exprClass); return compileExpression(code, getterClass, new String[] {PojoUtils.OBJECT}); }

Target:
private static Object createGetter(Class<?> pojoClass, String getterExpr, String exprObjectPlaceholder, Class<?> exprClass, Class<?> getterClass) { logger.debug("{} {}", pojoClass, getterExpr, exprClass, getterClass); JavaExpressionParser javaExpressionParser = new JavaExpressionParser(); javaExpressionParser.setInputObjectPlaceholder(PojoUtils.DEFAULT_EXPRESSION_OBJ_PLACEHOLDER, PojoUtils.OBJECT); String code = javaExpressionParser.convertToCompilableExpression(getterExpr, pojoClass, exprClass); return compileExpression(code, getterClass, new String[] {PojoUtils.OBJECT}); }
Source:
public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { this.satisfiedRedundancyRegions = DataSerializer.readHashMap(in); this.underRedundancyRegions = DataSerializer.readHashMap(in); this.zeroRedundancyRegions = DataSerializer.readHashMap(in); this.totalPrimaryTransfersCompleted = in.readInt(); this.totalPrimaryTransferTime = DataSerializer.readObject(in); this.success = DataSerializer.readBoolean(in); this.statusMessage = DataSerializer.readString(in); }

Target:
public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { satisfiedRedundancyRegions = DataSerializer.readHashMap(in); underRedundancyRegions = DataSerializer.readHashMap(in); zeroRedundancyRegions = DataSerializer.readHashMap(in); totalPrimaryTransfersCompleted = in.readInt(); totalPrimaryTransferTime = DataSerializer.readObject(in); success = DataSerializer.readBoolean(in); statusMessage = DataSerializer.readString(in); }
Source:
public String get() { if (SystemInfo.isWindows()) { return System.getProperty("user.home") + "\\AppData\\Local\\che\\ext-conf"; } else { final String localConfDir = System.getenv(CheBootstrap.CHE_LOCAL_CONF_DIR); return localConfDir == null ? "" : localConfDir + File.separator + "ext" + ":" + EXT_CHE_LOCAL_CONF_DIR + ":ro"; } }

Target:
public String get() { if (SystemInfo.isWindows()) { return System.getProperty("user.home") + "\\AppData\\Local\\che\\ext-conf"; } else { final String localConfDir = System.getenv(CheBootstrap.CHE_LOCAL_CONF_DIR); return localConfDir == null ? "" : localConfDir + File.separator + "ext:" + EXT_CHE_LOCAL_CONF_DIR + ":ro"; } }
Source:
public List<ProgramState> setConstraint(ProgramState programState, BooleanConstraint booleanConstraint) { ObjectConstraint optionalConstraint = (ObjectConstraint) programState.getConstraint(optionalSV); if (optionalConstraint == null) { return ImmutableList.of(); } boolean isknownAsNotPresent = optionalConstraint.hasStatus(Status.NOT_PRESENT); boolean isKnownAsPresent = optionalConstraint.hasStatus(Status.PRESENT); if (isknownAsNotPresent || isKnownAsPresent) { if (isImpossibleState(booleanConstraint, isknownAsNotPresent, isKnownAsPresent)) { return ImmutableList.of(); } return ImmutableList.of(programState); } ObjectConstraint newConstraint = booleanConstraint.isTrue() ? optionalConstraint.withStatus(Status.PRESENT) : optionalConstraint.withStatus(Status.NOT_PRESENT); return ImmutableList.of(programState.addConstraint(optionalSV, newConstraint)); }

Target:
public List<ProgramState> setConstraint(ProgramState programState, BooleanConstraint booleanConstraint) { ObjectConstraint optionalConstraint = (ObjectConstraint) programState.getConstraint(optionalSV); if (optionalConstraint == null || isImpossibleState(booleanConstraint, optionalConstraint)) { return ImmutableList.of(); } if (optionalConstraint.hasStatus(Status.NOT_PRESENT) || optionalConstraint.hasStatus(Status.PRESENT)) { return ImmutableList.of(programState); } ObjectConstraint newConstraint = booleanConstraint.isTrue() ? optionalConstraint.withStatus(Status.PRESENT) : optionalConstraint.withStatus(Status.NOT_PRESENT); return ImmutableList.of(programState.addConstraint(optionalSV, newConstraint)); }
Source:
private String addFolderPath(String param) { if (param == null) return null; String[] keys = param.split(";"); StringBuilder stringBuilder = new StringBuilder(param.length() + PGP_FOLDER.length() * keys.length); for(int i = 0; i < keys.length; i++) { stringBuilder .append(PGP_FOLDER) .append(keys[i]) .append(i != keys.length - 1 ? ";" : ""); } return stringBuilder.toString(); }

Target:
private String addFolderPath(String param) { if (param == null) return null; StringTokenizer keys = new StringTokenizer(param, ";"); StringBuilder stringBuilder = new StringBuilder(); while (keys.hasMoreTokens()) { String key = keys.nextToken(); stringBuilder .append(PGP_FOLDER) .append(key) .append(keys.hasMoreElements() ? ";" : ""); } return stringBuilder.toString(); }
Source:
public String get(String key) { Map<String, String> Map = inheritableThreadLocal.get(); if ((Map != null) && (key != null)) { return Map.get(key); } else { return null; } }

Target:
public String get(String key) { Map<String, String> map = inheritableThreadLocal.get(); if ((map != null) && (key != null)) { return map.get(key); } else { return null; } }
Source:
public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (enabled != null ? enabled.hashCode() : 0); result = 31 * result + (triggerPackages != null ? triggerPackages.hashCode() : 0); result = 31 * result + (pollInterval != null ? pollInterval.hashCode() : 0); return result; }

Target:
public int hashCode() { return Objects.hash(key, enabled, pollInterval, triggerPackages); }
Source:
public boolean isBonus() { return ((RaidAccessor) this.raid).accessor$hasBonusWave(); }

Target:
public boolean isBonus() { if (this.isFinal() || this.waveId < ((RaidAccessor) this.raid).accessor$getNumGroups()) { return false; } return true; }
Source:
private void updateWatchlistBox() { final LinearLayout layout = ButterKnife.findById(view, R.id.watchlist_box); final boolean supportsWatchList = cache.supportsWatchList(); layout.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE); if (!supportsWatchList) { return; } final Button buttonAdd = ButterKnife.findById(view, R.id.add_to_watchlist); final Button buttonRemove = ButterKnife.findById(view, R.id.remove_from_watchlist); final TextView text = ButterKnife.findById(view, R.id.watchlist_text); final int watchListCount = cache.getWatchlistCount(); String watchListCountString = ""; if (watchListCount != -1) { watchListCountString = " (" + watchListCount + ' ' + getString(R.string.cache_watchlist_in_total) + ')'; } if (cache.isOnWatchlist() || cache.isOwner()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(res.getString(R.string.cache_watchlist_on) + watchListCountString); } else { buttonAdd.setVisibility(View.VISIBLE); buttonRemove.setVisibility(View.GONE); text.setText(res.getString(R.string.cache_watchlist_not_on) + watchListCountString); } if (cache.isOwner()) { buttonAdd.setEnabled(false); buttonAdd.setVisibility(View.GONE); buttonRemove.setEnabled(false); buttonRemove.setVisibility(View.GONE); } }

Target:
private void updateWatchlistBox() { final LinearLayout layout = ButterKnife.findById(view, R.id.watchlist_box); final boolean supportsWatchList = cache.supportsWatchList(); layout.setVisibility(supportsWatchList ? View.VISIBLE : View.GONE); if (!supportsWatchList) { return; } final Button buttonAdd = ButterKnife.findById(view, R.id.add_to_watchlist); final Button buttonRemove = ButterKnife.findById(view, R.id.remove_from_watchlist); final TextView text = ButterKnife.findById(view, R.id.watchlist_text); final int watchListCount = cache.getWatchlistCount(); final String watchListCountString = watchListCount != -1 ? '(' + getString(R.string.cache_watchlist_count, watchListCount) + ')' : ""; if (cache.isOnWatchlist() || cache.isOwner()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(res.getString(R.string.cache_watchlist_on, watchListCountString)); } else { buttonAdd.setVisibility(View.VISIBLE); buttonRemove.setVisibility(View.GONE); text.setText(res.getString(R.string.cache_watchlist_not_on, watchListCountString)); } if (cache.isOwner()) { buttonAdd.setEnabled(false); buttonAdd.setVisibility(View.GONE); buttonRemove.setEnabled(false); buttonRemove.setVisibility(View.GONE); } }
Source:
public void testBareCloneRepositoryMirror() throws Exception { File directory = createTempDirectory( "testCloneRepositoryWithBranch_bare"); CloneCommand command = Git.cloneRepository(); command.setBranch("refs/heads/master"); command.setMirror(true); command.setDirectory(directory); command.setURI(fileUri()); Git git2 = command.call(); addRepoToClose(git2.getRepository()); assertNotNull(git2); assertNotNull(git2.getRepository().resolve("tag-for-blob")); assertNotNull(git2.getRepository().resolve("tag-initial")); assertEquals(git2.getRepository().getFullBranch(), "refs/heads/master"); assertEquals("refs/heads/master, refs/heads/test", allRefNames( git2.branchList().setListMode(ListMode.ALL).call())); assertNotNull(git2.getRepository().exactRef("refs/meta/foo/bar")); RemoteConfig cfg = new RemoteConfig(git2.getRepository().getConfig(), Constants.DEFAULT_REMOTE_NAME); List<RefSpec> specs = cfg.getFetchRefSpecs(); assertEquals(1, specs.size()); assertEquals(new RefSpec("+refs/*:refs/*"), specs.get(0)); }

Target:
public void testBareCloneRepositoryMirror() throws Exception { File directory = createTempDirectory( "testCloneRepositoryWithBranch_mirror"); CloneCommand command = Git.cloneRepository(); command.setBranch("refs/heads/master"); command.setMirror(true); command.setDirectory(directory); command.setURI(fileUri()); Git git2 = command.call(); addRepoToClose(git2.getRepository()); assertNotNull(git2); assertNotNull(git2.getRepository().resolve("tag-for-blob")); assertNotNull(git2.getRepository().resolve("tag-initial")); assertEquals(git2.getRepository().getFullBranch(), "refs/heads/master"); assertEquals("refs/heads/master, refs/heads/test", allRefNames( git2.branchList().setListMode(ListMode.ALL).call())); assertNotNull(git2.getRepository().exactRef("refs/meta/foo/bar")); RemoteConfig cfg = new RemoteConfig(git2.getRepository().getConfig(), Constants.DEFAULT_REMOTE_NAME); List<RefSpec> specs = cfg.getFetchRefSpecs(); assertEquals(1, specs.size()); assertEquals(new RefSpec("+refs/*:refs/*"), specs.get(0)); }