auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void registerAdditionalBox(@Observes BeforeBeanDiscovery event, BeanManager manager) { final AnnotatedType<Box> original = manager.createAnnotatedType(Box.class); AnnotatedType<Box> modifiedType = new ForwardingAnnotatedType<Box>() { @Override public AnnotatedType<Box> delegate() { return original; } @Override @SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(Class<A> annotationType) { if (Additional.class.equals(annotationType)) { return (A) Additional.Literal.INSTANCE; } return null; } @Override public Set<Annotation> getAnnotations() { return Collections.<Annotation>singleton(Additional.Literal.INSTANCE); } @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return getAnnotation(annotationType) != null; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set<AnnotatedMethod<? super Box>> getMethods() { ImmutableSet.Builder builder = ImmutableSet.builder(); Set<AnnotatedMethod<? super Box>> annotatedMethods = delegate().getMethods(); for (final AnnotatedMethod<? super Box> annotatedMethod : annotatedMethods) { builder.add(new NoAnnotationMethodWrapper() { protected AnnotatedMethod<? super Box> delegate() { return annotatedMethod; } }); } return builder.build(); } }; event.addAnnotatedType(modifiedType, "additionalBox"); }

Target:
void registerAdditionalBox(@Observes BeforeBeanDiscovery event, BeanManager manager) { final AnnotatedType<Box> original = manager.createAnnotatedType(Box.class); AnnotatedType<Box> modifiedType = new ForwardingAnnotatedType<Box>() { @Override public AnnotatedType<Box> delegate() { return original; } @Override @SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(Class<A> annotationType) { if (Additional.class.equals(annotationType)) { return (A) Additional.Literal.INSTANCE; } return null; } @Override public Set<Annotation> getAnnotations() { return Collections.<Annotation>singleton(Additional.Literal.INSTANCE); } @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) { return getAnnotation(annotationType) != null; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Set<AnnotatedMethod<? super Box>> getMethods() { Set<AnnotatedMethod<? super Box>> methods = new HashSet<>(); Set<AnnotatedMethod<? super Box>> annotatedMethods = delegate().getMethods(); for (final AnnotatedMethod<? super Box> annotatedMethod : annotatedMethods) { methods.add(new NoAnnotationMethodWrapper() { protected AnnotatedMethod<? super Box> delegate() { return annotatedMethod; } }); } return methods; } }; event.addAnnotatedType(modifiedType, "additionalBox"); }
Source:
public void clear() { getClient().unsetSessionVariables(Lists.newArrayList("TIMEZONE")); }

Target:
public void clear() { getClient().unsetSessionVariables(Lists.newArrayList(SessionVars.TIMEZONE.name())); }
Source:
public void handleGameInterruption( final GameSelectorModel gameSelectorModel, final ServerModel serverModel) { try { log.info("Game ended, going back to waiting."); serverModel.setAllPlayersToNullNodes(); final File f1 = getAutoSaveFileUtils().getHeadlessAutoSaveFile(); if (!f1.exists()) { gameSelectorModel.load(f1); } } catch (final Exception e1) { log.log(Level.SEVERE, "Failed to load game", e1); gameSelectorModel.resetGameDataToNull(); } }

Target:
public void handleGameInterruption( final GameSelectorModel gameSelectorModel, final ServerModel serverModel) { try { log.info("Game ended, going back to waiting."); serverModel.setAllPlayersToNullNodes(); final File autoSaveFile = getAutoSaveFileUtils().getHeadlessAutoSaveFile(); if (autoSaveFile.exists()) { gameSelectorModel.load(autoSaveFile); } } catch (final Exception e1) { log.log(Level.SEVERE, "Failed to load game", e1); gameSelectorModel.resetGameDataToNull(); } }
Source:
public void setSkeletonType(MCSkeletonType type) { try { ((Skeleton) getHandle()).setSkeletonType(BukkitMCSkeletonType.getConvertor().getConcreteEnum(type)); } catch(UnsupportedOperationException ex){ CHLog.GetLogger().Log(CHLog.Tags.DEPRECATION, LogLevel.WARNING, "Cannot change Skeleton to Stray or WitherSkeleton in Minecraft 1.11+", Target.UNKNOWN); } }

Target:
public void setSkeletonType(MCSkeletonType type) { try { ((Skeleton) getHandle()).setSkeletonType(BukkitMCSkeletonType.getConvertor().getConcreteEnum(type)); } catch(UnsupportedOperationException ex){ CHLog.GetLogger().Log(CHLog.Tags.DEPRECATION, LogLevel.ERROR, "Cannot change Skeleton to Stray or WitherSkeleton in Minecraft 1.11+", Target.UNKNOWN); } }
Source:
public void formatDateTime_withCurrentYear_worksSinceM() { final long millisAtStartOfYear = getMillisAtStartOfYear(); String actual = DateUtils.formatDateTime(RuntimeEnvironment.application, millisAtStartOfYear, DateUtils.FORMAT_NUMERIC_DATE); assertThat(actual).isEqualTo("1/1/2016"); }

Target:
public void formatDateTime_withCurrentYear_worksSinceM() { Calendar calendar = Calendar.getInstance(); final int currentYear = calendar.get(Calendar.YEAR); final long millisAtStartOfYear = getMillisAtStartOfYear(); String actual = DateUtils.formatDateTime(RuntimeEnvironment.application, millisAtStartOfYear, DateUtils.FORMAT_NUMERIC_DATE); assertThat(actual).isEqualTo("1/1/" + currentYear); }
Source:
private static Interval findInitialSearchInterval( VersionedIntervalTimeline<String, DataSegment> timeline, Period skipOffset ) { Preconditions.checkArgument(timeline != null && !timeline.isEmpty(), "timeline should not be null or empty"); Preconditions.checkNotNull(skipOffset, "skipOffset"); final TimelineObjectHolder<String, DataSegment> first = Preconditions.checkNotNull(timeline.first(), "first"); final TimelineObjectHolder<String, DataSegment> last = Preconditions.checkNotNull(timeline.last(), "last"); final Interval skipInterval = new Interval(skipOffset, last.getInterval().getEnd()); final DateTime lookupStart = first.getInterval().getStart(); final DateTime lookupEnd = last.getInterval().getEnd().minus(skipOffset); if (lookupStart.isBefore(lookupEnd)) { final List<TimelineObjectHolder<String, DataSegment>> holders = timeline.lookup( new Interval(first.getInterval().getStart(), last.getInterval().getEnd().minus(skipOffset)) ); final List<DataSegment> segments = holders .stream() .flatMap(holder -> StreamSupport.stream(holder.getObject().spliterator(), false)) .map(PartitionChunk::getObject) .filter(segment -> !segment.getInterval().overlaps(skipInterval)) .sorted((s1, s2) -> Comparators.intervalsByStartThenEnd().compare(s1.getInterval(), s2.getInterval())) .collect(Collectors.toList()); if (segments.isEmpty()) { return null; } else { return new Interval( segments.get(0).getInterval().getStart(), segments.get(segments.size() - 1).getInterval().getEnd() ); } } else { return null; } }

Target:
private static Interval findInitialSearchInterval( VersionedIntervalTimeline<String, DataSegment> timeline, Period skipOffset ) { Preconditions.checkArgument(timeline != null && !timeline.isEmpty(), "timeline should not be null or empty"); Preconditions.checkNotNull(skipOffset, "skipOffset"); final TimelineObjectHolder<String, DataSegment> first = Preconditions.checkNotNull(timeline.first(), "first"); final TimelineObjectHolder<String, DataSegment> last = Preconditions.checkNotNull(timeline.last(), "last"); final Interval skipInterval = new Interval(skipOffset, last.getInterval().getEnd()); final DateTime lookupStart = first.getInterval().getStart(); final DateTime lookupEnd = last.getInterval().getEnd().minus(skipOffset); if (lookupStart.isBefore(lookupEnd)) { final List<TimelineObjectHolder<String, DataSegment>> holders = timeline.lookup( new Interval(lookupStart, lookupEnd) ); final List<DataSegment> segments = holders .stream() .flatMap(holder -> StreamSupport.stream(holder.getObject().spliterator(), false)) .map(PartitionChunk::getObject) .filter(segment -> !segment.getInterval().overlaps(skipInterval)) .sorted((s1, s2) -> Comparators.intervalsByStartThenEnd().compare(s1.getInterval(), s2.getInterval())) .collect(Collectors.toList()); if (segments.isEmpty()) { return null; } else { return new Interval( segments.get(0).getInterval().getStart(), segments.get(segments.size() - 1).getInterval().getEnd() ); } } else { return null; } }
Source:
protected void process(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String uri = httpRequest.getRequestURI(); if (httpRequest.getPathInfo().startsWith(OAUTH2_SEGMENT)) { String endpoint = uri.split(OAUTH2_SEGMENT)[1]; switch (endpoint) { case ENDPOINT_AUTH: processAuthorization(httpRequest, httpResponse, chain); break; case ENDPOINT_TOKEN: processToken(httpRequest, httpResponse, chain); break; } } else if (isAuthorizedRequest(httpRequest)) { processAuthentication(httpRequest, httpResponse, chain); } if (!response.isCommitted()) { chain.doFilter(request, response); } }

Target:
protected void process(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String uri = httpRequest.getRequestURI(); if (httpRequest.getPathInfo() != null && httpRequest.getPathInfo().startsWith(OAUTH2_SEGMENT)) { String endpoint = uri.split(OAUTH2_SEGMENT)[1]; switch (endpoint) { case ENDPOINT_AUTH: processAuthorization(httpRequest, httpResponse, chain); break; case ENDPOINT_TOKEN: processToken(httpRequest, httpResponse, chain); break; } } else if (isAuthorizedRequest(httpRequest)) { processAuthentication(httpRequest, httpResponse, chain); } if (!response.isCommitted()) { chain.doFilter(request, response); } }
Source:
public void onMessage(Message message) { if (isTTransport) { try { frameBuffer.put(message.getData()); } catch (InterruptedException ignored) { } } else { try { executeFrame(message.getData()); } catch (TException ignored) { } } }

Target:
public void onMessage(Message message) { if (isTTransport) { try { frameBuffer.put(message.getData()); } catch (InterruptedException ignored) { } } else { try { executeFrame(message.getData()); } catch (TException e) { LOGGER.warn("Could not execute frame", e); } } }
Source:
protected void doExecute() { DiagramDescription diagramdesc = DescriptionFactory.eINSTANCE.createDiagramDescription(); diagramdesc.setName(BASE_ID + ".default.layer"); viewpoint.getOwnedRepresentations().add(diagramdesc); Layer layer = DescriptionFactory.eINSTANCE.createLayer(); diagramdesc.setDefaultLayer(layer); ContainerMapping packageMapping = createPackageMapping(layer); ContainerMapping classMapping = createClassListMapping(layer); createClassListMapping(layer); EdgeMapping edgeMappingInheritance = createEdgeMappingInheritance(layer, classMapping); EdgeMapping edgeMappingReference = createEdgeMappingReference(layer, classMapping); ToolSection toolSection = createToolSection(layer); createContainerClassMapping(toolSection, classMapping); createContainerPackageMapping(toolSection, packageMapping); createDeleteTool(toolSection, classMapping, classMapping, edgeMappingInheritance, edgeMappingReference); createEditTool(toolSection, classMapping, classMapping, edgeMappingInheritance, edgeMappingReference); createNodeCreation(toolSection, classMapping); }

Target:
protected void doExecute() { DiagramDescription diagramdesc = DescriptionFactory.eINSTANCE.createDiagramDescription(); diagramdesc.setName(BASE_ID + ".default.layer"); viewpoint.getOwnedRepresentations().add(diagramdesc); Layer layer = DescriptionFactory.eINSTANCE.createLayer(); diagramdesc.setDefaultLayer(layer); ToolSection toolSection = createToolSection(layer); ContainerMapping packageMapping = createPackageMapping(layer); NodeMapping attributes = createAttributes(toolSection); ContainerMapping classMapping = createClassListMapping(toolSection, layer, attributes); EdgeMapping edgeMappingInheritance = createEdgeMappingInheritance(toolSection, layer, classMapping); EdgeMapping edgeMappingReference = createEdgeMappingReference(toolSection, layer, classMapping); createContainerClassMapping(toolSection, classMapping); createContainerPackageMapping(toolSection, packageMapping); ArrayList<DiagramElementMapping> mappings = new ArrayList<DiagramElementMapping>(); mappings.add(classMapping); mappings.add(packageMapping); mappings.add(edgeMappingReference); mappings.add(edgeMappingInheritance); createDeleteTool(toolSection, mappings); createEditTool(toolSection, mappings); createNodeCreation(toolSection, classMapping); }
Source:
public boolean areSuggestionsDisplayed() { try { wait.forElementVisible(suggestedVideo); return true; } catch(NoSuchElementException e) { PageObjectLogging.log("areSuggestionsDisplayed", "Verified suggested module appeared", false, driver); return false; } }

Target:
public boolean areSuggestionsDisplayed() { try { wait.forElementVisible(suggestedVideo); return true; } catch(TimeoutException e) { PageObjectLogging.logInfo("Suggestion are not displayed", e); return false; } }
Source:
private static IpVersion getIpVersion(IpAddressAssignment ipAddressAssignment) { Ip ip = ipAddressAssignment.getIp(); if (ip == null) { return null; } if (ip.isSetVersion()) { return ip.getVersion(); } String address = ip.getAddress(); if (address == null) { return null; } return address.indexOf(':') == -1? IpVersion.V4: IpVersion.V6; }

Target:
private static IpVersion getIpVersion(IpAddressAssignment ipAddressAssignment) { Ip ip = ipAddressAssignment.getIp(); if (ip == null) { return null; } if (ip.isSetVersion()) { return ip.getVersion(); } String address = ip.getAddress(); if (address == null) { return null; } return address.contains(":")? IpVersion.V6: IpVersion.V4; }
Source:
public Object convert(byte[] tuple) { inputRecords++; if (tuple == null) { errorRecords++; return null; } String incomingString = new String(tuple); if (StringUtils.isBlank(incomingString) || StringUtils.equals(incomingString, header)) { errorRecords++; return null; } try { csvStringReader.open(incomingString); Object obj = csvBeanReader.read(clazz, nameMapping, processors); convertedRecords++; return obj; } catch (SuperCsvCellProcessorException e) { logger.error("Error during conversion ", e.getMessage()); errorRecords++; return null; } catch (SuperCsvReflectionException e) { logger.error("Error during conversion ", e.getMessage()); errorRecords++; return null; } catch (SuperCsvException e) { logger.error("Error during conversion ", e.getMessage()); errorRecords++; return null; } catch (IOException e) { logger.error("Exception in convert method {}", e.getMessage()); DTThrowable.rethrow(e); } return null; }

Target:
public Object convert(byte[] tuple) { inputRecords++; if (tuple == null) { errorRecords++; return null; } String incomingString = new String(tuple); if (StringUtils.isBlank(incomingString) || StringUtils.equals(incomingString, header)) { errorRecords++; return null; } try { csvStringReader.open(incomingString); Object obj = csvBeanReader.read(clazz, nameMapping, processors); convertedRecords++; return obj; }catch (SuperCsvException e) { logger.error("Error during conversion ", e.getMessage()); errorRecords++; return null; } catch (IOException e) { logger.error("Exception in convert method {}", e.getMessage()); DTThrowable.rethrow(e); } return null; }
Source:
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId(); getLocalSessionToken(request, sessionToken, partitionKeyRangeId); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }

Target:
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) { String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN); if (!Strings.isNullOrEmpty(sessionToken)) { getLocalSessionToken(request, sessionToken, StringUtils.EMPTY); request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } }
Source:
private void assertBlobIdFieldValues(short version, BlobId blobId, byte flag, byte datacenterId, short accountId, short containerId, PartitionId partitionId) throws Exception { assertTrue("Used unrecognized version", version == BLOB_ID_V1 || version == BLOB_ID_V2); assertEquals("Wrong partition id in blobId: " + blobId, partitionId, blobId.getPartition()); switch (version) { case BLOB_ID_V1: assertEquals("Wrong flag in blobId: " + blobId, BlobId.DEFAULT_FLAG, blobId.getFlag()); assertEquals("Wrong datacenter id in blobId: " + blobId, LEGACY_DATACENTER_ID, blobId.getDatacenterId()); assertEquals("Wrong account id in blobId: " + blobId, Account.LEGACY_ACCOUNT_ID, blobId.getAccountId()); assertEquals("Wrong container id in blobId: " + blobId, Container.LEGACY_CONTAINER_ID, blobId.getContainerId()); break; case BLOB_ID_V2: assertEquals("Wrong flag in blobId: " + blobId, flag, blobId.getFlag()); assertEquals("Wrong datacenter id in blobId: " + blobId, datacenterId, blobId.getDatacenterId()); assertEquals("Wrong account id in blobId: " + blobId, accountId, blobId.getAccountId()); assertEquals("Wrong container id in blobId: " + blobId, containerId, blobId.getContainerId()); break; } System.out.println("BlobId=" + blobId + ", flag=" + blobId.getFlag() + ", datacenterId=" + blobId.getDatacenterId() + ", accountId=" + blobId.getAccountId() + ", containerId=" + blobId.getContainerId() + ", idSizeInBytes=" + blobId.toString().length()); }

Target:
private void assertBlobIdFieldValues(short version, BlobId blobId, byte flag, byte datacenterId, short accountId, short containerId, PartitionId partitionId) throws Exception { assertTrue("Used unrecognized version", version == BLOB_ID_V1 || version == BLOB_ID_V2); assertEquals("Wrong partition id in blobId: " + blobId, partitionId, blobId.getPartition()); switch (version) { case BLOB_ID_V1: assertEquals("Wrong flag in blobId: " + blobId, BlobId.DEFAULT_FLAG, blobId.getFlag()); assertEquals("Wrong datacenter id in blobId: " + blobId, UNKNOWN_DATACENTER_ID, blobId.getDatacenterId()); assertEquals("Wrong account id in blobId: " + blobId, Account.UNKNOWN_ACCOUNT_ID, blobId.getAccountId()); assertEquals("Wrong container id in blobId: " + blobId, Container.UNKNOWN_CONTAINER_ID, blobId.getContainerId()); break; case BLOB_ID_V2: assertEquals("Wrong flag in blobId: " + blobId, flag, blobId.getFlag()); assertEquals("Wrong datacenter id in blobId: " + blobId, datacenterId, blobId.getDatacenterId()); assertEquals("Wrong account id in blobId: " + blobId, accountId, blobId.getAccountId()); assertEquals("Wrong container id in blobId: " + blobId, containerId, blobId.getContainerId()); break; default: fail("Unrecognized version"); } }
Source:
public void resolveAllOfWithoutAggregatingParameters(@Injectable final List<AuthorizationValue> auths) { ParseOptions options = new ParseOptions(); options.setResolveFully(true); options.setResolveCombinators(false); OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/composed.yaml",auths,options).getOpenAPI(); ComposedSchema allOf = (ComposedSchema) openAPI.getComponents().getSchemas().get("ExtendedAddress"); assertEquals(allOf.getAllOf().size(), 2); assertTrue(allOf.getAllOf().get(0).getProperties().containsKey("street")); assertTrue(allOf.getAllOf().get(1).getProperties().containsKey("gps")); ComposedSchema schema = (ComposedSchema) openAPI.getPaths().get("/withInvalidComposedModel").getPost().getRequestBody().getContent().get("application/json").getSchema(); assertEquals(schema, allOf); assertEquals(allOf.getAllOf().size(), 2); assertTrue(allOf.getAllOf().get(0).getProperties().containsKey("street")); assertTrue(allOf.getAllOf().get(1).getProperties().containsKey("gps")); }

Target:
public void resolveAllOfWithoutAggregatingParameters(@Injectable final List<AuthorizationValue> auths) { ParseOptions options = new ParseOptions(); options.setResolveFully(true); options.setResolveCombinators(false); OpenAPI openAPI = new OpenAPIV3Parser().readLocation("src/test/resources/composed.yaml",auths,options).getOpenAPI(); ComposedSchema allOf = (ComposedSchema) openAPI.getComponents().getSchemas().get("ExtendedAddress"); assertEquals(allOf.getAllOf().size(), 2); assertTrue(allOf.getAllOf().get(0).getProperties().containsKey("street")); assertTrue(allOf.getAllOf().get(1).getProperties().containsKey("gps")); ComposedSchema schema = (ComposedSchema) openAPI.getPaths().get("/withInvalidComposedModel").getPost().getRequestBody().getContent().get("application/json").getSchema(); assertEquals(schema, allOf); assertEquals(schema.getAllOf().size(), 2); assertTrue(schema.getAllOf().get(0).getProperties().containsKey("street")); assertTrue(schema.getAllOf().get(1).getProperties().containsKey("gps")); }
Source:
public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (databaseContext.isBiblatexMode()) { return Optional.empty(); } String valueOnlySpacesWithinCurlyBraces = value; while (true) { Matcher matcher = INSIDE_CURLY_BRAKETS.matcher(valueOnlySpacesWithinCurlyBraces); if (!matcher.find()) { break; } valueOnlySpacesWithinCurlyBraces = matcher.replaceAll(""); } String[] delimitedStr = valueOnlySpacesWithinCurlyBraces.split("(\\.|\\!|\\?|\\;|\\:)"); for (String subStr : delimitedStr) { subStr = subStr.trim(); if (subStr.length() > 0) { subStr = subStr.substring(1); } boolean hasCapitalLettersThatBibtexWillConvertToSmallerOnes = HAS_CAPITAL_LETTERS.test(subStr); if (hasCapitalLettersThatBibtexWillConvertToSmallerOnes) { return Optional.of(Localization.lang("capital letters are not masked using curly brackets {}")); } } return Optional.empty(); }

Target:
public Optional<String> checkValue(String value) { if (StringUtil.isBlank(value)) { return Optional.empty(); } if (databaseContext.isBiblatexMode()) { return Optional.empty(); } String valueOnlySpacesWithinCurlyBraces = value; while (true) { Matcher matcher = INSIDE_CURLY_BRAKETS.matcher(valueOnlySpacesWithinCurlyBraces); if (!matcher.find()) { break; } valueOnlySpacesWithinCurlyBraces = matcher.replaceAll(""); } String[] splitTitle = DELIMITERS.split(valueOnlySpacesWithinCurlyBraces); for (String subTitle : splitTitle) { subTitle = subTitle.trim(); if (!subTitle.isEmpty()) { subTitle = subTitle.substring(1); if (HAS_CAPITAL_LETTERS.test(subTitle)) { return Optional.of(Localization.lang("capital letters are not masked using curly brackets {}")); } } } return Optional.empty(); }
Source:
public void removeAddOn(String addOn) { this.addOns.remove(addOn); }

Target:
public void removeAddOn(String addOn) { this.addOns.remove(addOn); this.updateRHCloudProfileModified(); }
Source:
public String getName() { String name = ""; for (FieldMetadata field : fields) { name += "[" + field.getName() + "]"; } return name; }

Target:
public String getName() { String name = StringUtils.EMPTY; for (FieldMetadata field : fields) { name += "[" + field.getName() + "]"; } return name; }
Source:
protected void possibleChange(TreePath element, int type) { DebugContextEvent event = null; synchronized (this) { if (fContext instanceof ITreeSelection) { ITreeSelection ss = (ITreeSelection) fContext; for (TreePath ssPath : ss.getPaths()) { if (ssPath.startsWith(element, null)) { if (ssPath.getSegmentCount() == element.getSegmentCount()) { event = new DebugContextEvent(this, fContext, type); } else { event = new DebugContextEvent(this, fContext, DebugContextEvent.STATE); } } } } } if (event == null) { return; } if (getControl().getDisplay().getThread() == Thread.currentThread()) { fire(event); } else { final DebugContextEvent finalEvent = event; Job job = new UIJob("context change") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { synchronized (TreeViewerContextProvider.this) { if (fContext instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) fContext; Object changed = ((IStructuredSelection)finalEvent.getContext()).getFirstElement(); if (!(ss.size() == 1 && ss.getFirstElement().equals(changed))) { return Status.OK_STATUS; } } } fire(finalEvent); return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } }

Target:
protected void possibleChange(TreePath element, int type) { DebugContextEvent event = null; synchronized (this) { if (fContext instanceof ITreeSelection) { ITreeSelection ss = (ITreeSelection) fContext; for (TreePath path : ss.getPaths()) { if (path.startsWith(element, null)) { if (path.getSegmentCount() == element.getSegmentCount()) { event = new DebugContextEvent(this, fContext, type); } else { event = new DebugContextEvent(this, fContext, DebugContextEvent.STATE); } } } } } if (event == null) { return; } if (getControl().getDisplay().getThread() == Thread.currentThread()) { fire(event); } else { final DebugContextEvent finalEvent = event; Job job = new UIJob("context change") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { synchronized (TreeViewerContextProvider.this) { if (fContext instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection) fContext; Object changed = ((IStructuredSelection)finalEvent.getContext()).getFirstElement(); if (!(ss.size() == 1 && ss.getFirstElement().equals(changed))) { return Status.OK_STATUS; } } } fire(finalEvent); return Status.OK_STATUS; } }; job.setSystem(true); job.schedule(); } }
Source:
public LogoutResponse buildLogoutResponse( String issuerOrEntityId, String topLevelStatusCode, String secondLevelStatusCode, String inResponseTo) { if (issuerOrEntityId == null) { throw new IllegalArgumentException("Issuer cannot be null"); } if (topLevelStatusCode == null || secondLevelStatusCode == null) { throw new IllegalArgumentException("Status Codes cannot be null"); } Status status = SamlProtocol.createStatus(topLevelStatusCode); StatusCode statusCode = SamlProtocol.createStatusCode(secondLevelStatusCode); status.getStatusCode().setStatusCode(statusCode); return SamlProtocol.createLogoutResponse( SamlProtocol.createIssuer(issuerOrEntityId), status, inResponseTo, "a" + UUID.randomUUID().toString()); }

Target:
public LogoutResponse buildLogoutResponse( String issuerOrEntityId, String topLevelStatusCode, String secondLevelStatusCode, String inResponseTo) { Validate.notNull(issuerOrEntityId, ISSUER_CANNOT_BE_NULL_MSG); Validate.notNull(topLevelStatusCode, "Top level Status Code cannot be null"); Validate.notNull(secondLevelStatusCode, "Second level Status Code cannot be null"); Status status = SamlProtocol.createStatus(topLevelStatusCode); StatusCode statusCode = SamlProtocol.createStatusCode(secondLevelStatusCode); status.getStatusCode().setStatusCode(statusCode); return SamlProtocol.createLogoutResponse( SamlProtocol.createIssuer(issuerOrEntityId), status, inResponseTo, "_" + UUID.randomUUID().toString()); }
Source:
public void reencode() { reEncoded = true; }

Target:
public void reencode() { reencoded = true; }
Source:
private void setupCountrySpinner() { Bundle params = getArguments().getBundle(ExtraConstants.PARAMS); if (params != null) { mCountryListSpinner.setWhitelistedCountryCodes( params.getStringArrayList(ExtraConstants.WHITELISTED_COUNTRY_CODES)); mCountryListSpinner.setBlacklistedCountryCodes( params.getStringArrayList(ExtraConstants.BLACKLISTED_COUNTRY_CODES)); } mCountryListSpinner.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPhoneInputLayout.setError(null); } }); }

Target:
private void setupCountrySpinner() { Bundle params = getArguments().getBundle(ExtraConstants.PARAMS); if (params != null) { mCountryListSpinner.setWhitelistedCountries( params.getStringArrayList(ExtraConstants.WHITELISTED_COUNTRIES)); mCountryListSpinner.setBlacklistedCountries( params.getStringArrayList(ExtraConstants.BLACKLISTED_COUNTRIES)); } mCountryListSpinner.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPhoneInputLayout.setError(null); } }); }
Source:
private Map<String, List<CopyNumberTriStateSegment>> calculateBestPathSegments(CopyNumberTriStateHiddenMarkovModel model, ReadCountCollection inputCounts) { final List<String> columnNames = inputCounts.columnNames(); final Map<String, List<CopyNumberTriStateSegment>> allSegments = new LinkedHashMap<>(columnNames.size()); long recordCount = 0; final List<Target> targets = inputCounts.targets(); for (int i = 0; i < columnNames.size(); i++) { final String columnName = columnNames.get(i); final double[] inputValues = inputCounts.counts().getColumn(i); final List<CopyNumberTriStateSegment> bestPathSegmentList = getCopyNumberTriStateSegments(model, targets, inputValues); recordCount += bestPathSegmentList.size(); allSegments.put(columnName, bestPathSegmentList); } logger.info(String.format("Found a total of %d segments across %d samples", recordCount, inputCounts.columnNames().size())); return allSegments; }

Target:
private Map<String, List<CopyNumberTriStateSegment>> calculateBestPathSegments(CopyNumberTriStateHiddenMarkovModel model, ReadCountCollection inputCounts) { final List<String> sampleNames = inputCounts.columnNames(); final Map<String, List<CopyNumberTriStateSegment>> allSegments = new LinkedHashMap<>(sampleNames.size()); long recordCount = 0; final List<Target> targets = inputCounts.targets(); for (int i = 0; i < sampleNames.size(); i++) { final String sampleName = sampleNames.get(i); final double[] inputValues = inputCounts.counts().getColumn(i); final List<CopyNumberTriStateSegment> bestPathSegmentList = getCopyNumberTriStateSegments(model, targets, inputValues); recordCount += bestPathSegmentList.size(); allSegments.put(sampleName, bestPathSegmentList); } logger.info(String.format("Found a total of %d segments across %d samples", recordCount, inputCounts.columnNames().size())); return allSegments; }
Source:
public File getConfigurationTmpDir() { return this.serverTempDir; }

Target:
File getConfigurationTmpDir() { return this.serverTempDir; }
Source:
private boolean hasSymbolDefined( String name, ParsingContext context ) { Optional< Boolean > hasSymbol = Helpers.firstNonNull( () -> { if( symbolTables.get( program.context().source() ) == null ) { return null; } if( !symbolTables.get( program.context().source() ).symbol( name ).isPresent() ) { return null; } return Boolean.TRUE; }, () -> { if( symbolTables.get( context.source() ) == null ) { return null; } if( !symbolTables.get( context.source() ).symbol( name ).isPresent() ) { return null; } return Boolean.TRUE; } ); return hasSymbol.isPresent(); }

Target:
private boolean hasSymbolDefined( String name, ParsingContext context ) { return (symbolTables.get( program.context().source() ) != null && symbolTables.get( program.context().source() ).getSymbol( name ).isPresent()) || (symbolTables.get( context.source() ) != null && symbolTables.get( context.source() ).getSymbol( name ).isPresent()); }
Source:
private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { PartitionControllerImpl self = this; CancellationToken cancellationToken = this.shutdownCts.getToken(); WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { partitionSupervisor.run(cancellationToken) .onErrorResume(throwable -> { if (throwable instanceof PartitionSplitException) { PartitionSplitException ex = (PartitionSplitException) throwable; return self.handleSplit(lease, ex.getLastContinuation()); } else if (throwable instanceof TaskCancelledException) { logger.debug("Partition %s: processing canceled.", lease.getLeaseToken()); } else { logger.warn("Partition %s: processing failed.", lease.getLeaseToken(), throwable); } return Mono.empty(); }) .then(self.removeLease(lease)).subscribe(); }); this.executorService.execute(partitionSupervisorTask); return partitionSupervisorTask; }

Target:
private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { CancellationToken cancellationToken = this.shutdownCts.getToken(); WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { partitionSupervisor.run(cancellationToken) .onErrorResume(throwable -> { if (throwable instanceof PartitionSplitException) { PartitionSplitException ex = (PartitionSplitException) throwable; return this.handleSplit(lease, ex.getLastContinuation()); } else if (throwable instanceof TaskCancelledException) { logger.debug("Partition {}: processing canceled.", lease.getLeaseToken()); } else { logger.warn("Partition {}: processing failed.", lease.getLeaseToken(), throwable); } return Mono.empty(); }) .then(this.removeLease(lease)).subscribe(); }); this.scheduler.schedule(partitionSupervisorTask); return partitionSupervisorTask; }
Source:
public void onContinue() { if (mSiteStore.hasSite()) { setResult(RESULT_OK); } else if (AppPrefs.shouldShowPostSignupInterstitial()) { ActivityLauncher.showPostSignupInterstitial(this); } finish(); }

Target:
public void onContinue() { if (!mSiteStore.hasSite()) { ActivityLauncher.showPostSignupInterstitial(this); } setResult(RESULT_OK); finish(); }
Source:
public void populateContextForCreate(@NotNull Map<String, Object> context) { super.populateContextForCreate(context); serverConfigManager = ServerConfigManager.getInstance(); populateContextForAllOperations(context); context.put(NEW_TASK_CREATED, true); context.put(AbstractBuildContext.CAPTURE_BUILD_INFO, true); context.put(PUBLISH_BUILD_INFO_PARAM, false); }

Target:
public void populateContextForCreate(@NotNull Map<String, Object> context) { super.populateContextForCreate(context); serverConfigManager = ServerConfigManager.getInstance(); populateContextForAllOperations(context); context.put(BUILD_INFO_AGGREGATION, true); context.put(AbstractBuildContext.CAPTURE_BUILD_INFO, true); context.put(PUBLISH_BUILD_INFO_PARAM, false); }
Source:
EmbeddedDbServer embeddedDbServer(CassandraEmbeddedConfiguration cassandraConfiguration, JanusGraphConfiguration janusGraphConfiguration) { if (!Files.exists(Paths.get(cassandraConfiguration.getStorageFolder()))) { logger.info(String.format("Extract storage from [%s].", PATH_STRONGBOX_DB)); initStorage(cassandraConfiguration); logger.info(String.format("Sotorage extracted to [%s].", cassandraConfiguration.getStorageFolder())); } return new EmbeddedJanusGraphWithCassandraServer(cassandraConfiguration, janusGraphConfiguration); }

Target:
JanusGraphServer embeddedDbServer(CassandraEmbeddedConfiguration cassandraConfiguration, JanusGraphConfiguration janusGraphConfiguration) { if (!Files.exists(Paths.get(cassandraConfiguration.getStorageRoot()))) { logger.info(String.format("Extract storage from [%s].", PATH_STRONGBOX_DB)); initStorage(cassandraConfiguration); logger.info(String.format("Storage extracted to [%s].", cassandraConfiguration.getStorageRoot())); } return new JanusGraphWithEmbeddedCassandra(cassandraConfiguration, janusGraphConfiguration); }
Source:
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); final DataStorageConfiguration dataStorageConfiguration = new DataStorageConfiguration(); dataStorageConfiguration.getDefaultDataRegionConfiguration().setPersistenceEnabled(true); dataStorageConfiguration.setFileIOFactory(new FailingFileIOFactory()); cfg.setDataStorageConfiguration(dataStorageConfiguration); CacheConfiguration ccfg = new CacheConfiguration(); ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL); ccfg.setName(DEFAULT_CACHE_NAME); ccfg.setBackups(1); cfg.setCacheConfiguration(ccfg); cfg.setFailureHandler(new StopNodeFailureHandler()); return cfg; }

Target:
@Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(gridName); final DataStorageConfiguration dataStorageConfiguration = new DataStorageConfiguration(); dataStorageConfiguration.getDefaultDataRegionConfiguration().setPersistenceEnabled(true).setMaxSize(1 << 24); dataStorageConfiguration.setFileIOFactory(new FailingFileIOFactory()); cfg.setDataStorageConfiguration(dataStorageConfiguration); CacheConfiguration ccfg = new CacheConfiguration(); ccfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL); ccfg.setName(DEFAULT_CACHE_NAME); ccfg.setBackups(1); cfg.setCacheConfiguration(ccfg); cfg.setFailureHandler(new StopNodeFailureHandler()); return cfg; }
Source:
public void sortingShouldWorkForEasyStrings() { assertSortedLike("", ""); assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); assertEquals(0, cmp("", "")); assertEquals(0, cmp("a", "a")); assertTrue(cmp("", "a") < 0); assertTrue(cmp("a", "") > 0); }

Target:
public void sortingShouldWorkForEasyStrings() { assertSortedLike("", ""); assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); }
Source:
private void addReporter(Class<? extends IReporter> r) { m_reporters.put(r, ClassHelper.newInstance(r)); }

Target:
private void addReporter(Class<? extends IReporter> r) { if (!m_reporters.containsKey(r)) { m_reporters.put(r, ClassHelper.newInstance(r)); } }
Source:
public ValidationResult validate(ConfigKey key, String value) { boolean result = true; String errMsg = null; Version version = new Version(key.getVersion()); if (Version.v3_3.compareTo(version) > 0) { result = false; errMsg = String.format("Device custom properties are not supported in version %s", version.toString()); } if (result && !DevicePropertiesUtils.getInstance().isDevicePropertiesDefinitionValid(value)) { result = false; errMsg = "Invalid syntax, custom device properties specification should conform to " + DevicePropertiesUtils.getInstance().getCustomDevicePropSpec(); } return new ValidationResult(result, errMsg); }

Target:
public ValidationResult validate(ConfigKey key, String value) { boolean result = true; String errMsg = null; if (isCustomDevicePropertiesSupported(key.getVersion())) { if (!DevicePropertiesUtils.getInstance().isDevicePropertiesDefinitionValid(value)) { result = false; errMsg = "Invalid syntax, custom device properties specification should conform to " + DevicePropertiesUtils.getInstance().getCustomDevicePropSpec(); } } else { result = false; errMsg = String.format("Device custom properties are not supported in version %s", key.getVersion()); } return new ValidationResult(result, errMsg); }
Source:
public void addToUserPostListingUri(@NonNull final Uri.Builder builder) { switch(this) { case HOT: case NEW: case RISING: case CONTROVERSIAL: builder.appendQueryParameter("sort", General.asciiLowercase(name())); break; case TOP_HOUR: case TOP_DAY: case TOP_WEEK: case TOP_MONTH: case TOP_YEAR: case TOP_ALL: final String parts[] = name().split("_"); builder.appendQueryParameter("sort", General.asciiLowercase(parts[0])); builder.appendQueryParameter("t", General.asciiLowercase(parts[1])); break; } }

Target:
public void addToUserPostListingUri(@NonNull final Uri.Builder builder) { switch(this) { case HOT: case NEW: case CONTROVERSIAL: builder.appendQueryParameter("sort", General.asciiLowercase(name())); break; case TOP_HOUR: case TOP_DAY: case TOP_WEEK: case TOP_MONTH: case TOP_YEAR: case TOP_ALL: final String parts[] = name().split("_"); builder.appendQueryParameter("sort", General.asciiLowercase(parts[0])); builder.appendQueryParameter("t", General.asciiLowercase(parts[1])); break; } }
Source:
public Promise<Transaction> cancel() { RetrofitPromise<Transaction> promise = new RetrofitPromise<>(); UserCardService userCardService = this.getBitreserveRestAdapter().create(UserCardService.class); if (this.getOrigin() == null || TextUtils.isEmpty(this.getOrigin().getCardId())) { promise.reject(new LogicException("Origin CardId is missing from this transaction")); return promise; } if (this.getStatus() == null){ promise.reject(new LogicException("Invalid transaction status")); return promise; } if (this.getStatus().compareTo("pending") == 0) { promise.reject(new LogicException("Unable to cancel uncommited transaction")); return promise; } if (this.getStatus().compareTo("waiting") != 0) { promise.reject(new LogicException(String.format("This transaction cannot be cancelled, because the current status is %s", this.getStatus()))); return promise; } userCardService.cancelTransaction(this.getOrigin().getCardId(), this.getId(), promise); return promise.then(new PromiseFunction<Transaction, Transaction>() { public Transaction call(Transaction transaction) { transaction.setBitreserveRestAdapter(Transaction.this.getBitreserveRestAdapter()); return transaction; } }); }

Target:
public Promise<Transaction> cancel() { RetrofitPromise<Transaction> promise = new RetrofitPromise<>(); UserCardService userCardService = this.getBitreserveRestAdapter().create(UserCardService.class); if (TextUtils.isEmpty(this.getOrigin().getCardId())) { promise.reject(new LogicException("Origin CardId is missing from this transaction")); return promise; } if (this.getStatus().compareTo("pending") == 0) { promise.reject(new LogicException("Unable to cancel uncommited transaction")); return promise; } if (this.getStatus().compareTo("waiting") != 0) { promise.reject(new LogicException(String.format("This transaction cannot be cancelled, because the current status is %s", this.getStatus()))); return promise; } userCardService.cancelTransaction(this.getOrigin().getCardId(), this.getId(), promise); return promise.then(new PromiseFunction<Transaction, Transaction>() { public Transaction call(Transaction transaction) { transaction.setBitreserveRestAdapter(Transaction.this.getBitreserveRestAdapter()); return transaction; } }); }
Source:
public static void registerConsumerChannel(Channel channel, ConnectionFactory connectionFactory) { if (logger.isDebugEnabled()) { logger.debug("Registering consumer channel" + channel); } consumerChannel.set(new ChannelHolder(channel, connectionFactory)); }

Target:
public static void registerConsumerChannel(Channel channel, ConnectionFactory connectionFactory) { if (logger.isDebugEnabled()) { logger.debug("Registering consumer channel" + channel + " from factory " + connectionFactory); } consumerChannel.set(new ChannelHolder(channel, connectionFactory)); }
Source:
public static Properties loadProperties(Class<?> clazz, String resource) throws IOException{ Properties prop = new Properties(); InputStream is = clazz.getResourceAsStream(resource); if(is.available() > 0) { prop.load(is); } return prop; }

Target:
public static Properties loadProperties(Class<?> clazz, String resource) throws IOException{ try(Reader is = new InputStreamReader(clazz.getResourceAsStream(resource), "UTF-8")) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException e) { throw new IOException( String.format("An error occurred while reading properties file: '%1$s'", resource) ); } }
Source:
protected void delete(Context context, UUID id) throws AuthorizeException, RepositoryMethodNotImplementedException { EPerson eperson = null; try { eperson = es.find(context, id); List<String> constraints = es.getDeleteConstraints(context, eperson); if (constraints != null && constraints.size() > 0) { throw new UnprocessableEntityException( "The eperson cannot be deleted due to the following constraints: " + StringUtils.join(constraints, ", ")); } } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } try { es.delete(context, eperson); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }

Target:
protected void delete(Context context, UUID id) throws AuthorizeException { EPerson eperson = null; try { eperson = es.find(context, id); List<String> constraints = es.getDeleteConstraints(context, eperson); if (constraints != null && constraints.size() > 0) { throw new UnprocessableEntityException( "The eperson cannot be deleted due to the following constraints: " + StringUtils.join(constraints, ", ")); } } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } try { es.delete(context, eperson); } catch (SQLException | IOException e) { throw new RuntimeException(e.getMessage(), e); } }
Source:
public Single<Event> getEventToSubmit(String eventUid, String teiUid) { return Single.fromCallable(() -> trackedEntityModule.trackedEntityDataValues.byEvent().eq(eventUid).get() ).map(values -> eventModule.events.byUid().eq(eventUid).one().get().toBuilder() .trackedEntityInstance(teiUid) .trackedEntityDataValues(values) .build() ); }

Target:
public Single<Event> getEventToSubmit(String eventUid, String teiUid) { return Single.fromCallable(() -> eventModule.events.withTrackedEntityDataValues() .byUid().eq(eventUid).one().get().toBuilder() .trackedEntityInstance(teiUid) .build() ); }
Source:
public String getApiToken() { LOGGER.log(Level.WARNING, "Deprecated usage of getApiToken"); return hasPermissionToSeeToken() ? getApiTokenInsecure() : Messages.ApiTokenProperty_ChangeToken_TokenIsHidden(); }

Target:
public String getApiToken() { LOGGER.log(Level.FINE, "Deprecated usage of getApiToken"); if(LOGGER.isLoggable(Level.FINER)){ LOGGER.log(Level.FINER, "Deprecated usage of getApiToken (trace)", new Exception()); } return hasPermissionToSeeToken() ? getApiTokenInsecure() : Messages.ApiTokenProperty_ChangeToken_TokenIsHidden(); }
Source:
BinaryData(byte[] data) { if (Objects.isNull(data)) { data = EMPTY_DATA; } this.data = Arrays.copyOf(data, data.length); }

Target:
BinaryData(byte[] data) { this.data = data; }
Source:
public void addNewPartition() throws JSONException { TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); PartitionLayout partitionLayout = new PartitionLayout(testHardwareLayout.getHardwareLayout()); ClusterMapManager clusterMapManager = new ClusterMapManager(partitionLayout); List<? extends PartitionId> partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 0); clusterMapManager.addNewPartition(testHardwareLayout.getIndependentDisks(6), 100 * 1024 * 1024 * 1024L); partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 1); PartitionId partitionId = partitionIds.get(0); assertEquals(partitionId.getReplicaIds().size(), 6); }

Target:
public void addNewPartition() throws JSONException { TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); PartitionLayout partitionLayout = new PartitionLayout(testHardwareLayout.getHardwareLayout()); ClusterMapManager clusterMapManager = new ClusterMapManager(partitionLayout); List<PartitionId> partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 0); clusterMapManager.addNewPartition(testHardwareLayout.getIndependentDisks(6), 100 * 1024 * 1024 * 1024L); partitionIds = clusterMapManager.getWritablePartitionIds(); assertEquals(partitionIds.size(), 1); PartitionId partitionId = partitionIds.get(0); assertEquals(partitionId.getReplicaIds().size(), 6); }
Source:
default void check() { checkArgument(SERVICE_NAME_REGEX.matcher(serviceName()).matches(), "Illegal service name format: %s", serviceName()); if (instanceId().isPresent()) { checkArgument(INSTANCE_ID_REGEX.matcher(instanceId().get()).matches(), "Illegal instance id format: %s", instanceId().get()); } checkArgument(VERSION_REGEX.matcher(version()).matches(), "Illegal version format: %s", version()); }

Target:
default void check() { checkArgument(SERVICE_NAME_REGEX.matcher(serviceName()).matches(), "Illegal service name format: %s", serviceName()); if (instanceId().isPresent()) { checkArgument(INSTANCE_ID_REGEX.matcher(instanceId().get()).matches(), "Illegal instance id format: %s", instanceId().get()); } checkArgument(isOrderableVersion(version()), "Illegal version format: %s", version()); }