auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method method : clazz.getDeclaredMethods()) { if (methods.containsKey(method.getName())) { methods.get(method.getName()).add(method); continue; } methods.put(method.getName(), new HashSet<Method>() {{add(method);}}); } Class<?> parent = clazz.getSuperclass(); while (null != parent) { methods.putAll(extractMethods(clazz, parent, methods)); parent = parent.getSuperclass(); } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }

Target:
public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method declaredMethod : clazz.getDeclaredMethods()) { Set<Method> declaredMethods = methods.get(declaredMethod.getName()); if (declaredMethods == null) { declaredMethods = Sets.newHashSet(); methods.put(declaredMethod.getName(), declaredMethods); } declaredMethods.add(declaredMethod); } Class<?> parent = clazz.getSuperclass(); while (null != parent) { Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet(); for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods){ Set<Method> m = methods.get(extractedMethod.getKey()); if (m == null) { methods.put(extractedMethod.getKey(), extractedMethod.getValue()); } else { m.addAll(extractedMethod.getValue()); } } parent = parent.getSuperclass(); } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }
Source:
public int seek(int dictId) { if (dimConversions == null) { return -1; } if (lastVal != -1) { if (dictId <= lastVal) { throw new ISE("Value dictId[%d] is less than the last value dictId[%d] I have, cannot be.", dictId, lastVal); } return -1; } if (currVal == -1) { currVal = dimConversions.get(); } if(currVal == dictId) { int ret = currIndex; ++currIndex; if (dimConversions.hasRemaining()) { currVal = dimConversions.get(); } else { lastVal = dictId; } return ret; } else if (currVal < dictId) { throw new ISE("Skipped currValue dictId[%d], currIndex[%d]; incoming value dictId[%d]", currVal, currIndex, dictId); } else { return -1; } }

Target:
public int seek(int dictId) { if (dimConversions == null) { return NOT_EXIST; } if (lastVal != NOT_INIT) { if (dictId <= lastVal) { throw new ISE("Value dictId[%d] is less than the last value dictId[%d] I have, cannot be.", dictId, lastVal ); } return NOT_EXIST; } if (currVal == NOT_INIT) { currVal = dimConversions.get(); } if (currVal == dictId) { int ret = currIndex; ++currIndex; if (dimConversions.hasRemaining()) { currVal = dimConversions.get(); } else { lastVal = dictId; } return ret; } else if (currVal < dictId) { throw new ISE("Skipped currValue dictId[%d], currIndex[%d]; incoming value dictId[%d]", currVal, currIndex, dictId ); } else { return NOT_EXIST; } }
Source:
private boolean readRulesAtBase() throws IOException { String path = basePath + "/.gitignore"; File f = new File(path); IgnoreNode n = new IgnoreNode(f.getParentFile()); path = basePath + "/.git/info/exclude"; f = new File(path); if (f.canRead()) { n.addSecondarySource(f); } ignoreMap.put(basePath, n); return true; }

Target:
private boolean readRulesAtBase() throws IOException { String path = basePath + "/.gitignore"; File f = new File(path); IgnoreNode n = new IgnoreNode(f.getParentFile()); path = basePath + "/.git/info/exclude"; f = new File(path); if (f.canRead()) n.addSecondarySource(f); ignoreMap.put(basePath, n); return true; }
Source:
public boolean exists(String name) { Preconditions.checkArgument(!Strings.isNullOrEmpty(name)); return assetManager.getAsset(name, Prefab.class).isPresent(); }

Target:
public boolean exists(String name) { if (Strings.isNullOrEmpty(name)) { return false; } return assetManager.getAsset(name, Prefab.class).isPresent(); }
Source:
public void edit(HostNetworkProviderModel model) { driver.edit(model); final NeutronAgentModel neutronAgentModel = model.getNeutronAgentModel(); neutronAgentWidget.edit(neutronAgentModel); neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity()); neutronAgentModel.isPluginConfigurationAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity())); model.getNetworkProviders().setIsChangeable(!model.getUseClusterDefaultNetworkProvider().getEntity()); model.getUseClusterDefaultNetworkProvider().getEntityChangedEvent().addListener((ev, sender, args) -> model.getNetworkProviders().setIsChangeable(!model.getUseClusterDefaultNetworkProvider().getEntity())); }

Target:
public void edit(HostNetworkProviderModel model) { driver.edit(model); final NeutronAgentModel neutronAgentModel = model.getNeutronAgentModel(); neutronAgentWidget.edit(neutronAgentModel); neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity()); neutronAgentModel.isPluginConfigurationAvailable().getEntityChangedEvent().addListener((ev, sender, args) -> neutronAgentPanel.setVisible(neutronAgentModel.isPluginConfigurationAvailable().getEntity())); }
Source:
public synchronized Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { return views.entrySet().stream() .filter(entry -> prefix.matches(entry.getKey())) .collect(ImmutableMap.toImmutableMap( Map.Entry::getKey, entry -> new ConnectorViewDefinition(entry.getKey(), Optional.empty(), entry.getValue()))); }

Target:
public synchronized Map<SchemaTableName, ConnectorViewDefinition> getViews(ConnectorSession session, SchemaTablePrefix prefix) { return views.entrySet().stream() .filter(entry -> prefix.matches(entry.getKey())) .collect(toImmutableMap( Map.Entry::getKey, entry -> new ConnectorViewDefinition(entry.getKey(), Optional.empty(), entry.getValue()))); }
Source:
public void run() { while (!Thread.interrupted()) { FSAppAttempt starvedApp; try{ starvedApp = context.getStarvedApps().take(); if (Resources.none().equals(starvedApp.getStarvation())) { continue; } } catch (InterruptedException e) { LOG.info("Preemption thread interrupted! Exiting."); return; } List<RMContainer> containers = identifyContainersToPreempt(starvedApp); if (containers != null) { preemptContainers(containers); } } }

Target:
public void run() { while (!Thread.interrupted()) { FSAppAttempt starvedApp; try{ starvedApp = context.getStarvedApps().take(); if (!Resources.isNone(starvedApp.getStarvation())) { List<RMContainer> containers = identifyContainersToPreempt(starvedApp); if (containers != null) { preemptContainers(containers); } } } catch (InterruptedException e) { LOG.info("Preemption thread interrupted! Exiting."); return; } } }
Source:
public void initialize(RealtimeContext context) throws Exception { uniqueKey = config.getKeyField(); outputFieldMap = config.getOutputFieldMap(); solrClient = config.getSolrConnection(); config.verifySolrConfiguration(); }

Target:
public void initialize(RealtimeContext context) throws Exception { keyField = config.getKeyField(); solrClient = config.getSolrConnection(); outputFieldMap = config.createOutputFieldMap(); metrics = context.getMetrics(); config.testSolrConnection(); }
Source:
public String revisionId(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); try { return builder.build().exactRef("HEAD").getObjectId().getName(); } catch (IOException e) { throw MessageException.of("I/O error while getting revision ID for path: " + path, e); } }

Target:
public String revisionId(Path path) { RepositoryBuilder builder = getVerifiedRepositoryBuilder(path); try { return builder.build().exactRef("HEAD").getObjectId().getName(); } catch (IOException e) { throw new IllegalStateException("I/O error while getting revision ID for path: " + path, e); } }
Source:
void add(Context context, Request currentRequest, WorkspaceItem source, String path, Object value) throws Exception { String[] split = path.split("/"); Item item = source.getItem(); List<Bundle> bundle = itemService.getBundles(item, Constants.CONTENT_BUNDLE_NAME);; for(Bundle bb : bundle) { int idx = 0; for(Bitstream b : bb.getBitstreams()) { if(idx==Integer.parseInt(split[0])) { addValue(context, b, split[2], evaluateObject((LateObjectEvaluator)value)); } idx++; } } }

Target:
void add(Context context, Request currentRequest, WorkspaceItem source, String path, Object value) throws Exception { String[] split = getAbsolutePath(path).split("/"); Item item = source.getItem(); List<Bundle> bundle = itemService.getBundles(item, Constants.CONTENT_BUNDLE_NAME);; for(Bundle bb : bundle) { int idx = 0; for(Bitstream b : bb.getBitstreams()) { if(idx==Integer.parseInt(split[1])) { if (split.length == 4) { List<MetadataValueRest> list = evaluateArrayObject((LateObjectEvaluator) value); replaceValue(context, b, split[3], list); } else { MetadataValueRest object = evaluateSingleObject((LateObjectEvaluator) value); List<MetadataValue> metadataByMetadataString = bitstreamService.getMetadataByMetadataString(b, split[3]); Assert.notEmpty(metadataByMetadataString); if (split.length > 4) { String controlChar = split[4]; switch (controlChar) { case "-": addValue(context, b, split[3], object, -1); break; default: int index = Integer.parseInt(controlChar); if (index > metadataByMetadataString.size()) { throw new IllegalArgumentException( "The specified index MUST NOT be greater than the number of elements in the array"); } addValue(context, b, split[3], object, index); break; } } } } idx++; } } }
Source:
private boolean notRedirect(HttpServletRequest req) { String refererValue = req.getHeader("Referer"); return (refererValue != null && (refererValue.contains( "host_id=" ) || refererValue.contains( "fromAngular=true" ) || refererValue.contains( "dotAdmin" ) || refererValue.contains( "p_p_id=site-browser"))); }

Target:
private boolean notRedirect(HttpServletRequest req) { String refererValue = req.getHeader(Constants.REFERER_URL_HTTP_HEADER); return (refererValue != null && (refererValue.contains( "host_id=" ) || refererValue.contains( "fromAngular=true" ) || refererValue.contains(PortletURLUtil.URL_ADMIN_PREFIX ) || refererValue.contains( "p_p_id=" + PortletID.SITE_BROWSER ))); }
Source:
public void schedulePasswordReminderJob() { CronSchedulableJob job = new CronSchedulableJob(new MotechEvent(PASSWORD_EXPIRATION_CHECK_EVENT), "0 * * * * ? *"); schedulerService.safeScheduleJob(job); }

Target:
public void schedulePasswordReminderJob() { CronSchedulableJob job = new CronSchedulableJob(new MotechEvent(PASSWORD_EXPIRATION_CHECK_EVENT), "0 0 0 * * ? *"); schedulerService.safeScheduleJob(job); }
Source:
public static byte[] getBytesNoPaddingfromList(List<Integer> list, int maxValue) { int numBytes = getNumBytesForMax(maxValue); final ByteBuffer buffer = ByteBuffer.allocate((list.size() * numBytes)); int i = 0; for (Integer val : list) { if (val < 0) { throw new IAE("integer values must be positive, got[%d], i[%d]", val, i); } if (val > maxValue) { throw new IAE("val[%d] > maxValue[%d], please don't lie about maxValue. i[%d]", val, maxValue, i); } byte[] intAsBytes = Ints.toByteArray(val); buffer.put(intAsBytes, intAsBytes.length - numBytes, numBytes); ++i; } buffer.position(0); return buffer.array(); }

Target:
public static byte[] getBytesNoPaddingfromList(List<Integer> list, int maxValue) { int numBytes = getNumBytesForMax(maxValue); final ByteBuffer buffer = ByteBuffer.allocate((list.size() * numBytes)); writeToBuffer(buffer, list, numBytes, maxValue); return buffer.array(); }
Source:
public void detectsSplitPpv1Message() { EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler( true)); ByteBuf buf1 = Unpooled.wrappedBuffer( "PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); ByteBuf buf2 = Unpooled.wrappedBuffer( "192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf2); Object msg = channel.readInbound(); assertTrue(msg instanceof HAProxyMessage); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.class)); }

Target:
public void detectsSplitPpv1Message() { EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(true)); ByteBuf buf1 = Unpooled.wrappedBuffer( "PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); ByteBuf buf2 = Unpooled.wrappedBuffer( "192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf2); Object msg = channel.readInbound(); assertTrue(msg instanceof HAProxyMessage); buf1.release(); buf2.release(); ((HAProxyMessage) msg).release(); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.class)); }
Source:
protected Fragment getFragment(int position) { final IssueMilestoneListFragment f = IssueMilestoneListFragment.newInstance(mRepoOwner, mRepoName, position == 1); if (position != 1) { mOpenFragment = f; } return f; }

Target:
protected Fragment getFragment(int position) { final IssueMilestoneListFragment f = IssueMilestoneListFragment.newInstance(mRepoOwner, mRepoName, position == 1); if (position == 0) { mOpenFragment = f; } return f; }
Source:
public void configure(SpringProcessEngineConfiguration processEngineConfiguration){ processEngineConfiguration.setActivityBehaviorFactory(new DefaultActivityBehaviorFactoryMapping(processExtensionService,processVariablesInitiator)); }

Target:
public void configure(SpringProcessEngineConfiguration processEngineConfiguration){ processEngineConfiguration.setActivityBehaviorFactory(new MappingAwareActivityBehaviorFactory(variablesMappingProvider, processVariablesInitiator)); }
Source:
private void deleteChannel (ChannelInfoItem selectedItem) { ExtractorHelper.getChannelInfo(selectedItem.getServiceId(), selectedItem.getUrl(), true) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.newThread()) .subscribe((@NonNull ChannelInfo result) -> { List<SubscriptionEntity> toDelete = subscriptionService.subscriptionTable() .getSubscription(result.getServiceId(), result.getUrl()) .blockingFirst(); subscriptionService.subscriptionTable().delete(toDelete); }); }

Target:
private void deleteChannel (ChannelInfoItem selectedItem) { subscriptionService.subscriptionTable() .getSubscription(selectedItem.getServiceId(), selectedItem.getUrl()) .toObservable() .observeOn(Schedulers.io()) .subscribe(getDeleteObserver()); Toast.makeText(activity, getString(R.string.channel_unsubscribed), Toast.LENGTH_SHORT).show(); }
Source:
protected <T> Transform<Throwable, T> handleVersionConflict( Provider<T> emptyProvider, Runnable reportWriteDroppedByDuplicate ) { return throwable -> { if (throwable.getMessage().contains("version conflict")) { reportWriteDroppedByDuplicate.run(); return emptyProvider.get(); } throw new RuntimeException(throwable); }; }

Target:
protected <T> Transform<Throwable, T> handleVersionConflict( Provider<T> emptyProvider, Runnable reportWriteDroppedByDuplicate ) { return throwable -> { if (ExceptionUtils.getRootCause(throwable) instanceof VersionConflictEngineException || throwable.getMessage().contains("version_conflict_engine_exception")) { reportWriteDroppedByDuplicate.run(); return emptyProvider.get(); } throw new RuntimeException(throwable); }; }
Source:
public int getItemCount() { if (mNavigationItems != null) { return mNavigationItems.size(); } else { return mServerName.size(); } }

Target:
public int getItemCount() { return mNavigationItems != null ? mNavigationItems.size() : mServerName.size(); }
Source:
private static String getAltFromHgvs(String hgvs, Type type) { if (!type.equals(Type.DELETION)) return getPattern("(?<=[a-z+>])[ATCG]+$", hgvs); String alt = getPattern("(?<=[a-z+>])[ATCG]*$", hgvs); if (alt.equals(null)) return ""; String ans = ""; while (ans.length() < alt.length()) ans += "X"; return ans; }

Target:
private static String getAltFromHgvs(String hgvs, Type type) { if (!type.equals(Type.DELETION)) { return getPattern("(?<=[a-z+>])[ATCG]+$", hgvs); } String alt = getPattern("(?<=[a-z+>])[ATCG]*$", hgvs); if (alt.equals(null)) { return ""; } String ans = ""; while (ans.length() < alt.length()) { ans += "X"; } return ans; }
Source:
public long save(Study study) throws IOException { if (study.getId() == StudyImpl.UNSAVED_ID) { study.setLastModifier(authorizationManager.getCurrentUser()); return studyStore.save(study); } else { Study original = studyStore.get(study.getId()); authorizationManager.throwIfNotWritable(original); original.setAccession(study.getAccession()); original.setAlias(study.getAlias()); original.setDescription(study.getDescription()); original.setLastModifier(authorizationManager.getCurrentUser()); original.setStudyType(studyStore.getType(original.getStudyType().getId())); return studyStore.save(original); } }

Target:
public long save(Study study) throws IOException { if (study.getId() == StudyImpl.UNSAVED_ID) { study.setLastModifier(authorizationManager.getCurrentUser()); study.setStudyType(studyStore.getType(study.getStudyType().getId())); study.setProject(projectStore.get(study.getProject().getId())); study.setName(LimsUtils.generateTemporaryName()); long id = studyStore.save(study); try { study.setName(namingScheme.generateNameFor(study)); LimsUtils.validateNameOrThrow(study, namingScheme); studyStore.save(study); } catch (MisoNamingException e) { throw new IOException(e); } return id; } else { Study original = studyStore.get(study.getId()); authorizationManager.throwIfNotWritable(original); original.setAccession(study.getAccession()); original.setAlias(study.getAlias()); original.setDescription(study.getDescription()); original.setLastModifier(authorizationManager.getCurrentUser()); original.setStudyType(studyStore.getType(study.getStudyType().getId())); return studyStore.save(original); } }
Source:
public void testRepairAfterIncompleteCompaction() throws Exception { PartitionId partitionId = new MockPartitionId(testPartition, MockClusterMap.DEFAULT_PARTITION_CLASS); BlobId blobId = new BlobId(BLOB_ID_V6, BlobIdType.NATIVE, dataCenterId, accountId, containerId, partitionId, false, BlobDataType.DATACHUNK); InputStream inputStream = getBlobInputStream(blobSize); long now = System.currentTimeMillis(); CloudBlobMetadata cloudBlobMetadata = new CloudBlobMetadata(blobId, now, -1, blobSize, CloudBlobMetadata.EncryptionOrigin.NONE); uploadBlobWithRetry(blobId, blobSize, cloudBlobMetadata, inputStream); long deletionTime = now - TimeUnit.DAYS.toMillis(7); assertTrue("Expected delete to return true", azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator)); azureDest.getAzureBlobDataAccessor().purgeBlobs(Collections.singletonList(cloudBlobMetadata)); try { assertFalse("Expected delete to return false", azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator)); } catch (CloudStorageException cex) { assertEquals("Unexpected error code", HttpConstants.StatusCodes.NOTFOUND, cex.getStatusCode()); } assertNull("Expected record to be purged from Cosmos", azureDest.getCosmosDataAccessor().getMetadataOrNull(blobId)); }

Target:
public void testRepairAfterIncompleteCompaction() throws Exception { PartitionId partitionId = new MockPartitionId(testPartition, MockClusterMap.DEFAULT_PARTITION_CLASS); BlobId blobId = new BlobId(BLOB_ID_V6, BlobIdType.NATIVE, dataCenterId, accountId, containerId, partitionId, false, BlobDataType.DATACHUNK); InputStream inputStream = getBlobInputStream(blobSize); long now = System.currentTimeMillis(); CloudBlobMetadata cloudBlobMetadata = new CloudBlobMetadata(blobId, now, -1, blobSize, CloudBlobMetadata.EncryptionOrigin.NONE); uploadBlobWithRetry(blobId, blobSize, cloudBlobMetadata, inputStream); long deletionTime = now - TimeUnit.DAYS.toMillis(7); assertTrue("Expected delete to return true", azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator)); azureDest.getAzureBlobDataAccessor().purgeBlobs(Collections.singletonList(cloudBlobMetadata)); try { azureDest.deleteBlob(blobId, deletionTime, (short) 0, dummyCloudUpdateValidator); } catch (CloudStorageException cex) { assertEquals("Unexpected error code", HttpConstants.StatusCodes.NOTFOUND, cex.getStatusCode()); } assertNull("Expected record to be purged from Cosmos", azureDest.getCosmosDataAccessor().getMetadataOrNull(blobId)); }
Source:
private void updateGuideStarAdders() { final boolean onlyAutoGroup = getContextTargetEnv().getGroups().size() == 1; final boolean enabled = onlyAutoGroup || selectionIsManualGroup() || selectionIsManualTarget(); _guideStarAdders.forEach((gp, comp) -> comp.setEnabled(enabled)); }

Target:
private void updateGuideStarAdders() { final boolean onlyAutoGroup = getContextTargetEnv().getGuideEnvironment().manualGroups().isEmpty(); final boolean enabled = onlyAutoGroup || selectionIsManualGroup() || selectionIsManualTarget(); _guideStarAdders.forEach((gp, comp) -> comp.setEnabled(enabled)); }
Source:
void setupDefaultHandlers() { domElementContainer.addDomHandler(new ScrollHandler() { @Override public void onScroll(final ScrollEvent scrollEvent) { domElementContainer.getElement().setScrollTop(0); domElementContainer.getElement().setScrollLeft(0); } }, ScrollEvent.getType()); addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(final AttachEvent event) { if (event.isAttached()) { onResize(); } } }); addMouseDownHandler((e) -> setFocus(true)); }

Target:
protected void setupDefaultHandlers() { domElementContainer.addDomHandler(new ScrollHandler() { @Override public void onScroll(final ScrollEvent scrollEvent) { domElementContainer.getElement().setScrollTop(0); domElementContainer.getElement().setScrollLeft(0); } }, ScrollEvent.getType()); addAttachHandler(new AttachEvent.Handler() { @Override public void onAttachOrDetach(final AttachEvent event) { if (event.isAttached()) { onResize(); } } }); addMouseDownHandler((e) -> setFocus(true)); }
Source:
public static void assertThenRelease(final Response actual, final Matcher<Response> matcher) { try { MatcherAssert.assertThat(actual, matcher); } finally { if(actual != null) { actual.release(); } } }

Target:
public static void assertThenRelease(final Response actual, final Matcher<Response> matcher) { try { MatcherAssert.assertThat(actual, matcher); } finally { RequestFacade.releaseResponse(actual); } }
Source:
public ITmfStateProvider getNewInstance() { return new KernelMemoryStateProvider(this.getTrace(), this.fLayout); }

Target:
public ITmfStateProvider getNewInstance() { return new KernelMemoryStateProvider(getTrace(), fLayout); }
Source:
private Language saveOrUpdateLanguage(final String languageId, final LanguageForm form) { final Language newLanguage = new Language(); if (StringUtils.isSet(languageId)) { try { final Language origLanguage = this.languageAPI.getLanguage(languageId); BeanUtils.copyProperties(newLanguage, origLanguage); } catch (Exception e) { Logger.debug(this.getClass(), () -> "Unable to find language with id:" + languageId); throw new DoesNotExistException(e.getMessage(), e); } } newLanguage.setLanguageCode(form.getLanguageCode()); newLanguage.setLanguage(form.getLanguage()); newLanguage.setCountryCode(form.getCountryCode()); newLanguage.setCountry(form.getCountry()); this.languageAPI.saveLanguage(newLanguage); return newLanguage; }

Target:
private Language saveOrUpdateLanguage(final String languageId, final LanguageForm form) { final Language newLanguage = new Language(); if (StringUtils.isSet(languageId)) { final Language origLanguage = this.languageAPI.getLanguage(languageId); Sneaky.sneaked(()->BeanUtils.copyProperties(newLanguage, origLanguage)); } newLanguage.setLanguageCode(form.getLanguageCode()); newLanguage.setLanguage(form.getLanguage()); newLanguage.setCountryCode(form.getCountryCode()); newLanguage.setCountry(form.getCountry()); this.languageAPI.saveLanguage(newLanguage); return newLanguage; }
Source:
public void testAssumptionFailure( Failure failure ) { this.reporter.testAssumptionFailure( SimpleReportEntry.ignored( getClassName( failure.getDescription() ) , failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( Boolean.TRUE ); }

Target:
public void testAssumptionFailure( Failure failure ) { reporter.testAssumptionFailure( new SimpleReportEntry( getClassName( failure.getDescription() ) , failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( true ); }
Source:
public static String getGetFeatureInfoUrlForProxy(String url, String projection, String bbox, String width, String height, String x, String y, String layerName) { String wmsUrl = url+"?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&SRS="+projection +"&BBOX="+bbox +"&WIDTH="+width +"&HEIGHT="+height +"&QUERY_LAYERS="+layerName +"&X="+Math.round(Float.parseFloat(x)) +"&Y="+Math.round(Float.parseFloat(y)) +"&LAYERS="+layerName +"&FEATURECOUNT=1" +"&INFO_FORMAT=application/json" +"&EXCEPTIONS=application/vnd.ogc.se_xml" +"&BUFFER=0"; return wmsUrl; }

Target:
public static String getGetFeatureInfoUrlForProxy(String url, String projection, String bbox, String width, String height, String x, String y, String layerName) { Map<String, String> urlParams = new HashMap<String, String>(); urlParams.put("SERVICE", "WMS"); urlParams.put("VERSION", "1.1.1"); urlParams.put("REQUEST", "GetFeatureInfo"); urlParams.put("SRS", projection); urlParams.put("BBOX", bbox); urlParams.put("WIDTH", width); urlParams.put("HEIGHT", height); urlParams.put("QUERY_LAYERS", layerName); urlParams.put("X", Long.toString(Math.round(Float.parseFloat(x)))); urlParams.put("Y", Long.toString(Math.round(Float.parseFloat(y)))); urlParams.put("LAYERS", layerName); urlParams.put("FEATURECOUNT", "1"); urlParams.put("INFO_FORMAT", "application/json"); urlParams.put("EXCEPTIONS", "application/vnd.ogc.se_xml"); urlParams.put("BUFFER", "0"); return IOHelper.constructUrl(url, urlParams); }
Source:
public static Trace getAndClearTrace() { Trace trace = currentTrace.get(); currentTrace.remove(); return trace; }

Target:
public static Trace getAndClearTrace() { Trace trace = currentTrace.get(); currentTrace.remove(); MDC.remove(Tracers.TRACE_ID_KEY); return trace; }
Source:
private static Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } final StringBuilder selection = new StringBuilder(); selection.append(" detailed = 1 "); String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } selection.append(" and geocode in (SELECT geocode FROM " + dbTableCachesLists + " WHERE list_id "); selection.append(listId != PseudoList.ALL_LIST.id ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID); selection.append(")"); try { if (coords != null) { return queryToColl(dbTableCaches, new String[]{"geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) + ") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif"}, selection.toString(), selectionArgs, "dif", null, new HashSet<String>(), GET_STRING_0); } return queryToColl(dbTableCaches, new String[] { "geocode" }, selection.toString(), selectionArgs, "geocode", null, new HashSet<String>(), GET_STRING_0); } catch (final Exception e) { Log.e("DataStore.loadBatchOfStoredGeocodes", e); return Collections.emptySet(); } }

Target:
private static Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } final StringBuilder selection = new StringBuilder(); selection.append(" detailed = 1 "); String[] selectionArgs = null; if (cacheType != CacheType.ALL) { selection.append(" and type = ?"); selectionArgs = new String[] { String.valueOf(cacheType.id) }; } selection.append(" and geocode in (SELECT geocode FROM "); selection.append(dbTableCachesLists); selection.append(" WHERE list_id "); selection.append(listId != PseudoList.ALL_LIST.id ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID); selection.append(")"); try { if (coords != null) { return queryToColl(dbTableCaches, new String[]{"geocode", "(abs(latitude-" + String.format((Locale) null, "%.6f", coords.getLatitude()) + ") + abs(longitude-" + String.format((Locale) null, "%.6f", coords.getLongitude()) + ")) as dif"}, selection.toString(), selectionArgs, "dif", null, new HashSet<String>(), GET_STRING_0); } return queryToColl(dbTableCaches, new String[] { "geocode" }, selection.toString(), selectionArgs, "geocode", null, new HashSet<String>(), GET_STRING_0); } catch (final Exception e) { Log.e("DataStore.loadBatchOfStoredGeocodes", e); return Collections.emptySet(); } }
Source:
static void createModelsRunner(String buildingModelId, String floorModelId, String hvacModelId, String wardModelId, Consumer<List<String>> createModelsTestRunner) { String modelBuilding = TestAssetsHelper.getBuildingModelPayload(buildingModelId, hvacModelId, floorModelId); String modelHvac = TestAssetsHelper.getHvacModelPayload(hvacModelId, floorModelId); String modelWard = TestAssetsHelper.getWardModelPayload(wardModelId); List<String> modelsList = new ArrayList<>(); modelsList.add(modelBuilding); modelsList.add(modelHvac); modelsList.add(modelWard); createModelsTestRunner.accept(modelsList); }

Target:
static void createModelsRunner(String buildingModelId, String floorModelId, String hvacModelId, String wardModelId, Consumer<List<String>> createModelsTestRunner) { String modelBuilding = TestAssetsHelper.getBuildingModelPayload(buildingModelId, hvacModelId, floorModelId); String modelHvac = TestAssetsHelper.getHvacModelPayload(hvacModelId, floorModelId); String modelWard = TestAssetsHelper.getWardModelPayload(wardModelId); List<String> modelsList = new ArrayList<>(Arrays.asList(modelBuilding, modelHvac, modelWard)); createModelsTestRunner.accept(modelsList); }
Source:
public Class<? extends Writable> getSerializedClass() { LOG.debug("********" + Thread.currentThread().getStackTrace()[1].getMethodName()); return ExecRowWritable.class; }

Target:
public Class<? extends Writable> getSerializedClass() { if (LOG.isDebugEnabled()) LOG.debug("********" + Thread.currentThread().getStackTrace()[1].getMethodName()); return ExecRowWritable.class; }
Source:
private static boolean waitAuthServerReady() throws InterruptedException { int retryTimes = 50; Request request = new Request.Builder() .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "")) .url(Constants.AUTH_URL) .build(); while (retryTimes != 0) { Response response = null; try { response = client.newCall(request).execute(); if (response.code() == 400) { return true; } RealmLog.error("Error response from auth server: %s", response.toString()); } catch (IOException e) { Thread.sleep(100); } finally { if (response != null) { response.close(); } } retryTimes--; } return false; }

Target:
private static boolean waitAuthServerReady() throws InterruptedException { int retryTimes = 20; Request request = new Request.Builder() .url(Constants.AUTH_SERVER_URL) .build(); while (retryTimes != 0) { Response response = null; try { response = client.newCall(request).execute(); if (response.isSuccessful()) { return true; } RealmLog.error("Error response from auth server: %s", response.toString()); } catch (IOException e) { RealmLog.error(e); Thread.sleep(500); } finally { if (response != null) { response.close(); } } retryTimes--; } return false; }
Source:
public void testConnectorRestartCalled() { Properties props = new Properties(); props.setProperty("daemonThreadIntervalInSeconds", "1"); TestKafkaConnector connector = new TestKafkaConnector(false, props); DatastreamTask datastreamTask = new DatastreamTaskImpl(); connector.onAssignmentChange(Collections.singletonList(datastreamTask)); connector.start(null); PollUtils.poll(() -> connector.getCreateTaskCalled() >= 3, Duration.ofSeconds(1).toMillis(), Duration.ofSeconds(10).toMillis()); Assert.assertTrue(connector.getCreateTaskCalled() >= 3); Gauge<Long> metric = DynamicMetricsManager.getInstance() .getMetric("test" + "." + TestKafkaConnector.class.getSimpleName() + "." + "numTaskRestarts"); Assert.assertNotNull(metric); Assert.assertEquals(metric.getValue(), Long.valueOf(1)); MetricsTestUtils.verifyMetrics(connector, DynamicMetricsManager.getInstance()); connector.stop(); }

Target:
public void testConnectorRestartCalled() { Properties props = new Properties(); props.setProperty("daemonThreadIntervalInSeconds", "1"); TestKafkaConnector connector = new TestKafkaConnector(false, props); DatastreamTask datastreamTask = new DatastreamTaskImpl(); connector.onAssignmentChange(Collections.singletonList(datastreamTask)); connector.start(null); PollUtils.poll(() -> connector.getCreateTaskCalled() >= 3, Duration.ofSeconds(1).toMillis(), Duration.ofSeconds(10).toMillis()); Assert.assertTrue(connector.getCreateTaskCalled() >= 3); Gauge<Long> metric = DynamicMetricsManager.getInstance() .getMetric("test" + "." + TestKafkaConnector.class.getSimpleName() + "." + "numTaskRestarts"); Assert.assertNotNull(metric); Assert.assertEquals(metric.getValue(), Long.valueOf(1)); MetricsTestUtils.verifyMetrics(connector, DynamicMetricsManager.getInstance(), s -> s.startsWith("test")); connector.stop(); }
Source:
public TaskResult cleanup(TaskRequest request) { final Path projectPath = workspace.getProjectPath(); final CommandContext commandContext = buildCommandContext(projectPath); final long attemptId = request.getAttemptId(); final long taskId = request.getTaskId(); Config state = TaskState.of(request).params(); if (state.has("commandStatus")) { logger.debug(String.format("Starting cleanup: attemptId=%d, taskId=%d", attemptId, taskId)); try { exec.cleanup(commandContext, state); } catch (IOException ex) { throw Throwables.propagate(ex); } } return TaskResult.empty(request); }

Target:
public void cleanup(TaskRequest request) { final Path projectPath = workspace.getProjectPath(); final CommandContext commandContext = buildCommandContext(projectPath); final long attemptId = request.getAttemptId(); final long taskId = request.getTaskId(); Config state = TaskState.of(request).params(); if (state.has("commandStatus")) { logger.debug(String.format("Starting cleanup: attemptId=%d, taskId=%d", attemptId, taskId)); try { exec.cleanup(commandContext, state); } catch (Throwable e) { throw Throwables.propagate(e); } } }
Source:
public ExecutableFlow getExecutableFlow(int execId) throws ExecutorManagerException { if (runningFlows.containsKey(execId)) { return runningFlows.get(execId).getSecond(); } else if (queuedFlowMap.containsKey(execId)) { return queuedFlowMap.get(execId).getSecond(); } else { return executorLoader.fetchExecutableFlow(execId); } }

Target:
public ExecutableFlow getExecutableFlow(int execId) throws ExecutorManagerException { if (runningFlows.containsKey(execId)) { return runningFlows.get(execId).getSecond(); } else if (queuedFlows.hasExecution(execId)) { return queuedFlows.getFlow(execId); } else { return executorLoader.fetchExecutableFlow(execId); } }
Source:
public void setStartFinishTime(long time0, long time1) { synchronized (fListenerNotifierLock) { if (fListenerNotifier != null && fListenerNotifier.hasTimeRangeUpdated()) { return; } } fTime0 = time0; if (fTime0 < fTime0Bound) { fTime0 = fTime0Bound; } if (fTime0 > fTime1Bound) { fTime0 = fTime1Bound; } fTime1 = time1; if (fTime1 < fTime0Bound) { fTime1 = fTime0Bound; } if (fTime1 > fTime1Bound) { fTime1 = fTime1Bound; } if (fTime1 - fTime0 < fMinTimeInterval) { fTime1 = Math.min(fTime1Bound, fTime0 + fMinTimeInterval); } fTimeRangeFixed = true; adjustHorizontalScrollBar(); fTimeGraphCtrl.redraw(); fTimeScaleCtrl.redraw(); }

Target:
public void setStartFinishTime(long time0, long time1) { if (fListenerNotifier != null && fListenerNotifier.hasTimeRangeUpdated()) { return; } fTime0 = time0; if (fTime0 < fTime0Bound) { fTime0 = fTime0Bound; } if (fTime0 > fTime1Bound) { fTime0 = fTime1Bound; } fTime1 = time1; if (fTime1 < fTime0Bound) { fTime1 = fTime0Bound; } if (fTime1 > fTime1Bound) { fTime1 = fTime1Bound; } if (fTime1 - fTime0 < fMinTimeInterval) { fTime1 = Math.min(fTime1Bound, fTime0 + fMinTimeInterval); } fTimeRangeFixed = true; adjustHorizontalScrollBar(); fTimeGraphCtrl.redraw(); fTimeScaleCtrl.redraw(); }
Source:
private Plugin loadPlugin(File jarFile) throws IOException, ClassNotFoundException { Manifest jarManifest = new JarFile(jarFile).getManifest(); ClassLoader parentLoader = PluginLoader.class.getClassLoader(); ClassLoader jarClassLoader = URLClassLoader.newInstance(getPluginURLs(jarFile), parentLoader); Attributes attrs = jarManifest.getMainAttributes(); String pluginName = attrs.getValue("Gerrit-Plugin"); String moduleName = attrs.getValue("Gerrit-SshModule"); Class<?> moduleClass = Class.forName(moduleName, false, jarClassLoader); return new Plugin(pluginName, moduleClass); }

Target:
private Plugin loadPlugin(File jarFile) throws IOException, ClassNotFoundException { Manifest jarManifest = new JarFile(jarFile).getManifest(); ClassLoader parentLoader = PluginLoader.class.getClassLoader(); ClassLoader jarClassLoader = new URLClassLoader(getPluginURLs(jarFile), parentLoader); Attributes attrs = jarManifest.getMainAttributes(); String pluginName = attrs.getValue("Gerrit-Plugin"); String moduleName = attrs.getValue("Gerrit-SshModule"); Class<?> moduleClass = Class.forName(moduleName, false, jarClassLoader); return new Plugin(pluginName, moduleClass); }
Source:
private RelCollation extendCollation(RelCollation collation, List<Integer> keys) { List<RelFieldCollation> fieldsForNewCollation = new ArrayList<>(keys.size()); fieldsForNewCollation.addAll(collation.getFieldCollations()); Set<Integer> keySet = new HashSet<>(keys); for (RelFieldCollation rf : collation.getFieldCollations()) { keySet.remove(rf.getFieldIndex()); } for (Integer i : keySet) { fieldsForNewCollation.add(new RelFieldCollation(i)); } return RelCollations.of(fieldsForNewCollation); }

Target:
private RelCollation extendCollation(RelCollation collation, List<Integer> keys) { List<RelFieldCollation> fieldsForNewCollation = new ArrayList<>(keys.size()); fieldsForNewCollation.addAll(collation.getFieldCollations()); ImmutableBitSet keysBitset = ImmutableBitSet.of(keys); ImmutableBitSet colKeysBitset = ImmutableBitSet.of(collation.getKeys()); ImmutableBitSet exceptBitset = keysBitset.except(colKeysBitset); for (Integer i : exceptBitset.toList()) { fieldsForNewCollation.add(new RelFieldCollation(i)); } return RelCollations.of(fieldsForNewCollation); }
Source:
public GrpcBackedQueryUpdateMessage(QueryUpdate queryUpdate, Serializer serializer) { this.queryUpdate = queryUpdate; this.serializedPayload = queryUpdate.hasPayload() ? new LazyDeserializingObject<>(new GrpcSerializedObject(queryUpdate.getPayload()), serializer) : null; Supplier<Object> details = serializedPayload == null ? () -> null : serializedPayload::getObject; this.exception = queryUpdate.hasErrorMessage() ? ErrorCode.getFromCode(queryUpdate.getErrorCode()) .convert(queryUpdate.getErrorMessage(), details) : null; this.metaDataSupplier = new GrpcMetaData(queryUpdate.getMetaDataMap(), serializer); }

Target:
public GrpcBackedQueryUpdateMessage(QueryUpdate queryUpdate, Serializer serializer) { this.queryUpdate = queryUpdate; this.serializedPayload = queryUpdate.hasPayload() ? new LazyDeserializingObject<>(new GrpcSerializedObject(queryUpdate.getPayload()), serializer) : null; Supplier<Object> exceptionDetails = serializedPayload == null ? () -> null : serializedPayload::getObject; this.exception = queryUpdate.hasErrorMessage() ? ErrorCode.getFromCode(queryUpdate.getErrorCode()) .convert(queryUpdate.getErrorMessage(), exceptionDetails) : null; this.metaDataSupplier = new GrpcMetaData(queryUpdate.getMetaDataMap(), serializer); }
Source:
protected String defineClassNameField(String modelFieldClassName, Map<String, String> superTypesMap) { if (SIMPLE_CLASSES_MAP.containsKey(modelFieldClassName)) { return SIMPLE_CLASSES_MAP.get(modelFieldClassName).getCanonicalName(); } if (ScenarioSimulationSharedUtils.isEnum(superTypesMap.get(modelFieldClassName))) { return getFQCNByFactName(modelFieldClassName); } return modelFieldClassName; }

Target:
protected String defineClassNameField(String modelFieldClassName, Map<String, String> superTypesMap) { if (SIMPLE_CLASSES_MAP.containsKey(modelFieldClassName)) { return SIMPLE_CLASSES_MAP.get(modelFieldClassName).getCanonicalName(); } if (ScenarioSimulationSharedUtils.isEnumCanonicalName(superTypesMap.get(modelFieldClassName))) { return getFQCNByFactName(modelFieldClassName); } return modelFieldClassName; }
Source:
public Mono<Void> runAsync() { return dataLakeFileAsyncClient.append(createRandomByteBufferFlux(options.getSize()), 0, options.getSize()); }

Target:
public Mono<Void> runAsync() { return dataLakeFileAsyncClient.append(byteBufferFlux, 0, options.getSize()); }
Source:
private PretendSlave createPretendSlave(String slaveName) throws Exception { PretendSlave slave = new PretendSlave(slaveName, this.createTmpDir().getPath(), "", createComputerLauncher(null), new NoopFakeLaunher()); hudson.addNode(slave); return slave; }

Target:
private PretendSlave createPretendSlave(String slaveName) throws Exception { PretendSlave slave = new PretendSlave(slaveName, this.createTmpDir().getPath(), "", createComputerLauncher(null), new NoopFakeLauncher()); hudson.addNode(slave); return slave; }
Source:
public UpdatePasswordResponse resetPassword(@RequestBody final ResetPasswordRequest request) throws UserRetrievalException { UpdatePasswordResponse response = new UpdatePasswordResponse(); UserDTO currUser = userManager.getByName(request.getUserName()); if (currUser == null) { throw new UserRetrievalException("The user with id " + Util.getCurrentUser().getId() + " could not be found or the logged in user does not have permission to modify their data."); } Strength strength = userManager.getPasswordStrength(currUser, request.getNewPassword()); if (strength.getScore() < UserManager.MIN_PASSWORD_STRENGTH) { LOGGER.info("Strength results: [warning: {}] [suggestions: {}] [score: {}] [worst case crack time: {}]", strength.getFeedback().getWarning(), strength.getFeedback().getSuggestions().toString(), strength.getScore(), strength.getCrackTimesDisplay().getOfflineFastHashing1e10PerSecond()); response.setStrength(strength); response.setPasswordUpdated(false); return response; } if(userManager.authorizePasswordReset(request.getToken())){ userManager.updateUserPassword(currUser.getSubjectName(), request.getNewPassword()); userManager.deletePreviousTokens(request.getToken()); response.setPasswordUpdated(true); } else { response.setPasswordUpdated(false); } return response; }

Target:
public UpdatePasswordResponse resetPassword(@RequestBody final ResetPasswordRequest request) throws UserRetrievalException { UpdatePasswordResponse response = new UpdatePasswordResponse(); UserDTO currUser = userManager.getByNameUnsecured(request.getUserName()); if (currUser == null) { throw new UserRetrievalException("The user with username " + request.getUserName() + " cannot be found."); } Strength strength = userManager.getPasswordStrength(currUser, request.getNewPassword()); if (strength.getScore() < UserManager.MIN_PASSWORD_STRENGTH) { LOGGER.info("Strength results: [warning: {}] [suggestions: {}] [score: {}] [worst case crack time: {}]", strength.getFeedback().getWarning(), strength.getFeedback().getSuggestions().toString(), strength.getScore(), strength.getCrackTimesDisplay().getOfflineFastHashing1e10PerSecond()); response.setStrength(strength); response.setPasswordUpdated(false); return response; } if (userManager.authorizePasswordReset(request.getToken())) { userManager.updateUserPasswordUnsecured(currUser.getSubjectName(), request.getNewPassword()); userManager.deletePreviousTokens(request.getToken()); response.setPasswordUpdated(true); } else { response.setPasswordUpdated(false); } return response; }
Source:
private List<String> getLongestSharedDimOrder(List<IndexableAdapter> indexes) { int maxSize = 0; Iterable<String> orderingCandidate = null; for (IndexableAdapter index : indexes) { int iterSize = Iterators.size(index.getDimensionNames().iterator()); if (iterSize > maxSize) { maxSize = iterSize; orderingCandidate = index.getDimensionNames(); } } if (orderingCandidate == null) { return null; } for (IndexableAdapter index : indexes) { Iterator<String> candidateIter = orderingCandidate.iterator(); for (String matchDim : index.getDimensionNames()) { boolean matched = false; while (candidateIter.hasNext()) { String nextDim = candidateIter.next(); if (matchDim.equals(nextDim)) { matched = true; break; } } if (!matched) { return null; } } } return ImmutableList.copyOf(orderingCandidate); }

Target:
private static List<String> getLongestSharedDimOrder(List<IndexableAdapter> indexes) { int maxSize = 0; Iterable<String> orderingCandidate = null; for (IndexableAdapter index : indexes) { int iterSize = index.getDimensionNames().size(); if (iterSize > maxSize) { maxSize = iterSize; orderingCandidate = index.getDimensionNames(); } } if (orderingCandidate == null) { return null; } for (IndexableAdapter index : indexes) { Iterator<String> candidateIter = orderingCandidate.iterator(); for (String matchDim : index.getDimensionNames()) { boolean matched = false; while (candidateIter.hasNext()) { String nextDim = candidateIter.next(); if (matchDim.equals(nextDim)) { matched = true; break; } } if (!matched) { return null; } } } return ImmutableList.copyOf(orderingCandidate); }
Source:
public void expandToInclude( Envelope other ) { if ( !isValid() ) { min = other.min.clone(); max = other.max.clone(); } else { for ( int i = 0; i < min.length; i++ ) { if ( other.min[i] < min[i] ) { min[i] = other.min[i]; } if ( other.max[i] > max[i] ) { max[i] = other.max[i]; } } } }

Target:
public void expandToInclude( Envelope other ) { if ( getDimension() != other.getDimension() ) { throw new IllegalArgumentException( "Cannot join Envelopes with different dimensions: " + this.getDimension() + " != " + other.getDimension() ); } else { for ( int i = 0; i < min.length; i++ ) { if ( other.min[i] < min[i] ) { min[i] = other.min[i]; } if ( other.max[i] > max[i] ) { max[i] = other.max[i]; } } } }
Source:
public void testJson_MetadataBlock() { try { MetadataBlock mtb = new MetadataBlock(); mtb.setId(1L); mtb.setName("metadata_block_name"); mtb.setDisplayName("Metadata Block Name"); BriefJsonPrinter sut = new BriefJsonPrinter(); JsonObject res = sut.json(mtb).build(); assertEquals("Metadata Block Name", res.getString("displayName")); assertEquals("metadata_block_name", res.getString("name")); assertEquals(1, res.getInt("id")); assertEquals(3, res.keySet().size()); } catch (MissingResourceException e) { return; } }

Target:
public void testJson_MetadataBlock() { MetadataBlock mtb = new MetadataBlock(); mtb.setId(1L); mtb.setName("metadata_block_name"); mtb.setDisplayName("Metadata Block Name"); BriefJsonPrinter sut = new BriefJsonPrinter(); JsonObject res = sut.json(mtb).build(); assertEquals("Metadata Block Name", res.getString("displayName")); assertEquals("metadata_block_name", res.getString("name")); assertEquals(1, res.getInt("id")); assertEquals(3, res.keySet().size()); }