auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SearchRequestBuilder buildScrollSearchRequest() { String indices = index != null && !index.isEmpty() ? index : "_all"; SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indices) .setTypes(type) <START> .setSearchType(SearchType.QUERY_THEN_FETCH) <END> .setScroll(new TimeValue(scrollTimeout.toMillis())) .setQuery(buildSearchQuery()) .setPreference("_shards:" + shard) .setSize(scrollSize); LOG.debug("ElasticSearch Request: " + searchRequestBuilder.toString()); return searchRequestBuilder; }</code><technical_language>static import QUERY_THEN_FETCH</technical_language>

Target:
public SearchRequestBuilder buildScrollSearchRequest() { String indices = index != null && !index.isEmpty() ? index : "_all"; SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indices) .setTypes(type) .setSearchType(QUERY_THEN_FETCH) .setScroll(new TimeValue(scrollTimeout.toMillis())) .setQuery(buildSearchQuery()) .setPreference("_shards:" + shard) .setSize(scrollSize); LOG.debug("ElasticSearch Request: %s" + searchRequestBuilder); return searchRequestBuilder; }
Source:
<code>public Relationship byTypeValue(final String typeValue){ if(typeValue==null) { return null; } Relationship rel = null; try { rel = cache.getRelationshipByName(typeValue); if(rel != null && rel.getRelationTypeValue().equals(typeValue)) return rel; } catch (DotCacheException e) { Logger.debug(this.getClass(), "Unable to access the cache to obtain the relationship", e); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); try { final DotConnect dc = new DotConnect(); dc.setSQL(sql.FIND_BY_TYPE_VALUE); dc.addParam(typeValue.toLowerCase()); results = dc.loadObjectResults(); if (results.size() == 0) { return rel; } } catch (DotDataException e) { <START> Logger.error(this,"Error getting relationships with typeValue: " + typeValue.toLowerCase()); <END> } rel = new DbRelationshipTransformer(results).from(); if(rel!= null && InodeUtils.isSet(rel.getInode())){ cache.putRelationshipByInode(rel); } return rel; }</code><technical_language>include e in Logger.error</technical_language>

Target:
public Relationship byTypeValue(final String typeValue){ if(typeValue==null) { return null; } Relationship rel = null; try { rel = cache.getRelationshipByName(typeValue); if(rel != null && rel.getRelationTypeValue().equals(typeValue)) return rel; } catch (DotCacheException e) { Logger.debug(this.getClass(), "Unable to access the cache to obtain the relationship", e); } List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); try { final DotConnect dc = new DotConnect(); dc.setSQL(sql.FIND_BY_TYPE_VALUE); dc.addParam(typeValue.toLowerCase()); results = dc.loadObjectResults(); if (results.size() == 0) { return rel; } } catch (DotDataException e) { Logger.error(this,"Error getting relationships with typeValue: " + typeValue.toLowerCase(),e); } rel = new DbRelationshipTransformer(results).from(); if(rel!= null && InodeUtils.isSet(rel.getInode())){ cache.putRelationshipByInode(rel); } return rel; }
Source:
<code>public boolean validate() { boolean isValid = true; setMessage(null); Iterable<EntityModel<GlusterVolumeSnapshotConfig>> items1 = getClusterConfigOptions().getItems(); <START> if(getClusterConfigOptions().getItems() == <END> null || getClusterConfigOptions().getItems().isEmpty()) { return false; } for (EntityModel<GlusterVolumeSnapshotConfig> model : items1) { GlusterVolumeSnapshotConfig option = model.getEntity(); if (option.getParamValue().trim().length() == 0) { setMessage(ConstantsManager.getInstance() .getMessages() .clusterSnapshotOptionValueEmpty(option.getParamName())); isValid = false; break; } } return isValid; }</code><technical_language>this items1 instead</technical_language>

Target:
public boolean validate() { boolean isValid = true; setMessage(null); if(getClusterConfigOptions().getItems() == null || getClusterConfigOptions().getItems().isEmpty()) { return false; } for (EntityModel<GlusterVolumeSnapshotConfig> model : getClusterConfigOptions().getItems()) { GlusterVolumeSnapshotConfig option = model.getEntity(); if (option.getParamValue().trim().length() == 0) { setMessage(ConstantsManager.getInstance() .getMessages() .clusterSnapshotOptionValueEmpty(option.getParamName())); isValid = false; break; } } return isValid; }
Source:
<code>public void testConfigure() throws Descriptor.FormException { doNothing().when(desc).save(); StaplerRequest request = mock(StaplerRequest.class); desc.configure(request, json); <START> verify(request).bindJSON(desc, json); <END> }</code><technical_language>question is, if verifying a bindJSON call is sufficient for you. sure, values verified (using a StaplerRequest implementation/mock implements bindJSON if possible). if for example missed a setter for a field, this caught JCasC UI based configuration broken</technical_language>

Target:
public void testConfigure() throws Descriptor.FormException { doNothing().when(desc).save(); ServletContext servletContext = mock(ServletContext.class); WebApp webApp = new WebApp(servletContext); Stapler stapler = mock(Stapler.class); when(stapler.getWebApp()).thenReturn(webApp); HttpServletRequest servletRequest = mock(HttpServletRequest.class); TokenList tokenList = mock(TokenList.class); RequestImpl staplerRequest = new RequestImpl(stapler, servletRequest, new ArrayList<>(), tokenList); desc.configure(staplerRequest, json); assertThat(desc.isApplicable(AbstractProject.class), is(true)); assertThat(desc.getCredentialsId(), is("bitbucket-credentials")); assertThat(desc.isDisableInprogressNotification(), is(true)); assertThat(desc.getDisplayName(), is("Notify Stash Instance")); assertThat(desc.isIncludeBuildNumberInKey(), is(true)); assertThat(desc.isIgnoreUnverifiedSsl(), is(true)); assertThat(desc.isPrependParentProjectKey(), is(true)); assertThat(desc.getProjectKey(), is("JEN")); assertThat(desc.getStashRootUrl(), is("https://my.company.intranet/bitbucket")); }
Source:
<code>public void testNoRepository() throws CoreException { ConnectProviderOperation operation = new ConnectProviderOperation( <START> project.getProject()); <END> operation.run(null); assertFalse(RepositoryProvider.isShared(project.getProject())); assertTrue(!gitDir.exists()); }</code><technical_language>This change related JUnit migration</technical_language>

Target:
public void testNoRepository() throws CoreException { ConnectProviderOperation operation = new ConnectProviderOperation( project.getProject(), new File("../..", Constants.DOT_GIT)); operation.run(null); assertFalse(RepositoryProvider.isShared(project.getProject())); assertTrue(!gitDir.exists()); }
Source:
<code>private static boolean isInstancePrimitive(@Nonnull Class<?> type, @Nonnull Object instance) { if (type.isInstance(instance)) { return true; } if (instance instanceof Number) { Number n = (Number) instance; if (type == Long.class || type == Double.class) { <START> return true; <END> } if (type == Integer.class && n.longValue() <= Integer.MAX_VALUE && n.longValue() >= Integer.MIN_VALUE) { return true; } } return false; }</code><technical_language>This return true for narrowing conversions - happen, right</technical_language>

Target:
private static boolean isInstancePrimitive(@Nonnull Class<?> type, @Nonnull Object instance) { if (type.isInstance(instance)) { return true; } if (instance instanceof Number) { if (type == Long.class && instance instanceof Integer) { return true; } if (type == Integer.class && instance instanceof Long) { Long n = (Long) instance; if (n >= Integer.MIN_VALUE && n <= Integer.MAX_VALUE) { return true; } } } return false; }
Source:
<code>public void save(Subscription subscription, PartitionOffset partitionOffset) throws ExecutionException { OffsetCommitRequest commitRequest = createCommitRequest(subscription, partitionOffset); OffsetCommitResponse commitResponse; try { commitResponse = commitOffset(subscription, commitRequest); } catch (Exception e) { channels.invalidate(subscription); throw e; } if (commitResponse.hasError()) { <START> for (Object error: commitResponse.errors().values()) { <END> if ((Short) error == ErrorMapping.NotCoordinatorForConsumerCode() || (Short) error == ErrorMapping.ConsumerCoordinatorNotAvailableCode()) { channels.invalidate(subscription); break; } } throw new CannotCommitOffsetToBrokerException(new BrokerOffsetCommitErrors(commitResponse.errors())); } }</code><technical_language>I written stream</technical_language>

Target:
public void save(Subscription subscription, PartitionOffset partitionOffset) throws ExecutionException { OffsetCommitRequest commitRequest = createCommitRequest(subscription, partitionOffset); OffsetCommitResponse commitResponse; try { commitResponse = commitOffset(subscription, commitRequest); } catch (Exception e) { channels.invalidate(subscription); throw e; } if (commitResponse.hasError()) { commitResponse.errors().values() .stream() .map(error -> (Short) error) .filter(error -> error == ErrorMapping.NotCoordinatorForConsumerCode() || error == ErrorMapping.ConsumerCoordinatorNotAvailableCode()) .findAny() .ifPresent(error -> channels.invalidate(subscription)); throw new CannotCommitOffsetToBrokerException(new BrokerOffsetCommitErrors(commitResponse.errors())); } }
Source:
<code>private void loadPreselectedReplays() { enterSearchingState(); replayService.getNewestReplaysWithMeta(TOP_ELEMENT_COUNT, 1) <START> .thenAccept(replays -> populateReplays(replays.getFirst(), newestPane)) <END> .thenCompose(aVoid -> replayService.getHighestRatedReplaysWithMeta(TOP_ELEMENT_COUNT, 1).thenAccept(highestRatedReplays -> populateReplays(highestRatedReplays.getFirst(), highestRatedPane))) .thenCompose(aVoid -> replayService.getOwnReplaysWithMeta(TOP_ELEMENT_COUNT, 1).thenAccept(highestRatedReplays -> populateReplays(highestRatedReplays.getFirst(), ownReplaysPane))) .thenRun(this::enterResultState) .exceptionally(throwable -> { logger.warn("Could not populate replays", throwable); return null; }); }</code><technical_language>decided that, need carry a tuple pagination set in controller. This opens possibility more of metadata page amount</technical_language>

Target:
private void loadPreselectedReplays() { enterSearchingState(); replayService.getNewestReplaysWithPageCount(TOP_ELEMENT_COUNT, 1) .thenAccept(replays -> populateReplays(replays.getFirst(), newestPane)) .thenCompose(aVoid -> replayService.getHighestRatedReplaysWithPageCount(TOP_ELEMENT_COUNT, 1).thenAccept(highestRatedReplays -> populateReplays(highestRatedReplays.getFirst(), highestRatedPane))) .thenCompose(aVoid -> replayService.getOwnReplaysWithPageCount(TOP_ELEMENT_COUNT, 1).thenAccept(highestRatedReplays -> populateReplays(highestRatedReplays.getFirst(), ownReplaysPane))) .thenRun(this::enterShowRoomState) .exceptionally(throwable -> { logger.warn("Could not populate replays", throwable); return null; }); }
Source:
<code>public void testSerializePeriod() throws Exception { ObjectMapper mapper = new DefaultObjectMapper(); String json = "{ \"type\": \"period\", \"period\": \"P1D\" }"; QueryGranularity gran = mapper.readValue(json, QueryGranularity.class); Assert.assertEquals(new PeriodGranularity(new Period("P1D"), null, null), gran); json = "{ \"type\": \"period\", \"period\": \"P1D\"," + "\"timeZone\": \"America/Los_Angeles\", \"origin\": \"1970-01-01T00:00:00Z\"}"; gran = mapper.readValue(json, QueryGranularity.class); Assert.assertEquals(new PeriodGranularity(new Period("P1D"), new DateTime(0L), DateTimeZone.forID("America/Los_Angeles")), gran); QueryGranularity expected = new PeriodGranularity( new Period("P1D"), new DateTime("2012-01-01"), DateTimeZone.forID("America/Los_Angeles") ); String jsonOut = mapper.writeValueAsString(expected); Assert.assertEquals(expected, mapper.readValue(jsonOut, QueryGranularity.class)); String illegalJson = "{ \"type\": \"period\", \"period\": \"P0D\" }"; try { <START> mapper.readValue(illegalJson, QueryGranularity.class); <END> } catch (JsonMappingException e) { Assert.assertEquals("zero period is not acceptable in QueryGranularity!", e.getCause().getMessage()); } }</code><technical_language>suggest Assert.fail() exception is thrown. Or, @Rule ExpectedException (example in FileTaskLogsTest)</technical_language>

Target:
public void testSerializePeriod() throws Exception { ObjectMapper mapper = new DefaultObjectMapper(); String json = "{ \"type\": \"period\", \"period\": \"P1D\" }"; QueryGranularity gran = mapper.readValue(json, QueryGranularity.class); Assert.assertEquals(new PeriodGranularity(new Period("P1D"), null, null), gran); json = "{ \"type\": \"period\", \"period\": \"P1D\"," + "\"timeZone\": \"America/Los_Angeles\", \"origin\": \"1970-01-01T00:00:00Z\"}"; gran = mapper.readValue(json, QueryGranularity.class); Assert.assertEquals(new PeriodGranularity(new Period("P1D"), new DateTime(0L), DateTimeZone.forID("America/Los_Angeles")), gran); QueryGranularity expected = new PeriodGranularity( new Period("P1D"), new DateTime("2012-01-01"), DateTimeZone.forID("America/Los_Angeles") ); String jsonOut = mapper.writeValueAsString(expected); Assert.assertEquals(expected, mapper.readValue(jsonOut, QueryGranularity.class)); String illegalJson = "{ \"type\": \"period\", \"period\": \"P0D\" }"; try { mapper.readValue(illegalJson, QueryGranularity.class); Assert.fail(); } catch (JsonMappingException e) { } }
Source:
<code>public DitaClass(final String cls) { final String[] tokens = WHITESPACE.split(cls); final String last = tokens[tokens.length - 1]; matcher = ' ' + last + ' '; localName = last.substring(last.indexOf('/') + 1); final StringBuilder sb = new StringBuilder(); for (final String s: tokens) { sb.append(s).append(' '); } stringValue = sb.toString(); <START> validDitaClass = (cls == null ? false : VALID_DITA_CLASS.matcher(stringValue).matches()); <END> }</code><technical_language>need check for null, cls null throw a NullPointerException row 52 if is</technical_language>

Target:
public DitaClass(final String cls) { final String[] tokens = WHITESPACE.split(cls); final String last = tokens[tokens.length - 1]; matcher = ' ' + last + ' '; localName = last.substring(last.indexOf('/') + 1); final StringBuilder sb = new StringBuilder(); for (final String s: tokens) { sb.append(s).append(' '); } stringValue = sb.toString(); validDitaClass = VALID_DITA_CLASS.matcher(stringValue).matches(); }
Source:
<code>protected void onInitUI() { super.onInitUI(); createWidgets(); grid = new Grid(2, 2); grid.setStyleName(Gerrit.RESOURCES.css().infoBlock()); grid.setText(0, 0, Util.C.watchedProjectName()); grid.setWidget(0, 1, nameTxt); grid.setText(1, 0, Util.C.watchedProjectFilter()); grid.setWidget(1, 1, filterTxt); final CellFormatter fmt = grid.getCellFormatter(); fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().topmost()); fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().topmost()); fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().header()); fmt.addStyleName(1, 0, Gerrit.RESOURCES.css().header()); fmt.addStyleName(1, 0, Gerrit.RESOURCES.css().bottomheader()); final FlowPanel fp = new FlowPanel(); fp.setStyleName(Gerrit.RESOURCES.css().addWatchPanel()); fp.add(grid); fp.add(addNew); fp.add(browse); add(fp); add(watchesTab); add(delSel); projectListPopup = new ProjectListPopup(Util.C.projects(), PageLinks.SETTINGS_PROJECTS, <START> nameTxt, null); <END> projectListPopup .addOpenRowHandler(new ProjectListPopup.ProjectListPopupOnOpenRowHandler() { @Override public void onOpenProjectRow( ProjectListPopupOnOpenRowEvent projectListPopupEvent) { doAddNew(); } }); }</code><technical_language>change ProjectListPopup accept a ResizeHandler? This clean a lot of extra unused code</technical_language>

Target:
protected void onInitUI() { super.onInitUI(); createWidgets(); final Grid grid = new Grid(2, 2); grid.setStyleName(Gerrit.RESOURCES.css().infoBlock()); grid.setText(0, 0, Util.C.watchedProjectName()); grid.setWidget(0, 1, nameTxt); grid.setText(1, 0, Util.C.watchedProjectFilter()); grid.setWidget(1, 1, filterTxt); final CellFormatter fmt = grid.getCellFormatter(); fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().topmost()); fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().topmost()); fmt.addStyleName(0, 0, Gerrit.RESOURCES.css().header()); fmt.addStyleName(1, 0, Gerrit.RESOURCES.css().header()); fmt.addStyleName(1, 0, Gerrit.RESOURCES.css().bottomheader()); final FlowPanel fp = new FlowPanel(); fp.setStyleName(Gerrit.RESOURCES.css().addWatchPanel()); fp.add(grid); fp.add(addNew); fp.add(browse); add(fp); add(watchesTab); add(delSel); final FlowPanel pfp = new FlowPanel(); sp = new ScrollPanel(projectsTab); sp.setSize("100%", "100%"); pfp.add(sp); pfp.add(close); popup.setWidget(pfp); popup.setHeight("100%"); popupPosition = new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { int top = grid.getAbsoluteTop() - 50; int left = 5 + Math.max(grid.getAbsoluteLeft() + grid.getOffsetWidth(), watchesTab.getAbsoluteLeft() + watchesTab.getOffsetWidth()); if (top + offsetHeight > Window.getClientHeight()) { top = Window.getClientHeight() - offsetHeight; } if (left + offsetWidth > Window.getClientWidth()) { left = Window.getClientWidth() - offsetWidth; } if (top < 0) { sp.setHeight((sp.getOffsetHeight() + top) + "px"); top = 0; } if (left < 0) { sp.setWidth((sp.getOffsetWidth() + left) + "px"); left = 0; } popup.setPopupPosition(left, top); } }; }
Source:
<code>private void addFileSystemFile(SleuthkitCase skCase, FsContent recycleBinFile, Content parentDir, String fileName, long deletedTime) throws TskCoreException { skCase.addFileSystemFile( recycleBinFile.getDataSourceObjectId(), recycleBinFile.getFileSystemId(), fileName, recycleBinFile.getMetaAddr(), (int) recycleBinFile.getMetaSeq(), recycleBinFile.getAttrType(), recycleBinFile.getAttributeId(), TskData.TSK_FS_NAME_FLAG_ENUM.UNALLOC, (short) (TskData.TSK_FS_META_FLAG_ENUM.UNALLOC.getValue() | TskData.TSK_FS_META_FLAG_ENUM.USED.getValue()), recycleBinFile.getSize(), <START> 0, 0, 0, deletedTime, <END> true, parentDir); }</code><technical_language>add in Timestamps $R file add in. This file consistent $R file</technical_language>

Target:
private void addFileSystemFile(SleuthkitCase skCase, FsContent recycleBinFile, Content parentDir, String fileName, long deletedTime) throws TskCoreException { skCase.addFileSystemFile( recycleBinFile.getDataSourceObjectId(), recycleBinFile.getFileSystemId(), fileName, recycleBinFile.getMetaAddr(), (int) recycleBinFile.getMetaSeq(), recycleBinFile.getAttrType(), recycleBinFile.getAttributeId(), TskData.TSK_FS_NAME_FLAG_ENUM.UNALLOC, (short) (TskData.TSK_FS_META_FLAG_ENUM.UNALLOC.getValue() | TskData.TSK_FS_META_FLAG_ENUM.USED.getValue()), recycleBinFile.getSize(), recycleBinFile.getCtime(), recycleBinFile.getCrtime(), recycleBinFile.getAtime(), deletedTime, true, parentDir); }
Source:
<code>public void prepare() { string = new StringBuilder(32); date = new MutableDateTime(2015, 9, 24, 0, 0, 0, 0); timeOnly = new MutableDateTime(2015, 9, 24, 9, 30, 5, 250); timestamp = new MutableDateTime(2015, 9, 24, 9, 30, 5, 250); charValue = new FIXValue(32); charValue.setChar('Y'); intValue = new FIXValue(32); intValue.setInt(123); floatValue = new FIXValue(32); floatValue.setFloat(12.30, 2); stringValue = new FIXValue(32); stringValue.setString("FOO"); dateValue = new FIXValue(32); dateValue.setDate(date); timeOnlyValue = new FIXValue(32); timeOnlyValue.setTimeOnly(timeOnly, true); <START> timestampValue = new FIXValue(64); <END> timestampValue.setTimestamp(timestamp, true); timestampValueDestination = new FIXValue(64); }</code><technical_language>increase in capacity</technical_language>

Target:
public void prepare() { string = new StringBuilder(32); date = new MutableDateTime(2015, 9, 24, 0, 0, 0, 0); timeOnly = new MutableDateTime(2015, 9, 24, 9, 30, 5, 250); timestamp = new MutableDateTime(2015, 9, 24, 9, 30, 5, 250); charValue = new FIXValue(64); charValue.setChar('Y'); intValue = new FIXValue(64); intValue.setInt(123); floatValue = new FIXValue(64); floatValue.setFloat(12.30, 2); stringValue = new FIXValue(64); stringValue.setString("FOO"); dateValue = new FIXValue(64); dateValue.setDate(date); timeOnlyValue = new FIXValue(64); timeOnlyValue.setTimeOnly(timeOnly, true); timestampValue = new FIXValue(64); timestampValue.setTimestamp(timestamp, true); copyValue = new FIXValue(64); }
Source:
<code>private String obfuscate(TableReference tableRef) { <START> return Sha256Hash.computeHash(tableRef.getTablename().getBytes()).serializeToHexString().substring(0, 8); <END> }</code><technical_language>thinking collisions here, <LINK_0>, ~1% probability of collision in 10k tables, fine I (except for large internal product is creating truncating tables). a 16 character substring</technical_language>

Target:
private String obfuscate(TableReference tableRef) { return Sha256Hash.computeHash(tableRef.getTablename().getBytes()).serializeToHexString().substring(0, 16); }
Source:
<code>StackItemsModelChangeListener(Map<VStackLayout, Setting> stackToSetting) { this.stackToSetting = new LinkedHashMap<VStackLayout, EStructuralFeature.Setting>(); <START> this.stackToSetting.putAll(stackToSetting); <END> }</code><technical_language>simply assign</technical_language>

Target:
StackItemsModelChangeListener(Map<VStackLayout, Setting> stackToSetting) { this.stackToSetting = stackToSetting; }
Source:
<code>public final int hashCode() { <START> return (enabled ? 1 : 0); <END> }</code><technical_language>Boolean.hashCode(...)? a big concern here, larger figures (and primes) more fair hashing structures</technical_language>

Target:
public final int hashCode() { return Boolean.hashCode(enabled); }
Source:
<code>private LocalDateTime convertToLocalDateTime(ObjectMapper mapper, JsonNode jsonNode) { <START> TemporalAccessor parsedTimestamp = ISO8601_TIMESTAMP_FORMAT.parse(jsonNode.asText()); <END> ZoneOffset zoneOffset = parsedTimestamp.query(TemporalQueries.offset()); if (zoneOffset != null && zoneOffset.getTotalSeconds() != 0) { throw new IllegalStateException( "Invalid timestamp format. Only a timestamp in UTC timezone is supported yet. " + "Format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); } LocalTime localTime = parsedTimestamp.query(TemporalQueries.localTime()); LocalDate localDate = parsedTimestamp.query(TemporalQueries.localDate()); return LocalDateTime.of(localDate, localTime); }</code><technical_language>need udpate legacy json format (keep comatibility), change behavior support timestamp format for TIMESTAMP type, right</technical_language>

Target:
private LocalDateTime convertToLocalDateTime(ObjectMapper mapper, JsonNode jsonNode) { TemporalAccessor parsedTimestamp = RFC3339_TIMESTAMP_FORMAT.parse(jsonNode.asText()); ZoneOffset zoneOffset = parsedTimestamp.query(TemporalQueries.offset()); if (zoneOffset != null && zoneOffset.getTotalSeconds() != 0) { throw new IllegalStateException( "Invalid timestamp format. Only a timestamp in UTC timezone is supported yet. " + "Format: yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); } LocalTime localTime = parsedTimestamp.query(TemporalQueries.localTime()); LocalDate localDate = parsedTimestamp.query(TemporalQueries.localDate()); return LocalDateTime.of(localDate, localTime); }
Source:
<code>private CNLOHBalancedCall isBalanced(final double rho, final int m, final int n) { <START> if ((m == n) || (rho <= getRhoThreshold())) { <END> return CNLOHBalancedCall.BALANCED; } else { return CNLOHBalancedCall.NOT_BALANCED; } }</code><technical_language>Humor a ternary if a big deal you</technical_language>

Target:
private CNLOHBalancedCall isBalanced(final double rho, final int m, final int n) { return ( (m == n) || (rho <= getRhoThreshold()) ? CNLOHBalancedCall.BALANCED : CNLOHBalancedCall.NOT_BALANCED); }
Source:
<code>protected void executeCommand() { <START> T params = getParameters(); <END> String address = params.getAddress(); String subnet = StringUtils.isEmpty(params.getSubnet()) ? params.getNetwork() .getsubnet() : params.getSubnet(); String gateway = StringUtils.isEmpty(params.getGateway()) ? params.getNetwork() .getgateway() : params.getGateway(); NetworkVdsmVDSCommandParameters parameters = new NetworkVdsmVDSCommandParameters(params.getVdsId(), params.getNetwork(), params.getBondName(), params.getNics(), address, subnet, gateway, params.getBondingOptions(), params.getBootProtocol()); VDSReturnValue retVal = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.AddNetwork, parameters); if (retVal.getSucceeded()) { retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.CollectVdsNetworkData, new VdsIdAndVdsVDSCommandParametersBase(params.getVdsId())); if (retVal.getSucceeded()) { VdsStatic vdsStatic = DbFacade.getInstance().getVdsStaticDAO().get(params.getVdsId()); AttachNetworkToVdsGroupCommand.SetNetworkStatus(vdsStatic.getvds_group_id(), params .getNetwork()); setSucceeded(true); } } }</code><technical_language>extract variable</technical_language>

Target:
protected void executeCommand() { T params = getParameters(); String address = params.getAddress(); String subnet = StringUtils.isEmpty(params.getSubnet()) ? params.getNetwork() .getsubnet() : params.getSubnet(); String gateway = StringUtils.isEmpty(params.getGateway()) ? params.getNetwork() .getgateway() : params.getGateway(); NetworkVdsmVDSCommandParameters vdsParams = new NetworkVdsmVDSCommandParameters(params.getVdsId(), params.getNetwork(), params.getBondName(), params.getNics(), address, subnet, gateway, params.getBondingOptions(), params.getBootProtocol()); VDSReturnValue retVal = Backend.getInstance().getResourceManager() .RunVdsCommand(VDSCommandType.AddNetwork, vdsParams); if (retVal.getSucceeded()) { retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.CollectVdsNetworkData, new VdsIdAndVdsVDSCommandParametersBase(params.getVdsId())); if (retVal.getSucceeded()) { VdsStatic vdsStatic = DbFacade.getInstance().getVdsStaticDAO().get(params.getVdsId()); AttachNetworkToVdsGroupCommand.SetNetworkStatus(vdsStatic.getvds_group_id(), params .getNetwork()); setSucceeded(true); } } }
Source:
<code>public TestTpchTaskUpdateSizeLimitIntegrationTest() { <START> this(() -> createQueryRunner(ImmutableMap.of("experimental.internal-communication.max-task-update-size", "100B"))); <END> }</code><technical_language>super(() -> createQueryRunner(ImmutableMap.of("experimental.internal-communication.max-task-update-size", "100B")));</technical_language>

Target:
public TestTpchTaskUpdateSizeLimitIntegrationTest() { super(() -> createQueryRunner(ImmutableMap.of("experimental.internal-communication.max-task-update-size", "100B"))); }
Source:
<code>public Element build(final CallbackProperties properties) throws Exception { <START> LOG.debug("SamlCallbackHandler.createHOKSAMLAssertion20() -- Begin Minh version 33333"); <END> Element signedAssertion; try { Assertion assertion; assertion = OpenSAML2ComponentBuilder.getInstance().createAssertion(); final String aID = createAssertionId(); LOG.debug("Assertion ID: " + aID); assertion.setID(aID); final DateTime issueInstant = new DateTime(); assertion.setIssueInstant(issueInstant); assertion.setIssuer(createIssuer(properties)); final X509Certificate certificate = certificateManager.getDefaultCertificate(); final PublicKey publicKey = certificateManager.getDefaultPublicKey(); final Subject subject = createSubject(properties, certificate, publicKey); assertion.setSubject(subject); final Subject evidenceSubject = createEvidenceSubject(properties, certificate, publicKey); assertion.getStatements().addAll(createAttributeStatements(properties, evidenceSubject)); final PrivateKey privateKey = certificateManager.getDefaultPrivateKey(); signedAssertion = sign(assertion, certificate, privateKey, publicKey); } catch (final Exception ex) { LOG.error("Unable to create HOK Assertion: {}", ex.getLocalizedMessage()); throw ex; } LOG.debug("SamlCallbackHandler.createHOKSAMLAssertion20() -- End"); return signedAssertion; }</code><technical_language>This trace remoe "Minh version ...."</technical_language>

Target:
public Element build(final CallbackProperties properties) throws Exception { LOG.debug("SamlCallbackHandler.createHOKSAMLAssertion20()"); Element signedAssertion; try { Assertion assertion; assertion = OpenSAML2ComponentBuilder.getInstance().createAssertion(); final String aID = createAssertionId(); LOG.debug("Assertion ID: {}", aID); assertion.setID(aID); final DateTime issueInstant = new DateTime(); assertion.setIssueInstant(issueInstant); assertion.setIssuer(createIssuer(properties)); final X509Certificate certificate = certificateManager.getDefaultCertificate(); final PublicKey publicKey = certificateManager.getDefaultPublicKey(); final Subject subject = createSubject(properties, certificate, publicKey); assertion.setSubject(subject); final Subject evidenceSubject = createEvidenceSubject(properties, certificate, publicKey); assertion.getStatements().addAll(createAttributeStatements(properties, evidenceSubject)); final PrivateKey privateKey = certificateManager.getDefaultPrivateKey(); signedAssertion = sign(assertion, certificate, privateKey, publicKey); } catch (final Exception ex) { LOG.error("Unable to create HOK Assertion: {}", ex.getLocalizedMessage()); throw ex; } LOG.debug("SamlCallbackHandler.createHOKSAMLAssertion20() -- End"); return signedAssertion; }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); excelInputreaderConfig.validate(collector); <START> if (Strings.isNullOrEmpty(excelInputreaderConfig.columnList) && <END> Strings.isNullOrEmpty(excelInputreaderConfig.outputSchema)) { collector.addFailure( "'Field Name Schema Type Mapping' and 'Columns To Be Extracted' cannot both be empty.", null) .withConfigProperty(OUTPUT_SCHEMA).withConfigProperty(COLUMN_LIST); } createDatasets(pipelineConfigurer, null); init(collector); getOutputSchema(); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); }</code><technical_language>this belongs in validate() method</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); excelInputreaderConfig.validate(collector); createDatasets(pipelineConfigurer); collector.getOrThrowException(); init(collector); collector.getOrThrowException(); getOutputSchema(); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); }
Source:
<code>public static BeanPostProcessor upcase() { return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals("interceptedSource")) { ProxyFactory pf = new ProxyFactory(bean); <START> MethodInterceptor interceptor = new MethodInterceptor() { <END> @Override public Object invoke(MethodInvocation invocation) throws Throwable { if (invocation.getMethod().getName().equals("receive")) { org.springframework.messaging.Message<?> message = (org.springframework.messaging.Message<?>) invocation.proceed(); if (message == null) { return null; } return MessageBuilder.withPayload(((String) message.getPayload()).toUpperCase()) .copyHeaders(message.getHeaders()) .build(); } else { return invocation.proceed(); } } }; pf.addAdvice(interceptor); return pf.getProxy(); } return bean; } }; }</code><technical_language>MethodInterceptor is a @FunctionalInterface</technical_language>

Target:
public static BeanPostProcessor upcase() { return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals("interceptedSource")) { ProxyFactory pf = new ProxyFactory(bean); pf.addAdvice((MethodInterceptor) invocation -> { if (invocation.getMethod().getName().equals("receive")) { org.springframework.messaging.Message<?> message = (org.springframework.messaging.Message<?>) invocation.proceed(); if (message == null) { return null; } return MessageBuilder.withPayload(((String) message.getPayload()).toUpperCase()) .copyHeaders(message.getHeaders()) .build(); } else { return invocation.proceed(); } }); return pf.getProxy(); } return bean; } }; }
Source:
<code>private List<String> fixInvalidIndexes(ArrayListMultimap<String, byte[]> result) throws StandardException { try { WriteCoordinator writeCoordinator = PipelineDriver.driver().writeCoordinator(); WriteConfiguration writeConfiguration = writeCoordinator.defaultWriteConfiguration(); Partition indexPartition = SIDriver.driver().getTableFactory().getTable(Long.toString(conglomerate)); RecordingCallBuffer<KVPair> writeBuffer = writeCoordinator.writeBuffer(indexPartition, txn, null, writeConfiguration); List<String> messages = new LinkedList<>(); int i = 0; messages.add(String.format("The following %d indexes are deleted:", invalidIndexCount)); for (String baseRowId : result.keySet()) { List<byte[]> keys = result.get(baseRowId); for (byte[] key : keys) { if (i == maxCheckTableErrors) { messages.add("..."); <START> return messages; <END> } writeBuffer.add(new KVPair(key, new byte[0], KVPair.Type.DELETE)); if (i > maxCheckTableErrors) { continue; } indexKeyDecoder.set(key, 0, key.length); indexKeyDecoder.decode(indexKeyTemplate); messages.add(indexKeyTemplate.getClone().toString() + "=>" + baseRowId); i++; } } writeBuffer.flushBuffer(); return messages; } catch (Exception e) { throw StandardException.plainWrapException(e); } }</code><technical_language>return here? I thought want suppress messages in report, want continue remove invalidate indexes. If want stop fixing indexes reaches maxCheckTableErrors, return in result explicit message indexes fixed</technical_language>

Target:
private void fixInvalidIndexes(ArrayListMultimap<String, byte[]> result) throws StandardException { try { WriteCoordinator writeCoordinator = PipelineDriver.driver().writeCoordinator(); WriteConfiguration writeConfiguration = writeCoordinator.defaultWriteConfiguration(); Partition indexPartition = SIDriver.driver().getTableFactory().getTable(Long.toString(conglomerate)); RecordingCallBuffer<KVPair> writeBuffer = writeCoordinator.writeBuffer(indexPartition, txn, null, writeConfiguration); List<String> messages = new LinkedList<>(); for (String baseRowId : result.keySet()) { List<byte[]> keys = result.get(baseRowId); for (byte[] key : keys) { writeBuffer.add(new KVPair(key, new byte[0], KVPair.Type.DELETE)); } } writeBuffer.flushBuffer(); } catch (Exception e) { throw StandardException.plainWrapException(e); } }
Source:
<code>public int fill(FluidStack resource, boolean doFill) { if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); <START> BlockDynamicLiquid block = BlockLiquid.getFlowingBlock(material); <END> world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; }</code><technical_language>need change type here</technical_language>

Target:
public int fill(FluidStack resource, boolean doFill) { if (resource.amount < Fluid.BUCKET_VOLUME) { return 0; } if (doFill) { Material material = blockLiquid.getDefaultState().getMaterial(); BlockLiquid block = BlockLiquid.getFlowingBlock(material); world.setBlockState(blockPos, block.getDefaultState().withProperty(BlockLiquid.LEVEL, 0), 11); } return Fluid.BUCKET_VOLUME; }
Source:
<code>public String batchDurchBenutzerAbschliessen() throws DAOException, DataException, IOException { for (Task s : this.steps) { boolean error = false; if (s.isTypeCloseVerify()) { if (s.isTypeMetadata() && ConfigCore.getBooleanParameter("useMetadatenvalidierung")) { serviceManager.getMetadataValidationService().setAutoSave(true); if (!serviceManager.getMetadataValidationService().validate(s.getProcess())) { error = true; } } if (s.isTypeImagesWrite()) { MetadatenImagesHelper mih = new MetadatenImagesHelper(null, null); try { if (!mih.checkIfImagesValid(s.getProcess().getTitle(), serviceManager.getProcessService().getImagesOrigDirectory(false, s.getProcess()))) { error = true; } } catch (Exception e) { <START> logger.error(e.getMessage(), e); <END> Helper.setFehlerMeldung("Error on image validation: ", e); } } loadProcessProperties(s); for (Property prop : this.properties) { if ((prop.getValue() == null || prop.getValue().equals(""))) { List<String> parameter = new ArrayList<>(); parameter.add(prop.getTitle()); parameter.add(s.getProcess().getTitle()); Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); error = true; } } } if (!error) { this.myDav.uploadFromHome(s.getProcess()); TaskDAO taskDAO = new TaskDAO(); Task task = taskDAO.getById(s.getId()); task.setEditTypeEnum(TaskEditType.MANUAL_MULTI); serviceManager.getWorkflowService().close(s); } } AktuelleSchritteForm asf = (AktuelleSchritteForm) Helper.getManagedBeanValue("#{AktuelleSchritteForm}"); return asf.filterAll(); }</code><technical_language>Please replace this log call Helper.setFehlermeldung Helper.setErrorMessage bundles calls</technical_language>

Target:
public String batchDurchBenutzerAbschliessen() throws DAOException, DataException, IOException { for (Task s : this.steps) { boolean error = false; if (s.isTypeCloseVerify()) { if (s.isTypeMetadata() && ConfigCore.getBooleanParameter("useMetadatenvalidierung")) { serviceManager.getMetadataValidationService().setAutoSave(true); if (!serviceManager.getMetadataValidationService().validate(s.getProcess())) { error = true; } } if (s.isTypeImagesWrite()) { MetadatenImagesHelper mih = new MetadatenImagesHelper(null, null); try { if (!mih.checkIfImagesValid(s.getProcess().getTitle(), serviceManager.getProcessService().getImagesOrigDirectory(false, s.getProcess()))) { error = true; } } catch (RuntimeException e) { Helper.setErrorMessage("Error on image validation: ", logger, e); } } loadProcessProperties(s); for (Property prop : this.properties) { if ((prop.getValue() == null || prop.getValue().equals(""))) { List<String> parameter = new ArrayList<>(); parameter.add(prop.getTitle()); parameter.add(s.getProcess().getTitle()); Helper.setFehlerMeldung(Helper.getTranslation("BatchPropertyEmpty", parameter)); error = true; } } } if (!error) { this.myDav.uploadFromHome(s.getProcess()); TaskDAO taskDAO = new TaskDAO(); Task task = taskDAO.getById(s.getId()); task.setEditTypeEnum(TaskEditType.MANUAL_MULTI); serviceManager.getWorkflowControllerService().close(s); } } AktuelleSchritteForm asf = (AktuelleSchritteForm) Helper.getManagedBeanValue("#{AktuelleSchritteForm}"); return asf.filterAll(); }
Source:
<code>public void assignParameterIndexes() throws SQLException { int paramIndex = 1; if (sqlType == SQL_TYPE_SELECT) { if( whereClause != null && whereClause.getExpressionsCount() > 0) { Iterator<SQLExpression> expressionit = whereClause.getExpressions(); while (expressionit.hasNext()) { SQLExpression exp = expressionit.next(); if (exp.getExpressionType() == ExpressionType.LOGICAL_EXPRESSION_TYPE) { paramIndex = exp.setParametrizedNames(paramIndex); } } } <START> parametrizedCount = paramIndex - 1; <END> } }</code><technical_language>parameterizedCount</technical_language>

Target:
public void assignParameterIndexes() throws SQLException { int paramIndex = 1; if (sqlType == SQL_TYPE_SELECT) { if( whereClause != null && whereClause.getExpressionsCount() > 0) { Iterator<SQLExpression> expressionit = whereClause.getExpressions(); while (expressionit.hasNext()) { SQLExpression exp = expressionit.next(); if (exp.getExpressionType() == ExpressionType.LOGICAL_EXPRESSION_TYPE) { paramIndex = exp.setParameterizedNames(paramIndex); } } } parameterizedCount = paramIndex - 1; } }
Source:
<code>public int compareTo(FileEntry fe) { int diff = size - fe.size; <START> return (diff != 0) ? diff : (int) (offset - fe.offset); <END> }</code><technical_language>this is bad IMO. if offset >>> fe.offset diff overflow int (and return a negative int instead of a positive one). Long.valueOf(offset).compareTo(fe.offset) another suggestion is swap order... check offset size is offset size</technical_language>

Target:
public int compareTo(FileEntry fe) { int diff = size - fe.size; if (diff != 0) return diff; return (offset < fe.offset) ? -1 : ((offset == fe.offset) ? 0 : 1); }
Source:
<code>public void accumulate(View found) { try { <START> setLayout(found); <END> } catch (CantVisitException e) { cleanup(); mOnEditErrorListener.onError(e); } }</code><technical_language>This is nicely simpler</technical_language>

Target:
public void accumulate(View found) { ViewGroup parent = (ViewGroup) found; SparseArray<View> idToChild = new SparseArray<View>(); int count = parent.getChildCount(); for (int i = 0; i < count; i++) { View child = parent.getChildAt(i); int childId = child.getId(); if (childId > 0) { idToChild.put(childId, child); } } int size = mArgs.size(); for (int i = 0; i < size; i++) { LayoutRule layoutRule = mArgs.get(i); final View currentChild = idToChild.get(layoutRule.viewId); RelativeLayout.LayoutParams currentParams = (RelativeLayout.LayoutParams) currentChild.getLayoutParams(); final int[] currentRules = currentParams.getRules().clone(); if (currentRules[layoutRule.verb] == layoutRule.anchor) { continue; } if (mOriginalValues.containsKey(currentChild)) { ; } else { mOriginalValues.put(currentChild, currentRules); } currentParams.addRule(layoutRule.verb, layoutRule.anchor); final Set<Integer> rules; if (mHorizontalRules.contains(layoutRule.verb)) { rules = mHorizontalRules; } else if (mVerticalRules.contains(layoutRule.verb)) { rules = mVerticalRules; } else { rules = null; } if (rules != null && !verifyLayout(rules, idToChild)) { cleanup(); mOnLayoutErrorListener.onLayoutError(new LayoutErrorMessage("circular_dependency", mName)); return; } currentChild.setLayoutParams(currentParams); } }
Source:
<code>private long <START> initialDelay(Config <END> rc, String section, long interval) { long delay = -1L; String start = rc.getString(section, null, KEY_STARTTIME); try { if (start != null) { DateTimeFormatter formatter = ISODateTimeFormat.hourMinute(); DateTime now = DateTime.now(); MutableDateTime startTime = now.toMutableDateTime(); LocalTime firstStartTime = null; LocalDateTime firstStartDateTime = null; try { firstStartTime = formatter.parseLocalTime(start); startTime.hourOfDay().set(firstStartTime.getHourOfDay()); startTime.minuteOfHour().set(firstStartTime.getMinuteOfHour()); } catch (IllegalArgumentException e1) { formatter = DateTimeFormat.forPattern("E HH:mm"); firstStartDateTime = formatter.parseLocalDateTime(start); startTime.dayOfWeek().set(firstStartDateTime.getDayOfWeek()); startTime.hourOfDay().set(firstStartDateTime.getHourOfDay()); startTime.minuteOfHour().set(firstStartDateTime.getMinuteOfHour()); } startTime.secondOfMinute().set(0); startTime.millisOfSecond().set(0); while (startTime.isBefore(now)) { startTime.add(interval); } while (startTime.getMillis() - now.getMillis() > interval) { startTime.add(-interval); } delay = startTime.getMillis() - now.getMillis(); } else { log.info(MessageFormat.format("{0} schedule parameter \"{0}.{1}\" is not configured", section, KEY_STARTTIME)); } } catch (IllegalArgumentException e2) { log.error(MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, KEY_STARTTIME), e2); } return delay; }</code><technical_language>I this unit tested</technical_language>

Target:
private static long initialDelay(Config rc, String section, long interval) { long delay = -1L; String start = rc.getString(section, null, KEY_STARTTIME); try { if (start != null) { DateTimeFormatter formatter = ISODateTimeFormat.hourMinute(); DateTime now = DateTime.now(); MutableDateTime startTime = now.toMutableDateTime(); LocalTime firstStartTime = null; LocalDateTime firstStartDateTime = null; try { firstStartTime = formatter.parseLocalTime(start); startTime.hourOfDay().set(firstStartTime.getHourOfDay()); startTime.minuteOfHour().set(firstStartTime.getMinuteOfHour()); } catch (IllegalArgumentException e1) { formatter = DateTimeFormat.forPattern("E HH:mm"); firstStartDateTime = formatter.parseLocalDateTime(start); startTime.dayOfWeek().set(firstStartDateTime.getDayOfWeek()); startTime.hourOfDay().set(firstStartDateTime.getHourOfDay()); startTime.minuteOfHour().set(firstStartDateTime.getMinuteOfHour()); } startTime.secondOfMinute().set(0); startTime.millisOfSecond().set(0); while (startTime.isBefore(now)) { startTime.add(interval); } while (startTime.getMillis() - now.getMillis() > interval) { startTime.add(-interval); } delay = startTime.getMillis() - now.getMillis(); } else { log.info(MessageFormat.format("{0} schedule parameter \"{0}.{1}\" is not configured", section, KEY_STARTTIME)); } } catch (IllegalArgumentException e2) { log.error(MessageFormat.format("Invalid {0} schedule parameter \"{0}.{1}\"", section, KEY_STARTTIME), e2); } return delay; }
Source:
<code>public static TokenResponse getTokenResponse(String googleClientID, String googleClientSecret, String code, String redirectUri) { final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), TokenResource.HTTP_TRANSPORT, TokenResource.JSON_FACTORY, new GenericUrl(GoogleHelper.GOOGLE_ENCODED_URL), new ClientParametersAuthentication(googleClientID, googleClientSecret), googleClientID, GoogleHelper.GOOGLE_AUTHORIZATION_SERVICE_ENCODED_URL).build(); try { return flow.newTokenRequest(code).setRedirectUri(redirectUri) .setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).execute(); } catch (IOException e) { LOG.error("Retrieving accessToken was unsuccessful"); <START> throw new CustomWebApplicationException("Could not retrieve google.com token based on code", HttpStatus.SC_BAD_REQUEST); <END> } }</code><technical_language>This is super minor, I google.com, typically logging in another domain, e.g., I log in a ucsc.edu domain. google token</technical_language>

Target:
public static TokenResponse getTokenResponse(String googleClientID, String googleClientSecret, String code, String redirectUri) { final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), TokenResource.HTTP_TRANSPORT, TokenResource.JSON_FACTORY, new GenericUrl(GoogleHelper.GOOGLE_ENCODED_URL), new ClientParametersAuthentication(googleClientID, googleClientSecret), googleClientID, GoogleHelper.GOOGLE_AUTHORIZATION_SERVICE_ENCODED_URL).build(); try { return flow.newTokenRequest(code).setRedirectUri(redirectUri) .setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).execute(); } catch (IOException e) { LOG.error("Retrieving accessToken was unsuccessful"); throw new CustomWebApplicationException("Could not retrieve google token based on code", HttpStatus.SC_BAD_REQUEST); } }
Source:
<code>private void onRemove() { ConfirmationModel model = (ConfirmationModel) <START> getWindow(); <END> if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> prms = getSelectedItems() .stream() .map(item -> new VmTemplateImportExportParameters(item.getId(), getEntity().getId(), storagePool.getId())) .collect(Collectors.toList()); Frontend.getInstance().runMultipleAction(ActionType.RemoveUnregisteredVmTemplate, prms, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }</code><technical_language>if(getWindow() == null) {return};</technical_language>

Target:
private void onRemove() { if (getWindow() != null) { return; } ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> vmTemplateImportExportParams = getSelectedItems() .stream() .map(item -> new VmTemplateImportExportParameters(item.getId(), getEntity().getId(), storagePool.getId())) .collect(Collectors.toList()); Frontend.getInstance().runMultipleAction( ActionType.RemoveUnregisteredVmTemplate, vmTemplateImportExportParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }