auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void requestEmailSignInTwiceReturnsSameToken() { doReturn("something").when(cacheProvider).getString(CACHE_KEY); doReturn(account).when(accountDao).getAccount(any()); service.requestEmailSignIn(SIGN_IN_REQUEST_WITH_EMAIL); verify(cacheProvider, never()).setString(any(), any(), anyInt()); verify(sendMailService).sendEmail(any()); }

Target:
public void requestEmailSignInTwiceReturnsSameToken() throws Exception { doReturn("something").when(cacheProvider).getString(CACHE_KEY); doReturn(account).when(accountDao).getAccount(any()); service.requestEmailSignIn(SIGN_IN_REQUEST_WITH_EMAIL); verify(cacheProvider, never()).setString(any(), any(), anyInt()); verify(sendMailService).sendEmail(providerCaptor.capture()); MimeTypeEmailProvider provider = providerCaptor.getValue(); assertEquals(RECIPIENT_EMAIL, provider.getMimeTypeEmail().getRecipientAddresses().get(0)); assertEquals(SUPPORT_EMAIL, provider.getPlainSenderEmail()); String bodyString = (String)provider.getMimeTypeEmail().getMessageParts().get(0).getContent(); assertEquals("something", bodyString); }
Source:
public void saveEncounter_shouldUpdateExistingEncounterWhenAChildObsIsEdited() throws Exception { executeDataSet(ENC_OBS_HIERARCHY_DATA_XML); EncounterService es = Context.getEncounterService(); ObsService os = Context.getObsService(); Encounter enc = es.getEncounter(100); Obs o = os.getObs(101); o.setValueText("Obs value updated"); es.saveEncounter(enc); Context.evictFromSession(enc); Context.flushSession(); enc = es.getEncounter(100); Set<Obs> obsAtTopLevelUpdated = enc.getObsAtTopLevel(true); Obs oParent = os.getObs(100); final Obs editedObs = os.getObs(101); Obs o2 = os.getObs(102); Obs o3 = getNewVersionOfEditedObs(oParent,editedObs); assertEquals(1,obsAtTopLevelUpdated.size()); assertEquals(3, oParent.getGroupMembers(true).size()); assertTrue(editedObs.getVoided()); assertFalse(oParent.getVoided()); assertFalse(o2.getVoided()); assertNotNull(o3); assertFalse(o3.getVoided()); assertEquals("Obs value updated", o3.getValueText()); }

Target:
public void saveEncounter_shouldUpdateExistingEncounterWhenAChildObsIsEdited() throws Exception { executeDataSet(ENC_OBS_HIERARCHY_DATA_XML); EncounterService es = Context.getEncounterService(); ObsService os = Context.getObsService(); Encounter enc = es.getEncounter(100); Obs o = os.getObs(101); o.setValueText("Obs value updated"); es.saveEncounter(enc); Context.flushSession(); Context.clearSession(); enc = es.getEncounter(100); Set<Obs> obsAtTopLevelUpdated = enc.getObsAtTopLevel(true); Obs oParent = os.getObs(100); final Obs editedObs = os.getObs(101); Obs o2 = os.getObs(102); Obs o3 = getNewVersionOfEditedObs(oParent,editedObs); assertEquals(1,obsAtTopLevelUpdated.size()); assertEquals(3, oParent.getGroupMembers(true).size()); assertTrue(editedObs.getVoided()); assertFalse(oParent.getVoided()); assertFalse(o2.getVoided()); assertNotNull(o3); assertFalse(o3.getVoided()); assertEquals("Obs value updated", o3.getValueText()); }
Source:
public void updateBodySetInvalidAttachments() throws Exception { MutableDocumentRevision update = saved.mutableCopy(); update.body = bodyTwo; String attachmentName = "doesnt_exist_attachment"; File f = TestUtils.loadFixture("fixture/"+ attachmentName); Attachment att = new UnsavedFileAttachment(f, "text/plain"); update.attachments.put(attachmentName, att); BasicDocumentRevision updated = null; try { updated = datastore.updateDocumentFromRevision(update); Assert.fail("Expected AttachmentException; not thrown"); } catch (AttachmentException ioe) { ; } Assert.assertNull("Updated DocumentRevision is not null", updated); BasicDocumentRevision retrieved = this.datastore.getDocument(saved.getId()); Assert.assertEquals("Document should not be updated", retrieved.getRevision(), saved.getRevision()); Assert.assertEquals("Revision should have 0 attachments", 0, retrieved.getAttachments().size()); }

Target:
public void updateBodySetInvalidAttachments() throws Exception { MutableDocumentRevision update = saved.mutableCopy(); update.body = bodyTwo; String attachmentName = "doesnt_exist_attachment"; File f = TestUtils.loadFixture("fixture/"+ attachmentName); Attachment att = new UnsavedFileAttachment(f, "text/plain"); update.attachments.put(attachmentName, att); BasicDocumentRevision updated = null; try { updated = datastore.updateDocumentFromRevision(update); Assert.fail("Expected AttachmentException; not thrown"); } catch (AttachmentException e) { ; } Assert.assertNull("Updated DocumentRevision is not null", updated); BasicDocumentRevision retrieved = this.datastore.getDocument(saved.getId()); Assert.assertEquals("Document should not be updated", retrieved.getRevision(), saved.getRevision()); Assert.assertEquals("Revision should have 0 attachments", 0, retrieved.getAttachments().size()); }
Source:
private void glusterPeerProbe(Guid upServerId, String newServerName) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(upServerId, newServerName)); setSucceeded(returnValue.getSucceeded()); if (!getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(upServerId), AuditLogType.GLUSTER_HOST_ADD_FAILED); return; } }

Target:
private void glusterPeerProbe(Guid upServerId, String newServerName) { VDSReturnValue returnValue = runVdsCommand( VDSCommandType.GlusterHostAdd, new GlusterHostAddVDSParameters(upServerId, newServerName)); if (!returnValue.getSucceeded()) { getReturnValue().getFault().setError(returnValue.getVdsError().getCode()); getReturnValue().getFault().setMessage(returnValue.getVdsError().getMessage()); AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.GLUSTER_HOST_ADD_FAILED); return; } }
Source:
public GetFirmwareVersionAsyncResponse getFirmwareVersion( @OrganisationIdentification final String organisationIdentification, @RequestPayload final GetFirmwareVersionRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime) throws OsgpException { LOGGER.info("GetFirmwareVersion Request received from organisation for device {}.", organisationIdentification, request.getDeviceIdentification()); final GetFirmwareVersionAsyncResponse response = new com.alliander.osgp.adapter.ws.schema.smartmetering.configuration.ObjectFactory() .createGetFirmwareVersionAsyncResponse(); try { final String correlationUid = this.configurationService.enqueueGetFirmwareRequest( organisationIdentification, request.getDeviceIdentification(), MessagePriorityEnum.getMessagePriority(messagePriority), this.configurationMapper.map(scheduleTime, Long.class)); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(request.getDeviceIdentification()); } catch (final MethodConstraintViolationException e) { LOGGER.error("exception", e); throw new FunctionalException(FunctionalExceptionType.VALIDATION_ERROR, ComponentType.WS_CORE, new ValidationException(e.getConstraintViolations())); } catch (final Exception e) { this.handleException(e); } return response; }

Target:
public GetFirmwareVersionAsyncResponse getFirmwareVersion( @OrganisationIdentification final String organisationIdentification, @RequestPayload final GetFirmwareVersionRequest request, @MessagePriority final String messagePriority, @ScheduleTime final String scheduleTime) throws OsgpException { LOGGER.info("GetFirmwareVersion Request received from organisation for device {}.", organisationIdentification, request.getDeviceIdentification()); final GetFirmwareVersionAsyncResponse response = new com.alliander.osgp.adapter.ws.schema.smartmetering.configuration.ObjectFactory() .createGetFirmwareVersionAsyncResponse(); try { final String correlationUid = this.configurationService.enqueueGetFirmwareRequest( organisationIdentification, request.getDeviceIdentification(), MessagePriorityEnum.getMessagePriority(messagePriority), this.configurationMapper.map(scheduleTime, Long.class)); response.setCorrelationUid(correlationUid); response.setDeviceIdentification(request.getDeviceIdentification()); } catch (final Exception e) { this.handleException(e); } return response; }
Source:
public void sendSmallEventsFullBatchPartitionKey() { final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider, new TracerProvider(Collections.emptyList()), null, null); int count = 0; while (batch.tryAdd(createData())) { if (count % 100 == 0) { logger.verbose("Batch size: {}", batch.getCount()); } count++; } StepVerifier.create(producer.send(batch.getEvents())) .verifyComplete(); }

Target:
public void sendSmallEventsFullBatchPartitionKey() { final EventDataBatch batch = new EventDataBatch(ClientConstants.MAX_MESSAGE_LENGTH_BYTES, null, PARTITION_KEY, contextProvider, new TracerProvider(Collections.emptyList()), getFullyQualifiedDomainName(), getEventHubName()); int count = 0; while (batch.tryAdd(createData())) { if (count % 100 == 0) { logger.verbose("Batch size: {}", batch.getCount()); } count++; } StepVerifier.create(producer.send(batch.getEvents())) .verifyComplete(); }
Source:
public void shouldPublishUsingOkHttpClientUsingSSL() { SSLContextSupplier sslSupplier = getSslContextSupplier(); HermesClient client = hermesClient(new OkHttpSender(sslSupplier.get())).withURI(topicURI_SSL).build(); runTestSuiteForHermesClient(client); }

Target:
public void shouldPublishUsingOkHttpClientUsingSSL() { HermesClient client = hermesClient(new OkHttpHermesSender(getOkHttpClientWithSslContextConfigured())).withURI(sslTopicUri).build(); runTestSuiteForHermesClient(client); }
Source:
private Map<Class<?>, Integer> getGlobalAlternativeMap() { if (cachedAlternativeMap == null || dirty) { Map<Class<?>, Integer> map = new HashMap<Class<?>, Integer>(); for (ListIterator<Item> iterator = alternatives.listIterator(); iterator.hasNext(); ) { Item item = iterator.next(); map.put(item.getJavaClass(), item.getPriority()); } cachedAlternativeMap = ImmutableMap.copyOf(map); } return cachedAlternativeMap; }

Target:
private Map<Class<?>, Integer> getGlobalAlternativeMap() { if (cachedAlternativeMap == null || dirty) { Map<Class<?>, Integer> map = new HashMap<Class<?>, Integer>(); for (Item item : alternatives) { map.put(item.getJavaClass(), item.getPriority()); } cachedAlternativeMap = ImmutableMap.copyOf(map); } return cachedAlternativeMap; }
Source:
public void put(ResourceRecordSet<?> rrset) { checkNotNull(rrset, "rrset was null"); checkArgument(!rrset.records().isEmpty(), "rrset was empty %s", rrset); List<Map<String, Object>> recordsLeftToCreate = new ArrayList<Map<String, Object>>(rrset.records()); for (Record record : api.recordsByNameAndType(domainId, rrset.name(), rrset.type())) { Map<String, Object> rdata = toRDataMap(record); if (recordsLeftToCreate.contains(rdata)) { recordsLeftToCreate.remove(rdata); if (rrset.ttl() != null) { if (rrset.ttl().equals(record.ttl)) { continue; } awaitComplete(api.updateRecord(domainId, record.id, rrset.ttl(), record.getData())); } } else { awaitComplete(api.deleteRecord(domainId, record.id)); } } int ttlToApply = rrset.ttl() != null ? rrset.ttl() : DEFAULT_TTL; for (Map<String, Object> rdata : recordsLeftToCreate) { Map<String, Object> mutableRData = new LinkedHashMap<String, Object>(rdata); Integer priority = getPriority(mutableRData); String data = join(' ', mutableRData.values().toArray()); if (priority == null) { awaitComplete(api.createRecord(domainId, rrset.name(), rrset.type(), ttlToApply, data)); } else { awaitComplete(api.createRecordWithPriority( domainId, rrset.name(), rrset.type(), ttlToApply, data, priority)); } } }

Target:
public void put(ResourceRecordSet<?> rrset) { checkNotNull(rrset, "rrset was null"); checkArgument(!rrset.records().isEmpty(), "rrset was empty %s", rrset); List<Map<String, Object>> recordsLeftToCreate = new ArrayList<Map<String, Object>>(rrset.records()); for (Record record : api.recordsByNameAndType(domainId, rrset.name(), rrset.type())) { Map<String, Object> rdata = toRDataMap(record); if (recordsLeftToCreate.contains(rdata)) { recordsLeftToCreate.remove(rdata); if (rrset.ttl() != null) { if (Util.equal(rrset.ttl(), record.ttl)) { continue; } awaitComplete(api.updateRecord(domainId, record.id, rrset.ttl(), record.data())); } } else { awaitComplete(api.deleteRecord(domainId, record.id)); } } int ttlToApply = rrset.ttl() != null ? rrset.ttl() : DEFAULT_TTL; for (Map<String, Object> rdata : recordsLeftToCreate) { Map<String, Object> mutableRData = new LinkedHashMap<String, Object>(rdata); Integer priority = getPriority(mutableRData); String data = join(' ', mutableRData.values().toArray()); if (priority == null) { awaitComplete(api.createRecord(domainId, rrset.name(), rrset.type(), ttlToApply, data)); } else { awaitComplete(api.createRecordWithPriority( domainId, rrset.name(), rrset.type(), ttlToApply, data, priority)); } } }
Source:
public MapValue<Statistic, Long> statistics() { return new SpongeMapValue<Statistic, Long>(Keys.STATISTICS, Maps.<Statistic, Long>newLinkedHashMap(), getValue()); }

Target:
public MapValue<Statistic, Long> statistics() { return new SpongeMapValue<>(Keys.STATISTICS, Maps.newLinkedHashMap(), getValue()); }
Source:
protected abstract UUID sendRequest(ManagementClient client) throws TimeoutException; protected Optional<ManagementClient> getOrchestrator() { runtime.invalidateLayout(); Layout layout = new Layout(runtime.getLayoutView().getLayout()); List<String> availableLayoutServers = layout.getLayoutServers().stream() .filter(s -> !s.equals(nodeForWorkflow)) .collect(Collectors.toList()); if (availableLayoutServers.isEmpty()) { throw new WorkflowException("getOrchestrator: no available orchestrators " + layout); } Optional<ManagementClient> managementClient = Optional.empty(); for (String endpoint : availableLayoutServers) { BaseClient client = runtime.getLayoutView().getRuntimeLayout(layout) .getBaseClient(endpoint); if (client.pingSync()) { log.info("getOrchestrator: orchestrator selected {}, layout {}", endpoint, layout); managementClient = Optional.of(runtime.getLayoutView().getRuntimeLayout(layout) .getManagementClient(endpoint)); } } return managementClient; }

Target:
protected abstract UUID sendRequest(ManagementClient client) throws TimeoutException; protected Optional<ManagementClient> getOrchestrator() { runtime.invalidateLayout(); Layout layout = new Layout(runtime.getLayoutView().getLayout()); List<String> availableLayoutServers = layout.getLayoutServers().stream() .filter(s -> !s.equals(nodeForWorkflow)) .collect(Collectors.toList()); if (availableLayoutServers.isEmpty()) { throw new WorkflowException("getOrchestrator: no available orchestrators " + layout); } Optional<ManagementClient> managementClient = Optional.empty(); for (String endpoint : availableLayoutServers) { BaseClient client = runtime.getLayoutView().getRuntimeLayout(layout) .getBaseClient(endpoint); if (client.pingSync()) { log.info("getOrchestrator: orchestrator selected {}, layout {}", endpoint, layout); managementClient = Optional.of(runtime.getLayoutView().getRuntimeLayout(layout) .getManagementClient(endpoint)); break; } } return managementClient; }
Source:
public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { config.setTopologyChangeAware(true); final Client client = ClientFactory.createClient(config); for (String server : servers) { try { client.createConnection(server.trim(), port); } catch (IOException e) { } } if (client.getConnectedHostList().isEmpty()) { throw new Exception("Unable to connect to any servers"); } return client; }

Target:
public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { config.setTopologyChangeAware(true); final Client client = ClientFactory.createClient(config); for (String server : servers) { try { client.createConnection(server.trim(), port); } catch (IOException e) { } } if (client.getConnectedHostList().isEmpty()) { try { client.close(); } catch (Exception ignore) throw new Exception("Unable to connect to any servers"); } return client; }
Source:
public int getLatestPacketFailRate() { int failure = 0; int sent = 0; int received = 0; int size = mTcpStats.size(); for (int i = 0; i < size; i++) { final long key = mTcpStats.keyAt(i); failure += (mTcpStats.get(key).lostCount + mTcpStats.get(key).retransmitCount); sent += mTcpStats.get(key).sentCount; received += mTcpStats.get(key).receivedCount; } updateSentSinceLastRecv(sent, received); if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; final int rate = ((sent != 0) ? (failure * 100 / sent) : 0); log("getLatestPacketFailRate:" + rate); return rate; }

Target:
public int getLatestPacketFailRate() { if (!mDependencies.isTcpInfoParsingSupported()) return 0; if (getSentSinceLastRecv() < getMinPacketsThreshold()) return 0; return mLatestPacketFailRate; }
Source:
public SQLExecEnvironment withModel(String model) { if (model == null) { return this; } Connection connection = null; try { Properties p = new Properties(); p.put("model", "inline:" + model); connection = DriverManager.getConnection("jdbc:calcite:", p); CalciteConnection conn = connection.unwrap(CalciteConnection.class); this.schema = conn.getRootSchema().getSubSchema(connection.getSchema()); } catch (SQLException e) { throw new RuntimeException(e); } finally { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } return this; }

Target:
public SQLExecEnvironment withModel(String model) { if (model == null) { return this; } Properties p = new Properties(); p.put("model", "inline:" + model); try (Connection connection = DriverManager.getConnection("jdbc:calcite:", p)) { CalciteConnection conn = connection.unwrap(CalciteConnection.class); this.schema = conn.getRootSchema().getSubSchema(connection.getSchema()); } catch (SQLException e) { throw new RuntimeException(e); } return this; }
Source:
public TypedSet(Type elementType, BlockBuilder blockBuilder, int expectedSize, String functionName) { checkArgument(expectedSize >= 0, "expectedSize must not be negative"); this.elementType = requireNonNull(elementType, "elementType must not be null"); this.elementBlock = requireNonNull(blockBuilder, "blockBuilder must not be null"); this.functionName = functionName; initialElementBlockOffset = elementBlock.getPositionCount(); initialElementBlockSizeInBytes = elementBlock.getSizeInBytes(); hashCapacity = arraySize(expectedSize, FILL_RATIO); this.maxFill = calculateMaxFill(hashCapacity); this.hashMask = hashCapacity - 1; blockPositionByHash = new IntArrayList(hashCapacity); blockPositionByHash.size(hashCapacity); for (int i = 0; i < hashCapacity; i++) { blockPositionByHash.set(i, EMPTY_SLOT); } this.containsNullElement = false; }

Target:
public TypedSet(Type elementType, BlockBuilder blockBuilder, int expectedSize, String functionName) { checkArgument(expectedSize >= 0, "expectedSize must not be negative"); this.elementType = requireNonNull(elementType, "elementType must not be null"); this.elementBlock = requireNonNull(blockBuilder, "blockBuilder must not be null"); this.functionName = functionName; initialElementBlockOffset = elementBlock.getPositionCount(); initialElementBlockSizeInBytes = elementBlock.getSizeInBytes(); this.size = 0; this.hashCapacity = arraySize(expectedSize, FILL_RATIO); this.maxFill = calculateMaxFill(hashCapacity); this.hashMask = hashCapacity - 1; blockPositionByHash = new IntArrayList(hashCapacity); blockPositionByHash.size(hashCapacity); for (int i = 0; i < hashCapacity; i++) { blockPositionByHash.set(i, EMPTY_SLOT); } this.containsNullElement = false; }
Source:
protected String getPagePhrase(SyntaxContainer syntax, String pageNumber) { String result = ""; if (syntax.getMaxCount() < Integer.MAX_VALUE) { Integer page = IntegerCompat.tryParse(pageNumber); if (page == null) { page = 1; } PagingType pagingType = getPagingType(); if (pagingType != null) { String pagingSyntax = Config.<String> getValue(ConfigValues.DBPagingSyntax); switch (pagingType) { case Range: result = StringFormat.format(pagingSyntax, (page - 1) * syntax.getMaxCount() + 1, page * syntax.getMaxCount()); break; case Offset: result = StringFormat.format(pagingSyntax, (page - 1) * syntax.getMaxCount() + 1, syntax.getMaxCount()); break; } } } return result; }

Target:
protected String getPagePhrase(SyntaxContainer syntax, String pageNumber) { String result = ""; Integer page = IntegerCompat.tryParse(pageNumber); if (page == null) { page = 1; } PagingType pagingType = getPagingType(); if (pagingType != null) { String pagingSyntax = Config.<String> getValue(ConfigValues.DBPagingSyntax); switch (pagingType) { case Range: result = StringFormat.format(pagingSyntax, BigInteger.valueOf((page - 1) * syntax.getMaxCount() + 1), BigInteger.valueOf(page * syntax.getMaxCount())); break; case Offset: result = StringFormat.format(pagingSyntax, BigInteger.valueOf((page - 1) * syntax.getMaxCount() + 1), syntax.getMaxCount()); break; } } return result; }
Source:
private void reserveSeat(Seat seat, Long ticketId) { if (ticketId != null) { seatRepository.findByTicketId(ticketId).ifPresent(previousSeat -> previousSeat.setTicket(null)); Ticket ticket = ticketRepository.findOne(ticketId); if (!ticket.isValid()) { throw new InvalidTicketException("Unable to reserve seat for an invalid Ticket"); } if (seat.getTicket() != null && seat.getTicket().getOwner() != null) { mailService.sendSeatOverrideMail(seat.getTicket().getOwner()); } seat.setTicket(ticket); } else { seat.setTicket(null); } seat.setTaken(true); seatRepository.saveAndFlush(seat); }

Target:
private void reserveSeat(Seat seat, Long ticketId) { if (ticketId != null) { seatRepository.findByTicketId(ticketId).ifPresent(previousSeat -> previousSeat.setTicket(null)); Ticket ticket = ticketService.getTicketById(ticketId); if (!ticket.isValid()) { throw new InvalidTicketException("Unable to reserve seat for an invalid Ticket"); } if (seat.getTicket() != null && seat.getTicket().getOwner() != null) { mailService.sendSeatOverrideMail(seat.getTicket().getOwner()); } seat.setTicket(ticket); } else { seat.setTicket(null); } seat.setTaken(true); seatRepository.saveAndFlush(seat); }
Source:
public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); transaction = new TransactionConfigurationBuilder(this); }

Target:
public ConfigurationBuilder() { this.classLoader = new WeakReference<>(Thread.currentThread().getContextClassLoader()); this.connectionPool = new ConnectionPoolConfigurationBuilder(this); this.asyncExecutorFactory = new ExecutorFactoryConfigurationBuilder(this); this.security = new SecurityConfigurationBuilder(this); this.nearCache = new NearCacheConfigurationBuilder(this); this.transaction = new TransactionConfigurationBuilder(this); }
Source:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("Function[%s] needs 3 arguments", name()); } String base = NullHandling.nullToEmptyIfNeeded(args.get(0).eval(bindings).asString()); int len = args.get(1).eval(bindings).asInt(); String pad = NullHandling.nullToEmptyIfNeeded(args.get(2).eval(bindings).asString()); if (base == null || pad == null) { return ExprEval.of(null); } else { return ExprEval.of(len == 0 ? NullHandling.defaultStringValue() : StringUtils.lpad(base, len, pad)); } }

Target:
public ExprEval apply(List<Expr> args, Expr.ObjectBinding bindings) { if (args.size() != 3) { throw new IAE("Function[%s] needs 3 arguments", name()); } String base = args.get(0).eval(bindings).asString(); int len = args.get(1).eval(bindings).asInt(); String pad = args.get(2).eval(bindings).asString(); if (base == null || pad == null) { return ExprEval.of(null); } else { return ExprEval.of(len == 0 ? NullHandling.defaultStringValue() : StringUtils.lpad(base, len, pad)); } }
Source:
private void open() { try { pin.open(); } catch (KuraGPIODeviceException | KuraUnavailableDeviceException | IOException e) { logger.error("Exception GPIOService ", e); } }

Target:
private void open() { try { pin.open(); } catch (KuraGPIODeviceException | KuraUnavailableDeviceException | IOException e) { logger.error("Open Exception ", e); } }
Source:
public CacheResource parse(ConfigResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(); } if (!user.getCapabilities().canViewCaches()) { throw new AuthException("not allowed to view caches"); } String cacheName = id.get(); String pluginName = "gerrit"; int i = cacheName.indexOf('.'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Provider<Cache<?, ?>> cacheProvider = cacheMap.byPlugin(pluginName).get(cacheName); if (cacheProvider == null) { throw new ResourceNotFoundException(id); } return new CacheResource(pluginName, cacheName, cacheProvider); }

Target:
public CacheResource parse(ConfigResource parent, IdString id) throws AuthException, ResourceNotFoundException { final CurrentUser user = self.get(); if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if(!(user.isIdentifiedUser())) { throw new ResourceNotFoundException(); } if (!user.getCapabilities().canViewCaches()) { throw new AuthException("not allowed to view caches"); } String cacheName = id.get(); String pluginName = "gerrit"; int i = cacheName.indexOf('-'); if (i != -1) { pluginName = cacheName.substring(0, i); cacheName = cacheName.length() > i + 1 ? cacheName.substring(i + 1) : ""; } Provider<Cache<?, ?>> cacheProvider = cacheMap.byPlugin(pluginName).get(cacheName); if (cacheProvider == null) { throw new ResourceNotFoundException(id); } return new CacheResource(pluginName, cacheName, cacheProvider); }
Source:
protected void activate(ComponentContext ctxt) { TOTPManagerImpl totpService = new TOTPManagerImpl(); Hashtable<String, String> props = new Hashtable<String, String>(); ctxt.getBundleContext().registerService(TOTPManager.class.getName(), totpService, props); if (log.isDebugEnabled()) { log.info("TOTPServiceComponent bundle is activated"); } }

Target:
protected void activate(ComponentContext ctxt) { TOTPManagerImpl totpService = new TOTPManagerImpl(); Hashtable<String, String> props = new Hashtable<String, String>(); ctxt.getBundleContext().registerService(TOTPManager.class.getName(), totpService, props); if (log.isDebugEnabled()) { log.debug("TOTPServiceComponent bundle is activated"); } }
Source:
public Opt<Iterator<Identity>> enter(final Request req) throws IOException { final Iterator<String> flg = new RqHref.Base(req).href() .param(this.flag).iterator(); final Collection<Identity> users = new ArrayList<Identity>(1); if (flg.hasNext()) { final String value = flg.next(); for (final Map.Entry<Pattern, Pass> ent : this.passes.entrySet()) { if (ent.getKey().matcher(value).matches()) { final Opt<Iterator<Identity>> tmpIdentity = ent.getValue() .enter(req); users.add(tmpIdentity.get().next()); } } } return new Opt.Single<Iterator<Identity>>(users.iterator()); }

Target:
public Opt<Identity> enter(final Request req) throws IOException { final Iterator<String> flg = new RqHref.Base(req).href() .param(this.flag).iterator(); Opt<Identity> user = new Opt.Empty<Identity>(); if (flg.hasNext()) { final String value = flg.next(); for (final Map.Entry<Pattern, Pass> ent : this.passes.entrySet()) { if (ent.getKey().matcher(value).matches()) { user = ent.getValue().enter(req); break; } } } return user; }
Source:
public double scaledEvidenceProbabilityUsingGenotypeFrequencies(final double[] genotypeFrequencies) { final double[] likelihoods = getLikelihoods(); assert (genotypeFrequencies.length == nGeno); assert (likelihoods.length == nGeno); double result = 0; for (Genotype g: Genotype.values()){ result += likelihoods[g.v] * genotypeFrequencies[g.v]; } return result; }

Target:
public double scaledEvidenceProbabilityUsingGenotypeFrequencies(final double[] genotypeFrequencies) { final double[] likelihoods = getLikelihoods(); ValidationUtils.validateArg(genotypeFrequencies.length == NUM_GENOTYPES, "provided genotype frequencies must be length 3"); ValidationUtils.validateArg(likelihoods.length == NUM_GENOTYPES, "internal liklihoods must be length 3"); double result = 0; for (Genotype g : Genotype.values()) { result += likelihoods[g.v] * genotypeFrequencies[g.v]; } return result; }
Source:
public Loader<Result> onCreateLoader(final int loaderId, final Bundle bundle) { BaseSimpleRequest request; switch (loaderId) { case ID_LOADER_REFRESH_ARTICLE: showLoadingState(true); request = new SimpleGetRequest( UrlFactory.buildNewsArticleURL(bundle.getString(ID)), BaseSimpleRequest.RequestType.FROM_NAVIGATION ); break; case ID_LOADER_HOOAH: request = new SimplePostRequest( UrlFactory.buildNewsArticleHooahURL(articleId), bundle ); break; case ID_LOADER_POST_COMMENT: request = new SimplePostRequest( UrlFactory.buildNewsArticlePostCommentURL(articleId), bundle ); break; case ID_LOADER_COMMENT_UPVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentUpvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; case ID_LOADER_COMMENT_DOWNVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentDownvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; default: throw new IllegalArgumentException("No loader matching " + loaderId); } return new IntelLoader(getActivity(), request); }

Target:
public Loader<Result> onCreateLoader(final int loaderId, final Bundle bundle) { BaseSimpleRequest request; switch (loaderId) { case ID_LOADER_REFRESH_ARTICLE: showLoadingState(bundle.getBoolean(FLAG_SHOW_LOADING, true)); request = new SimpleGetRequest( UrlFactory.buildNewsArticleURL(bundle.getString(ID)), BaseSimpleRequest.RequestType.FROM_NAVIGATION ); break; case ID_LOADER_HOOAH: request = new SimplePostRequest( UrlFactory.buildNewsArticleHooahURL(articleId), bundle ); break; case ID_LOADER_POST_COMMENT: request = new SimplePostRequest( UrlFactory.buildNewsArticlePostCommentURL(articleId), bundle ); break; case ID_LOADER_COMMENT_UPVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentUpvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; case ID_LOADER_COMMENT_DOWNVOTE: request = new SimplePostRequest( UrlFactory.buildNewsArticleCommentDownvoteURL(bundle.getString(COMMENT_ID)), bundle ); break; default: throw new IllegalArgumentException("No loader matching " + loaderId); } return new IntelLoader(getActivity(), request); }
Source:
public void flop(Throwable thr, String msg) { try { fail(msg); } catch (Throwable t) { asyncErrors.add(thr); throw new RuntimeException(t); } }

Target:
public void flop(Throwable thr, String msg) { try { fail(msg); } catch (Throwable t) { asyncErrors.add(thr); } }
Source:
public boolean didMove() { return moved || (copied && deletedOld); }

Target:
public boolean didMove() { return copied && deletedOld; }
Source:
public long readLong(final int numBits) { if (numBits < 0 || numBits > Long.SIZE) { throw new IllegalArgumentException("bits must be in range 0 ... 64!"); } long bits = 0; if (currentBitIndex < 0 && (numBits & 0x7) == 0) { for (int i = numBits; i > 0; i -= 8) { bits <<= 8; bits |= readByte(); } } else { for (int i = numBits - 1; i >= 0; i--) { if (currentBitIndex < 0) { readCurrentByte(); } boolean bit = (currentByte >> currentBitIndex & 1) != 0; if (bit) { bits |= (1L << i); } --currentBitIndex; } } return bits; }

Target:
public long readLong(final int numBits) { if (numBits < 0 || numBits > Long.SIZE) { throw new IllegalArgumentException("bits must be in range 0 ... 64!"); } long bits = 0; if (currentBitIndex < 0 && (numBits & 0x7) == 0) { for (int i = 0; i < numBits; i += 8) { bits <<= 8; bits |= readByte(); } } else { for (int i = numBits - 1; i >= 0; i--) { if (currentBitIndex < 0) { readCurrentByte(); } boolean bit = (currentByte >> currentBitIndex & 1) != 0; if (bit) { bits |= (1L << i); } --currentBitIndex; } } return bits; }
Source:
public void testElementWithGenericNodeAttributes() { FaxResponse.Builder builder = new FaxResponse.Builder(); GenericNode.Builder genericBuilder = new GenericNode.Builder("genericTag"); genericBuilder.option("key", "value").addText("someText"); GenericNode node = genericBuilder.build(); Receive.Builder receiveBuilder = new Receive.Builder().addChild(node); Receive message = receiveBuilder.build(); FaxResponse elem = builder.receive(message).build(); Assert.assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Response>" + "<Receive>"+ "<genericTag key=\"value\">"+ "someText"+ "</genericTag>"+ "</Receive>"+ "</Response>", elem.toXml() ); }

Target:
public void testElementWithGenericNodeAttributes() { GenericNode.Builder genericBuilder = new GenericNode.Builder("genericTag"); GenericNode node = genericBuilder.option("key", "value").addText("someText").build(); FaxResponse.Builder builder = new FaxResponse.Builder(); FaxResponse elem = builder.addChild(node).build(); Assert.assertEquals( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Response>" + "<genericTag key=\"value\">" + "someText" + "</genericTag>" + "</Response>", elem.toXml() ); }
Source:
private static boolean isBlacklistedTransformer(TransformerDescriptors descriptors, String id) { for (String transformer : descriptors.getBlackListedMetacardTransformers()) { if (id.endsWith(transformer)) { return true; } } return false; }

Target:
private static boolean isBlacklistedTransformer(TransformerDescriptors descriptors, String id) { return descriptors .getBlackListedMetacardTransformerIds() .stream() .anyMatch(s -> id.endsWith(s)); }
Source:
protected void isNuageVspManagerLoaded() throws Exception { if (!_isNuageVspClientLoaded || _nuageVspManagerClient == null) { throw new Exception(NUAGE_VSP_PLUGIN_ERROR_MESSAGE); } }

Target:
protected void isNuageVspManagerLoaded() throws ConfigurationException { if (!_isNuageVspClientLoaded || _nuageVspManagerClient == null) { throw new ConfigurationException(NUAGE_VSP_PLUGIN_ERROR_MESSAGE); } }
Source:
private void saveMediaToDevice() { String[] permissionList = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; if (!PermissionUtils.checkAndRequestPermissions(this, WPPermissionUtils.MEDIA_PREVIEW_PERMISSION_REQUEST_CODE, permissionList)) { return; } if (!NetworkUtils.checkConnection(this)) { return; } DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mMedia.getUrl())); try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mMedia.getFileName()); } catch (IllegalStateException error) { AppLog.e(AppLog.T.MEDIA, error); ToastUtils.showToast(MediaSettingsActivity.this, R.string.error_media_save); return; } request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.addRequestHeader("User-Agent", WordPress.getDefaultUserAgent()); mDownloadId = dm.enqueue(request); invalidateOptionsMenu(); ToastUtils.showToast(this, R.string.media_downloading); }

Target:
private void saveMediaToDevice() { String[] permissionList = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; if (!PermissionUtils.checkAndRequestPermissions(this, WPPermissionUtils.MEDIA_PREVIEW_PERMISSION_REQUEST_CODE, permissionList)) { return; } if (!NetworkUtils.checkConnection(this)) { return; } DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mMedia.getUrl())); try { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mMedia.getFileName()); } catch (IllegalStateException error) { AppLog.e(AppLog.T.MEDIA, error); ToastUtils.showToast(MediaSettingsActivity.this, R.string.error_media_save); return; } request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.addRequestHeader("User-Agent", WordPress.getUserAgent()); mDownloadId = dm.enqueue(request); invalidateOptionsMenu(); ToastUtils.showToast(this, R.string.media_downloading); }
Source:
public Type toStorageType(Type type) { Type storageType; if (type.equals(BOOLEAN) || type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT) || type.equals(DOUBLE) || type.equals(REAL) || type.equals(DATE) || isCharType(type) || isVarcharType(type) || isLongDecimal(type) || isShortDecimal(type) || type.equals(VARBINARY)) { storageType = type; } else if (type.equals(TIME) || type.equals(TIMESTAMP)) { storageType = BIGINT; } else if (type instanceof ArrayType) { storageType = new ArrayType(toStorageType(((ArrayType) type).getElementType())); } else if (type instanceof MapType) { storageType = mapType(toStorageType(((MapType) type).getKeyType()), toStorageType(((MapType) type).getValueType())); } else { throw new PrestoException(NOT_SUPPORTED, "Type not supported: " + type); } try { checkState(storageType.getJavaType().equals(type.getJavaType())); } catch (Exception e) { System.out.println("ooh"); } return storageType; }

Target:
public Type toStorageType(Type type) { Type storageType; if (type.equals(BOOLEAN) || type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT) || type.equals(DOUBLE) || type.equals(REAL) || type.equals(DATE) || isCharType(type) || isVarcharType(type) || isLongDecimal(type) || isShortDecimal(type) || type.equals(VARBINARY)) { storageType = type; } else if (type.equals(TIME) || type.equals(TIMESTAMP)) { storageType = BIGINT; } else if (type instanceof ArrayType) { storageType = new ArrayType(toStorageType(((ArrayType) type).getElementType())); } else if (type instanceof MapType) { storageType = mapType(toStorageType(((MapType) type).getKeyType()), toStorageType(((MapType) type).getValueType())); } else { throw new PrestoException(NOT_SUPPORTED, "Type not supported: " + type); } checkState(storageType.getJavaType().equals(type.getJavaType())); return storageType; }
Source:
public DirectConnectionConfig() { this.connectionTimeout = null; this.idleConnectionTimeout = Duration.ZERO; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_ENDPOINT; }

Target:
public DirectConnectionConfig() { this.idleConnectionTimeout = Duration.ZERO; this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; this.idleEndpointTimeout = DEFAULT_IDLE_ENDPOINT_TIMEOUT; this.maxConnectionsPerEndpoint = DEFAULT_MAX_CONNECTIONS_PER_ENDPOINT; this.maxRequestsPerConnection = DEFAULT_MAX_REQUESTS_PER_CONNECTION; }
Source:
AnnotationMirror convertStringValToMatchesRegex( AnnotationMirror stringValAnno) { List<String> values = getStringValues(stringValAnno); List<@Regex String> valuesAsRegexes = new ArrayList<>(); for (String value : values) { valuesAsRegexes.add("^" + Pattern.quote(value) + "$"); } return createMatchesRegexAnnotation(valuesAsRegexes); }

Target:
AnnotationMirror convertStringValToMatchesRegex( AnnotationMirror stringValAnno) { List<String> values = getStringValues(stringValAnno); List<@Regex String> valuesAsRegexes = new ArrayList<>(); for (String value : values) { valuesAsRegexes.add(Pattern.quote(value)); } return createMatchesRegexAnnotation(valuesAsRegexes); }
Source:
public long applyPoliteness(WebURL url) { long politenessDelay = NO_POLITENESS_APPLIED; String host = getHost(url); if (host != null) { if (seenHosts.containsKey(host)) { Date lastFetchTime = seenHosts.get(host); if (lastFetchTime != null) { long now = (new Date()).getTime(); long diff = (now - lastFetchTime.getTime()); if (diff < config.getPolitenessDelay()) { politenessDelay = config.getPolitenessDelay() - diff; logger.debug("Applying politeness delay of ms for host {}", politenessDelay, host); } else { } } } seenHosts.put(host, new Date()); return politenessDelay; } else { logger.warn("Could not determine host for: " + url.getURL()); return politenessDelay; } }

Target:
public long applyPoliteness(WebURL url) { synchronized (mutex) { long politenessDelay = NO_POLITENESS_APPLIED; String host = getHost(url); if (host != null) { Date lastFetchTime = seenHosts.getIfPresent(host); if (lastFetchTime != null) { long now = (new Date()).getTime(); long diff = (now - lastFetchTime.getTime()); if (diff < config.getPolitenessDelay()) { politenessDelay = config.getPolitenessDelay() - diff; logger.debug("Applying politeness delay of ms for host {}", politenessDelay, host); } else { } } seenHosts.put(host, new Date()); } return politenessDelay; } }
Source:
protected void doHealthCheck(Health.Builder builder) throws Exception { builder.up(); List<Map<String, Object>> details = new ArrayList<>(); for (String name : this.repositories.keySet()) { Repository repository = this.repositories.get(name); String application = (repository.getName() == null)? name : repository.getName(); String profiles = repository.getProfiles(); try { Environment environment = this.environmentRepository.findOne(application, profiles, repository.getLabel()); HashMap<String, Object> detail = new HashMap<>(); detail.put("name", environment.getName()); detail.put("label", environment.getLabel()); if (environment.getCached()) { builder.outOfService(); } if (environment.getProfiles() != null && environment.getProfiles().length > 0) { detail.put("profiles", Arrays.asList(environment.getProfiles())); } if (!CollectionUtils.isEmpty(environment.getPropertySources())) { List<String> sources = new ArrayList<>(); for (PropertySource source : environment.getPropertySources()) { sources.add(source.getName()); } detail.put("sources", sources); } details.add(detail); } catch (Exception e) { HashMap<String, String> map = new HashMap<>(); map.put("application", application); map.put("profiles", profiles); builder.withDetail("repository", map); builder.down(e); return; } } builder.withDetail("repositories", details); }

Target:
protected void doHealthCheck(Health.Builder builder) throws Exception { builder.up(); List<Map<String, Object>> details = new ArrayList<>(); for (String name : this.repositories.keySet()) { Repository repository = this.repositories.get(name); String application = (repository.getName() == null)? name : repository.getName(); String profiles = repository.getProfiles(); try { Environment environment = this.environmentRepository.findOne(application, profiles, repository.getLabel()); HashMap<String, Object> detail = new HashMap<>(); detail.put("name", environment.getName()); detail.put("label", environment.getLabel()); if (environment.getCached()) { builder.unknown(); } if (environment.getProfiles() != null && environment.getProfiles().length > 0) { detail.put("profiles", Arrays.asList(environment.getProfiles())); } if (!CollectionUtils.isEmpty(environment.getPropertySources())) { List<String> sources = new ArrayList<>(); for (PropertySource source : environment.getPropertySources()) { sources.add(source.getName()); } detail.put("sources", sources); } details.add(detail); } catch (Exception e) { HashMap<String, String> map = new HashMap<>(); map.put("application", application); map.put("profiles", profiles); builder.withDetail("repository", map); builder.down(e); return; } } builder.withDetail("repositories", details); }
Source:
@Override protected Void run() throws Exception { String fromImage = null; FilePath dockerfile = workspace.child(step.dockerfile); InputStream is = dockerfile.read(); BufferedReader r = null; try { r = new BufferedReader(new InputStreamReader(is, "ASCII")); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { continue; } if (line.startsWith("FROM ")) { fromImage = line.substring(5); break; } } } finally { IOUtils.closeQuietly(r); } if (fromImage == null) { throw new AbortException("could not find FROM instruction in " + dockerfile); } DockerClient client = new DockerClient(launcher, node, step.toolName); String descendantImageId = client.inspectRequiredField(env, step.image, ".Id"); if (fromImage.equals("scratch")) { DockerFingerprints.addFromFacet(null, descendantImageId, run); } else { DockerFingerprints.addFromFacet(client.inspectRequiredField(env, fromImage, ".Id"), descendantImageId, run); ImageAction.add(fromImage, run); } return null; }

Target:
@Override protected Void run() throws Exception { String fromImage = null; FilePath dockerfile = workspace.child(step.dockerfile); InputStream is = dockerfile.read(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "ISO-8859-1")); try { String line; while ((line = r.readLine()) != null) { line = line.trim(); if (line.startsWith("#")) { continue; } if (line.startsWith("FROM ")) { fromImage = line.substring(5); break; } } } finally { r.close(); } } finally { is.close(); } if (fromImage == null) { throw new AbortException("could not find FROM instruction in " + dockerfile); } DockerClient client = new DockerClient(launcher, node, step.toolName); String descendantImageId = client.inspectRequiredField(env, step.image, ".Id"); if (fromImage.equals("scratch")) { DockerFingerprints.addFromFacet(null, descendantImageId, run); } else { DockerFingerprints.addFromFacet(client.inspectRequiredField(env, fromImage, ".Id"), descendantImageId, run); ImageAction.add(fromImage, run); } return null; }
Source:
private Map<String, LockFile> lockLooseRefs(List<ReceiveCommand> commands) throws IOException { ReceiveCommand failed = null; Map<String, LockFile> locks = new HashMap<>(); try { RETRY: for (int ms : refdb.getRetrySleepMs()) { failed = null; unlockAll(locks); locks.clear(); RefDirectory.sleep(ms); for (ReceiveCommand c : commands) { String name = c.getRefName(); LockFile lock = new LockFile(refdb.fileFor(name)); if (locks.put(name, lock) != null) { throw new IOException( MessageFormat.format(JGitText.get().duplicateRef, name)); } if (!lock.lock()) { failed = c; continue RETRY; } } return locks; } } catch (IOException e) { unlockAll(locks); throw e; } unlockAll(locks); lockFailure(failed != null ? failed : commands.get(0), commands); return null; }

Target:
private Map<String, LockFile> lockLooseRefs(List<ReceiveCommand> commands) throws IOException { ReceiveCommand failed = null; Map<String, LockFile> locks = new HashMap<>(); try { RETRY: for (int ms : refdb.getRetrySleepMs()) { failed = null; unlockAll(locks); locks.clear(); RefDirectory.sleep(ms); for (ReceiveCommand c : commands) { String name = c.getRefName(); LockFile lock = new LockFile(refdb.fileFor(name)); if (locks.put(name, lock) != null) { throw new IOException( MessageFormat.format(JGitText.get().duplicateRef, name)); } if (!lock.lock()) { failed = c; continue RETRY; } } Map<String, LockFile> result = locks; locks = null; return result; } } finally { unlockAll(locks); } lockFailure(failed != null ? failed : commands.get(0), commands); return null; }
Source:
public void handleValidationErrors(GlusterVolumeSnapshotModel object) { StringBuilder generalTabErrorBuilder = new StringBuilder(); if (!snapshotNameEditor.isValid()){ appendErrors(Collections.singletonList(constants.volumeSnapshotNamePrefixLabel()), generalTabErrorBuilder); appendErrors(object.getSnapshotName().getInvalidityReasons(), generalTabErrorBuilder); } generalTabErrorMsgLabel.setText(generalTabErrorBuilder.toString()); generalTabErrorMsgLabel.setVisible(generalTabErrorBuilder.toString() != null || !generalTabErrorBuilder.toString().isEmpty()); if (!clusterNameEditor.isValid() || !volumeNameEditor.isValid() || !snapshotNameEditor.isValid() || !snapshotDescriptionEditor.isValid()) { tabContainer.switchTab(generalTab); } else if (!recurrenceEditor.isValid() || !intervalEditor.isValid() || !timeZoneEditor.isValid() || !startAtEditor.isValid() || !executionTimeEditor.isValid() || !daysOfWeekEditor.isValid() || !daysOfMonthEditor.isValid() || !endByOptionsEditor.isValid() || !endDate.isValid()) { tabContainer.switchTab(scheduleTab); } }

Target:
public void handleValidationErrors(GlusterVolumeSnapshotModel object) { String generalTabErrors = collectGeneralTabErrors(object); setMessage(generalTabErrors, generalTabErrorMsgLabel); String scheduleTabErrors = collectScheduleTabErrors(object); setMessage(scheduleTabErrors, errorMsgLabel); }