auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Object loadFromSecondLevelCache( final LoadEvent event, final EntityPersister persister, final EntityKey entityKey) { final SessionImplementor source = event.getSession(); final boolean skipCache = ( ! persister.canReadFromCache() ) || ( ! source.getCacheMode().isGetEnabled() ) || ( ! event.getLockMode().lessThan( LockMode.READ ) ); if ( skipCache ) { return null; } final Object ce = getFromSharedCache( event, persister, source ); if ( ce == null ) { return null; } return processCachedEntry( event, persister, ce, source, entityKey ); }

Target:
private Object loadFromSecondLevelCache( final LoadEvent event, final EntityPersister persister, final EntityKey entityKey) { final SessionImplementor source = event.getSession(); final boolean useCache = persister.canReadFromCache() && source.getCacheMode().isGetEnabled() && event.getLockMode().lessThan( LockMode.READ ); if ( !useCache ) { return null; } final Object ce = getFromSharedCache( event, persister, source ); if ( ce == null ) { return null; } return processCachedEntry( event, persister, ce, source, entityKey ); }
Source:
public String toString() { return getToStringBuilder().toString(); }

Target:
public final String toString() { return getToStringBuilder().toString(); }
Source:
public void onBackgroundTabSelected() { setItemMenuEnabled(true); runScenarioMenuItem.setEnabled(false); scenarioBackgroundGridWidget.clearSelections(); scenarioBackgroundGridWidget.select(); scenarioMainGridWidget.deselect(); populateRightDocks(TestToolsPresenter.IDENTIFIER); }

Target:
public void onBackgroundTabSelected() { setItemMenuEnabled(true); scenarioBackgroundGridWidget.clearSelections(); scenarioBackgroundGridWidget.select(); scenarioMainGridWidget.deselect(); populateRightDocks(TestToolsPresenter.IDENTIFIER); }
Source:
public Matrix removeColumn(int j, Factory factory) { if (j >= this.columns || j < 0) { throw new IllegalArgumentException("Illegal row number, must be 0.." + (this.columns - 1)); } Matrix that = factory.createMatrix(this.rows, this.columns - 1); for (int jj = 0; jj < j; jj++) { that.setColumn(jj, this.getColumn(jj)); } for (int jj = j + 1; jj < this.columns; jj++) { that.setRow(jj - 1, this.getRow(jj)); } return that; }

Target:
public Matrix removeColumn(int j, Factory factory) { if (j >= columns || j < 0) { throw new IndexOutOfBoundsException("Illegal row number, must be 0.." + (columns - 1)); } Matrix result = factory.createMatrix(rows, columns - 1); for (int jj = 0; jj < j; jj++) { result.setColumn(jj, getColumn(jj)); } for (int jj = j + 1; jj < columns; jj++) { result.setColumn(jj - 1, getColumn(jj)); } return result; }
Source:
public MailjetRequest parseToEmail(EmailWrapper wrapper) { MailjetRequest request = new MailjetRequest(Email.resource); request.property(Email.FROMEMAIL, wrapper.getSenderEmail()); if (wrapper.getSenderName() != null && !wrapper.getSenderName().isEmpty()) { request.property(Email.FROMNAME, wrapper.getSenderName()); } request.property(Email.RECIPIENTS, new JSONArray().put(new JSONObject().put("Email", wrapper.getRecipient()))); if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) { request.property(Email.BCC, new JSONArray().put(new JSONObject().put("Email", wrapper.getBcc()))); } request.property(Email.HEADERS, new JSONObject().put("Reply-To", wrapper.getReplyTo())); request.property(Email.SUBJECT, wrapper.getSubject()); request.property(Email.HTMLPART, wrapper.getContent()); request.property(Email.TEXTPART, Jsoup.parse(wrapper.getContent()).text()); return request; }

Target:
public MailjetRequest parseToEmail(EmailWrapper wrapper) { MailjetRequest request = new MailjetRequest(Email.resource); request.property(Email.FROMEMAIL, wrapper.getSenderEmail()); if (wrapper.getSenderName() != null && !wrapper.getSenderName().isEmpty()) { request.property(Email.FROMNAME, wrapper.getSenderName()); } request.property(Email.RECIPIENTS, new JSONArray().put(new JSONObject().put("Email", wrapper.getRecipient()))); if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) { request.append(Email.RECIPIENTS, new JSONObject().put("Email", wrapper.getBcc())); } request.property(Email.HEADERS, new JSONObject().put("Reply-To", wrapper.getReplyTo())); request.property(Email.SUBJECT, wrapper.getSubject()); request.property(Email.HTMLPART, wrapper.getContent()); request.property(Email.TEXTPART, Jsoup.parse(wrapper.getContent()).text()); return request; }
Source:
for (final String prefix : ArrayUtils.toArray("@p", "@a", "@r", "@e")) { selectorHandlers.put(prefix, vanillaHandler); registeringMods.put(prefix, "Minecraft"); }

Target:
for (final String prefix : ArrayUtils.toArray("@p", "@a", "@r", "@e")) { selectorHandlers.put(prefix, vanillaHandler); registeringMods.put(prefix, "minecraft"); }
Source:
private boolean skipToNextSegment(boolean deleteCurrent) throws IOException { PBDSegmentReader<M> segmentReader = m_segment.getReader(m_cursorId); if (segmentReader == null) { segmentReader = m_segment.openForRead(m_cursorId); } m_numRead += m_segment.getNumEntries() - segmentReader.readIndex(); segmentReader.markAllReadAndDiscarded(); Map.Entry<Long, PBDSegment<M>> entry = m_segments.higherEntry(m_segment.segmentIndex()); if (entry == null) { if (canDeleteSegmentsBefore(m_segment, 1)) { PBDSegment<M> deleteBefore = m_segment; m_deferredDeleter.execute(() -> deleteSegmentsBefore(deleteBefore)); } return false; } PBDSegment<M> oldSegment = m_segment; m_segment = entry.getValue(); PBDSegment<M> segmentToDeleteBefore = deleteCurrent ? m_segment : oldSegment; if (canDeleteSegmentsBefore(segmentToDeleteBefore, 1)) { m_deferredDeleter.execute(() -> deleteSegmentsBefore(segmentToDeleteBefore)); } return true; }

Target:
private boolean skipToNextSegment(boolean deleteCurrent) throws IOException { PBDSegmentReader<M> segmentReader = m_segment.getReader(m_cursorId); if (segmentReader == null) { segmentReader = m_segment.openForRead(m_cursorId); } m_numRead += m_segment.getNumEntries() - segmentReader.readIndex(); segmentReader.markAllReadAndDiscarded(); Map.Entry<Long, PBDSegment<M>> entry = m_segments.higherEntry(m_segment.segmentIndex()); if (entry == null) { callDeleteSegmentsBefore(m_segment, 1); return false; } PBDSegment<M> oldSegment = m_segment; m_segment = entry.getValue(); PBDSegment<M> segmentToDeleteBefore = deleteCurrent ? m_segment : oldSegment; callDeleteSegmentsBefore(segmentToDeleteBefore, 1); return true; }
Source:
public void testCreateTableWithUnsupportedType() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); try { metadata.createTable(SESSION, getOrdersTableWithUnsupportedType(ImmutableMap.of()), false); assert (false); } catch (PrestoException pe) { assertEquals(pe.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } }

Target:
public void testCreateTableWithUnsupportedType() { assertNull(metadata.getTableHandle(SESSION, DEFAULT_TEST_ORDERS)); ConnectorTableMetadata raptorMetadata = buildTable(ImmutableMap.of(), tableMetadataBuilder(DEFAULT_TEST_ORDERS) .column("orderkey", BIGINT) .column("rowtype", RowType.withDefaultFieldNames(ImmutableList.of(BIGINT)))); try { metadata.createTable(SESSION, raptorMetadata, false); fail(); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_SUPPORTED.toErrorCode()); } }
Source:
public Builder config(@NonNull Bitmap.Config config) { if (config == null) { throw new IllegalArgumentException("tag == null"); } this.config = config; return this; }

Target:
public Builder config(@NonNull Bitmap.Config config) { if (config == null) { throw new IllegalArgumentException("config == null"); } this.config = config; return this; }
Source:
public void testCopyWithoutCompaction() throws Exception { command.repoURI = repoUri; command.noCompaction = true; command.datasets = Lists.newArrayList(source, dest); int rc = command.run(); Assert.assertEquals("Should return success", 0, rc); DatasetRepository repo = DatasetRepositories.open("repo:" + repoUri); int size = DatasetTestUtilities.datasetSize(repo.load(dest)); Assert.assertEquals("Should contain copied records", 6, size); verify(console).info("Added records to \"{}\"", 6l, dest); verifyNoMoreInteractions(console); }

Target:
public void testCopyWithoutCompaction() throws Exception { command.repoURI = repoUri; command.noCompaction = true; command.datasets = Lists.newArrayList(source, dest); int rc = command.run(); Assert.assertEquals("Should return success", 0, rc); DatasetRepository repo = DatasetRepositories.open("repo:" + repoUri); FileSystemDataset<GenericData.Record> ds = (FileSystemDataset<GenericData.Record>) repo.<GenericData.Record> load(dest); int size = DatasetTestUtilities.datasetSize(ds); Assert.assertEquals("Should contain copied records", 6, size); Assert.assertEquals("Should produce 1 files", 1, Iterators.size(ds.pathIterator())); verify(console).info("Added records to \"{}\"", 6l, dest); verifyNoMoreInteractions(console); }
Source:
protected ImmutableValue<DyeColor> constructImmutableValue(DyeColor value) { return constructValue(value).asImmutable(); }

Target:
protected ImmutableValue<DyeColor> constructImmutableValue(DyeColor value) { return ImmutableSpongeValue.cachedOf(Keys.DYE_COLOR, DyeColors.PURPLE, value); }
Source:
public BlobServiceClient createBlobStorageClient(CloudConfig cloudConfig, AzureCloudConfig azureCloudConfig) throws MalformedURLException, InterruptedException, ExecutionException { validateABSAuthConfigs(azureCloudConfig); Configuration storageConfiguration = new Configuration(); ProxyOptions proxyOptions = (cloudConfig.vcrProxyHost == null) ? null : new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(cloudConfig.vcrProxyHost, cloudConfig.vcrProxyPort)); if (proxyOptions != null) { logger.info("Using proxy: {}:{}", cloudConfig.vcrProxyHost, cloudConfig.vcrProxyPort); } HttpClient client = new NettyAsyncHttpClientBuilder().proxy(proxyOptions).build(); RequestRetryOptions noRetries = new RequestRetryOptions(RetryPolicyType.FIXED, 1, null, null, null, null); return buildBlobServiceClient(client, storageConfiguration, noRetries, azureCloudConfig); }

Target:
public BlobServiceClient createBlobStorageClient(CloudConfig cloudConfig, AzureCloudConfig azureCloudConfig) { validateABSAuthConfigs(azureCloudConfig); Configuration storageConfiguration = new Configuration(); ProxyOptions proxyOptions = (cloudConfig.vcrProxyHost == null) ? null : new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress(cloudConfig.vcrProxyHost, cloudConfig.vcrProxyPort)); if (proxyOptions != null) { logger.info("Using proxy: {}:{}", cloudConfig.vcrProxyHost, cloudConfig.vcrProxyPort); } HttpClient client = new NettyAsyncHttpClientBuilder().proxy(proxyOptions).build(); RequestRetryOptions noRetries = new RequestRetryOptions(RetryPolicyType.FIXED, 1, null, null, null, null); try { return buildBlobServiceClient(client, storageConfiguration, noRetries, azureCloudConfig); } catch (MalformedURLException | InterruptedException | ExecutionException ex) { logger.error("Error building ABS blob service client: {}", ex.getMessage()); throw new IllegalStateException(ex); } }
Source:
public void shouldCloseWrappedStoreAfterErrorDuringCacheFlush() { setUpCloseTests(); cache.flush(CACHE_NAMESPACE); EasyMock.expectLastCall().andThrow(new NullPointerException("Simulating an error on flush")); EasyMock.replay(cache); EasyMock.reset(keyValueStore); keyValueStore.close(); EasyMock.replay(keyValueStore); try { store.close(); } catch (final NullPointerException npe) { EasyMock.verify(keyValueStore); } }

Target:
public void shouldCloseWrappedStoreAfterErrorDuringCacheFlush() { setUpCloseTests(); cache.flush(CACHE_NAMESPACE); EasyMock.expectLastCall().andThrow(new NullPointerException("Simulating an error on flush")); EasyMock.replay(cache); EasyMock.reset(underlyingStore); underlyingStore.close(); EasyMock.replay(underlyingStore); try { store.close(); } catch (final RuntimeException exception) { EasyMock.verify(underlyingStore); } }
Source:
private void loadInitialState(ITmfStateProvider provider) { for (ITmfStateSystem ss : getStateSystems()) { if (ss instanceof ITmfStateSystemBuilder) { ITmfStateSystemBuilder ssb = (ITmfStateSystemBuilder) ss; final ITmfTrace trace = getTrace(); if (trace == null) { throw new IllegalStateException(); } final long startTime = trace.getStartTime().toNanos(); StateSnapshot snapshot = StateSnapshot.read(Paths.get(trace.getPath()), ss.getSSID()); if (snapshot == null || provider.getVersion() != snapshot.getVersion()) { continue; } for (Entry<List<String>, ITmfStateInterval> attributeSnapshot : snapshot.getStates().entrySet()) { List<String> attributePath = Objects.requireNonNull(attributeSnapshot.getKey()); int quark = ssb.getQuarkAbsoluteAndAdd(attributePath.toArray(new String[attributePath.size()])); Object initialState = Objects.requireNonNull(attributeSnapshot.getValue()).getValue(); ssb.modifyAttribute(startTime, initialState, quark); } } } }

Target:
private void loadInitialState(ITmfStateProvider provider) { for (ITmfStateSystem ss : getStateSystems()) { if (ss instanceof ITmfStateSystemBuilder) { ITmfStateSystemBuilder ssb = (ITmfStateSystemBuilder) ss; final ITmfTrace trace = getTrace(); if (trace == null) { throw new IllegalStateException(); } final long startTime = trace.getStartTime().toNanos(); StateSnapshot snapshot = StateSnapshot.read(Paths.get(trace.getPath()), ss.getSSID()); if (snapshot == null || provider.getVersion() != snapshot.getVersion()) { continue; } for (Entry<List<String>, ITmfStateInterval> attributeSnapshot : snapshot.getStates().entrySet()) { List<String> attributePath = Objects.requireNonNull(attributeSnapshot.getKey()); int quark = ssb.getQuarkAbsoluteAndAdd(attributePath.toArray(new String[attributePath.size()])); ITmfStateInterval interval = Objects.requireNonNull(attributeSnapshot.getValue()); Object initialState = interval.getValue(); ssb.modifyAttribute(Math.max(interval.getStartTime(), ssb.getStartTime()), initialState, quark); } } } }
Source:
public String getResponseString() { if (response == null) return ""; return HexUtils.byteArrayToHexString(response).replace("\n", ""); }

Target:
public String getResponseString() { if (response == null) return null; return HexUtils.byteArrayToHexString(response).replace("\n", ""); }
Source:
public static int[] calculateWrapOffsets(final String line, final int maxLineLength) { if (line.length() == 0) return null; IntList wrapOffsets = new IntList(); int wordStart = 0; int lineStart = 0; boolean wasSpace = true; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (ch == ' ') { wasSpace = true; } else if (ch == '\r' || ch == '\n') { lineStart = i + 1; wordStart = i + 1; wasSpace = false; } else { if (wasSpace) { wasSpace = false; wordStart = i; } if (i >= lineStart + maxLineLength) { if (wordStart != lineStart) { wrapOffsets.add(wordStart); lineStart = wordStart; } } } } int size = wrapOffsets.size(); if (size == 0) { return null; } else { int[] result = new int[size]; for (int i= 0; i < size; i++) { result[i] = wrapOffsets.get(i); } return result; } }

Target:
public static int[] calculateWrapOffsets(final String line, final int maxLineLength) { if (line.length() == 0) return null; IntList wrapOffsets = new IntList(); int wordStart = 0; int lineStart = 0; boolean lastWasSpace = true; boolean onlySpaces = true; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (ch == ' ') { lastWasSpace = true; } else if (ch == '\n') { lineStart = i + 1; wordStart = i + 1; lastWasSpace = true; onlySpaces = true; } else { if (lastWasSpace) { lastWasSpace = false; if (!onlySpaces) { wordStart = i; } } else { onlySpaces = false; } if (i >= lineStart + maxLineLength) { if (wordStart != lineStart) { wrapOffsets.add(wordStart); lineStart = wordStart; onlySpaces = true; } } } } int size = wrapOffsets.size(); if (size == 0) { return null; } else { int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = wrapOffsets.get(i); } return result; } }
Source:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { BigDecimal result = null; for (int i=0; i<children.size(); i++) { Expression childExpr = children.get(i); if (!childExpr.evaluate(tuple, ptr) || ptr.getLength() == 0) { return false; } PDataType childType = children.get(i).getDataType(); BigDecimal bd= (BigDecimal)PDataType.DECIMAL.toObject(ptr, childType); if (result == null) { result = bd; maxLength = childExpr.getMaxLength(); scale = childExpr.getScale(); } else { result = result.divide(bd, NumberUtil.DEFAULT_MATH_CONTEXT); if (maxLength != null && scale != null && childExpr.getMaxLength() != null & childExpr.getScale() != null) { int desiredPrecision = NumberUtil.getDecimalPrecision(NumericOperators.DIVIDE, maxLength, childExpr.getMaxLength(), scale, childExpr.getScale()); int desiredScale = NumberUtil.getDecimalScale(NumericOperators.DIVIDE, maxLength, childExpr.getMaxLength(), scale, childExpr.getScale()); result = NumberUtil.setDecimalWidthAndScale(result, desiredPrecision, desiredScale); if (result == null) { return false; } maxLength = desiredPrecision; scale = desiredScale; } } } ptr.set(PDataType.DECIMAL.toBytes(result)); return true; }

Target:
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) { BigDecimal result = null; for (int i=0; i<children.size(); i++) { Expression childExpr = children.get(i); if (!childExpr.evaluate(tuple, ptr)) { return false; } if (ptr.getLength() == 0) { return true; } PDataType childType = children.get(i).getDataType(); BigDecimal bd= (BigDecimal)PDataType.DECIMAL.toObject(ptr, childType); if (result == null) { result = bd; } else { result = result.divide(bd, PDataType.DEFAULT_MATH_CONTEXT); } } if (maxLength != null && scale != null) { result = NumberUtil.setDecimalWidthAndScale(result, maxLength, scale); } if (result == null) { return false; } ptr.set(PDataType.DECIMAL.toBytes(result)); return true; }
Source:
protected LogSubmitOutcomes doInBackground(Void... params) { try { SqlStorage<DeviceReportRecord> storage = CommCareApplication._().getUserStorage(DeviceReportRecord.class); if (serializeCurrentLogs) { if (!serializeLogs(storage)) { return LogSubmitOutcomes.Error; } } int numberOfLogsToSubmit = storage.getNumRecords(); if (numberOfLogsToSubmit == 0) { return LogSubmitOutcomes.Submitted; } this.beginSubmissionProcess(numberOfLogsToSubmit); ArrayList<Integer> submittedSuccesfullyIds = new ArrayList<>(); ArrayList<DeviceReportRecord> submittedSuccesfully = new ArrayList<>(); submitReports(storage, submittedSuccesfullyIds, submittedSuccesfully); if (!removeLocalReports(storage, submittedSuccesfullyIds, submittedSuccesfully)) { return LogSubmitOutcomes.Serialized; } return checkSubmissionResult(numberOfLogsToSubmit, submittedSuccesfully); } catch (UserStorageClosedException e) { return LogSubmitOutcomes.Error; } }

Target:
protected LogSubmitOutcomes doInBackground(Void... params) { try { SqlStorage<DeviceReportRecord> storage = CommCareApplication._().getUserStorage(DeviceReportRecord.class); if (serializeCurrentLogs && !serializeLogs(storage)) { return LogSubmitOutcomes.Error; } int numberOfLogsToSubmit = storage.getNumRecords(); if (numberOfLogsToSubmit == 0) { return LogSubmitOutcomes.Submitted; } this.beginSubmissionProcess(numberOfLogsToSubmit); ArrayList<Integer> submittedSuccesfullyIds = new ArrayList<>(); ArrayList<DeviceReportRecord> submittedSuccesfully = new ArrayList<>(); submitReports(storage, submittedSuccesfullyIds, submittedSuccesfully); if (!removeLocalReports(storage, submittedSuccesfullyIds, submittedSuccesfully)) { return LogSubmitOutcomes.Serialized; } return checkSubmissionResult(numberOfLogsToSubmit, submittedSuccesfully); } catch (UserStorageClosedException e) { return LogSubmitOutcomes.Error; } }
Source:
public Map<String, ValidationReport> uploadProject(final Project project, final File archive, final String fileType, final User uploader, final Props additionalProps) throws ProjectManagerException { log.info("Uploading files to " + project.getName()); final Props prop = new Props(this.props); prop.putAll(additionalProps); final File file = unzipProject(archive, fileType); final Map<String, ValidationReport> reports = validateProject(project, archive, file, prop); final DirectoryFlowLoader directoryFlowLoader = new DirectoryFlowLoader(prop); reports.put(DIRECTORY_FLOW_REPORT_KEY, directoryFlowLoader.loadProject(project, file)); if(!isReportStatusValid(reports, project, file)) { return reports; } persistProject(project, archive, uploader); cleanUpProject(project, file); return reports; }

Target:
public Map<String, ValidationReport> uploadProject(final Project project, final File archive, final String fileType, final User uploader, final Props additionalProps) throws ProjectManagerException { log.info("Uploading files to " + project.getName()); final Map<String, ValidationReport> reports; final Props prop = new Props(this.props); prop.putAll(additionalProps); File file = null; try { file = unzipProject(archive, fileType); reports = validateProject(project, archive, file, prop); final DirectoryFlowLoader directoryFlowLoader = new DirectoryFlowLoader(prop); reports.put(DIRECTORY_FLOW_REPORT_KEY, directoryFlowLoader.loadProject(project, file)); } finally { cleanUpProjectTempDir(file); } if (!isReportStatusValid(reports, project)) { return reports; } persistProject(project, archive, uploader); cleanUpProjectOldInstallations(project); return reports; }
Source:
public static Cost calculate(final Collection<EvaluatorParameters> activeEvaluators) { final EvaluatorParameters ctlTaskEvaluatorParameters = getControllerTaskParameters(activeEvaluators); final Collection<EvaluatorParameters> cmpTasksEvaluatorParameters = getComputeTaskParameters(activeEvaluators); final Collection<Cost.ComputeTaskCost> computeTaskCosts = getComputeTaskCosts(cmpTasksEvaluatorParameters); final double communicationCost = getCommunicationCost(ctlTaskEvaluatorParameters, computeTaskCosts); return new Cost(communicationCost, computeTaskCosts); }

Target:
public static Cost calculate(final Collection<EvaluatorParameters> activeEvaluators) { final DolphinTaskParameters dolphinTaskParams = getDolphinTaskParameters(activeEvaluators); final Collection<Cost.ComputeTaskCost> computeTaskCosts = getComputeTaskCosts(dolphinTaskParams.getComputeTasksParameters()); final double communicationCost = getCommunicationCost(dolphinTaskParams.getControllerTaskParameters(), computeTaskCosts); return new Cost(communicationCost, computeTaskCosts); }
Source:
private ResponseHandler<Object> createExecResponseHandler(LogOutputSpec outputSpec) throws FileNotFoundException { final LogCallback callback = createLogCallback(outputSpec); return new ResponseHandler<Object>() { @Override public Object handleResponse(HttpResponse response) throws IOException { try (InputStream stream = response.getEntity().getContent()) { LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream)); String line; try { while ( (line = reader.readLine()) != null) { callback.log(1, new Timestamp(), line); } } catch (LogCallback.DoneException e) { } } return null; } }; }

Target:
private ResponseHandler<Object> createExecResponseHandler(LogOutputSpec outputSpec) throws FileNotFoundException { final LogCallback callback = new DefaultLogCallback(outputSpec); return new ResponseHandler<Object>() { @Override public Object handleResponse(HttpResponse response) throws IOException { try (InputStream stream = response.getEntity().getContent()) { LineNumberReader reader = new LineNumberReader(new InputStreamReader(stream)); String line; try { callback.open(); while ( (line = reader.readLine()) != null) { callback.log(1, new Timestamp(), line); } } catch (LogCallback.DoneException e) { } finally { callback.close(); } } return null; } }; }
Source:
public static Predicate<Resource> createTestApiLiquibaseChangelogFilter() { return r -> { try { URI uri = r.getURI(); return (uri.getScheme().equals("file") && uri.toString().contains("test-api/schema")) || (uri.getScheme().equals("jar") && uri.toString().contains("test-api.schema")); } catch (IOException e) { return false; } }; }

Target:
public static final Predicate<Resource> createTestApiLiquibaseChangelogFilter() { return r -> { try { URI uri = r.getURI(); return (uri.getScheme().equals("file") && uri.toString().contains("test-api/schema")) || (uri.getScheme().equals("jar") && uri.toString().contains("test-api.schema")); } catch (IOException e) { return false; } }; }
Source:
private void unmarshalAndInsert(byte[] factBytes, Class<?> clazz) { try { String packageName = clazz.getPackage().getName(); String className = clazz.getSimpleName(); FactType factType = getFactType(packageName, className); if (factType != null) { m_kieSession.insert(DroolsStreamUtils.streamIn(factBytes, factType.getFactClass().getClassLoader())); } else { m_kieSession.insert(DroolsStreamUtils.streamIn(factBytes, clazz.getClassLoader())); } } catch (IOException | ClassNotFoundException e) { LOG.error("Exception while unmarshalling fact with class {}", factBytes, clazz.getCanonicalName()); } }

Target:
private void unmarshalAndInsert(byte[] factBytes, Class<?> clazz) { try { String packageName = clazz.getPackage().getName(); String className = clazz.getSimpleName(); FactType factType = getDeclaredFactType(packageName, className); if (factType != null) { m_kieSession.insert(DroolsStreamUtils.streamIn(factBytes, factType.getFactClass().getClassLoader())); } else { m_kieSession.insert(DroolsStreamUtils.streamIn(factBytes, clazz.getClassLoader())); } } catch (IOException | ClassNotFoundException e) { LOG.error("Exception while unmarshalling fact of size with Class {}", factBytes.length, clazz.getCanonicalName()); } }
Source:
public static String generate(String derivedClassName, ClassModel classModel) { final List<MethodModel> methodModels = classModel.getMethods().stream() .filter(method -> method.isAnnotatedWith(Unapply.class)) .collect(toList()); final String _package = classModel.getPackageName(); final ImportManager im = ImportManager.forClass(classModel, "javaslang.API.Match"); final String methods = generate(im, classModel, methodModels); return " (_package.isEmpty() ? "" : "package " + _package + ";\n\n") + im.getImports() + "\n\n "public final class " + derivedClassName + " {\n\n" + " private " + derivedClassName + "() {\n" + " }\n\n" + methods + "}\n" + " }

Target:
public static String generate(String derivedClassName, ClassModel classModel) { final List<MethodModel> methodModels = classModel.getMethods().stream() .filter(method -> method.isAnnotatedWith(Unapply.class)) .collect(toList()); final String _package = classModel.getPackageName(); final ImportManager im = ImportManager.forClass(classModel, "javaslang.API.Match"); final String methods = generate(im, classModel, methodModels); return " " (_package.isEmpty() ? "" : "package " + _package + ";\n\n") + im.getImports() + "\n\n "public final class " + derivedClassName + " {\n\n" + " private " + derivedClassName + "() {\n" + " }\n\n" + methods + "}\n" + " " }
Source:
public void ClearTasks() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { if (task.getLastTaskStatus().getStatus() == AsyncTaskStatusEnum.finished) { task.clearAsyncTask(); if (task.getVdsmTaskId() != null) { _listTasks.remove(task.getVdsmTaskId()); } } } } }

Target:
public void ClearTasks() { synchronized (_listTasks) { java.util.ArrayList<CommandAsyncTask> CurrentActionTypeTasks = getCurrentTasks(); for (CommandAsyncTask task : CurrentActionTypeTasks) { if (task.getLastTaskStatus().getStatus() == AsyncTaskStatusEnum.finished) { task.clearAsyncTask(); _listTasks.remove(task.getVdsmTaskId()); } } } }
Source:
void incClearCount(LocalRegion lr) { if (lr != null && !(lr instanceof HARegion)) { CachePerfStats stats = lr.getCachePerfStats(); if (stats != null) { if (lr instanceof BucketRegion) { stats.incBucketClearCount(); } else { stats.incRegionClearCount(); } } } }

Target:
void incClearCount(LocalRegion lr) { if (lr != null && !(lr instanceof HARegion)) { CachePerfStats stats = lr.getCachePerfStats(); if (stats != null) { if (lr.isUsedForPartitionedRegionBucket()) { stats.incBucketClearCount(); } else { stats.incRegionClearCount(); } } } }
Source:
private Set<String> locationRequestToRegions(LocationRequest location, String cloudPlatform) { if (AWS.name().equals(cloudPlatform)) { return Set.of(location.getName()); } else if (AZURE.name().equals(cloudPlatform)) { return Set.of(location.getName()); } return Set.of(); }

Target:
private Set<String> locationRequestToRegions(LocationRequest location, String cloudPlatform) { return Set.of(location.getName()); }
Source:
private void readResponseToFindActiveComponents() throws IOException { InputStream in = telnet.getInputStream(); BufferedReader inBuff = new BufferedReader(new InputStreamReader(in, "UTF-8")); String inputLine; while ((inputLine = inBuff.readLine()) != null) { if (inputLine.contains("Active")) { arrList.add(inputLine); log.info(inputLine); break; } } inBuff.close(); out.close(); }

Target:
private void readResponseToFindActiveComponents() throws CarbonToolsIntegrationTestException { InputStream in = telnet.getInputStream(); try { BufferedReader inBuff = new BufferedReader(new InputStreamReader(in, "UTF-8")); String inputLine; while ((inputLine = inBuff.readLine()) != null) { if (inputLine.contains("Active")) { arrList.add(inputLine); log.info(inputLine); break; } } inBuff.close(); } catch (IOException ex) { log.error("Error while reading input stream ", ex); throw new CarbonToolsIntegrationTestException("Error while reading input stream ", ex); } out.close(); }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); final ProfileModel model = new PrefManager(getActivity(), PrefManager.Pref.LOGIN).getCurrentUserProfile(); isViewingOwnProfile = null != model && model.username.equalsIgnoreCase(username); getAccountTask = new GetAccountTask(getActivity(), username) { @Override protected void onSuccess(Account account) throws Exception { UserProfileFragment.this.account = account; if (null != viewHolder) { viewHolder.setAccount(account); } } }; getAccountTask.setTaskProcessCallback(null); getAccountTask.execute(); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); final ProfileModel model = new PrefManager(getActivity(), PrefManager.Pref.LOGIN).getCurrentUserProfile(); isViewingOwnProfile = null != model && model.username.equalsIgnoreCase(username); }
Source:
private List stageHistoryAsJson(PipelineInstanceModel pipelineInstanceModel, StageInstanceModels stageHistory) { List json = new ArrayList(); for (StageInstanceModel stageHistoryItem : stageHistory) { Map<String, Object> jsonMap = new LinkedHashMap<>(); jsonMap.put("stageName", stageHistoryItem.getName()); jsonMap.put("stageId", stageHistoryItem.getId()); jsonMap.put("stageStatus", stageHistoryItem.getState().toString()); StageIdentifier stageIdentifier = new StageIdentifier(pipelineInstanceModel.getPipelineIdentifier(), stageHistoryItem.getName(), stageHistoryItem.getCounter()); jsonMap.put("stageLocator", encodeInUtf8(stageIdentifier.stageLocator())); jsonMap.put("getCanRun", Boolean.toString(stageHistoryItem.getCanRun())); if (!stageHistoryItem.getCanRun()) { jsonMap.put("getErrorMessage", stageHistoryItem.getErrorMessage()); } jsonMap.put("getCanCancel", Boolean.toString(stageHistoryItem.getCanCancel())); jsonMap.put("scheduled", Boolean.toString(stageHistoryItem.isScheduled())); jsonMap.put("stageCounter", stageHistoryItem.getCounter()); handleApproval(stageHistoryItem, jsonMap); json.add(jsonMap); } return json; }

Target:
private List stageHistoryAsJson(PipelineInstanceModel pipelineInstanceModel, StageInstanceModels stageHistory) { List json = new ArrayList(); for (StageInstanceModel stageHistoryItem : stageHistory) { Map<String, Object> jsonMap = new LinkedHashMap<>(); jsonMap.put("stageName", stageHistoryItem.getName()); jsonMap.put("stageId", stageHistoryItem.getId()); jsonMap.put("stageStatus", stageHistoryItem.getState().toString()); StageIdentifier stageIdentifier = new StageIdentifier(pipelineInstanceModel.getPipelineIdentifier(), stageHistoryItem.getName(), stageHistoryItem.getCounter()); jsonMap.put("stageLocator", encodeInUtf8(stageIdentifier.stageLocator())); jsonMap.put("getCanRun", Boolean.toString(stageHistoryItem.getCanRun())); if (!stageHistoryItem.getCanRun()) { jsonMap.put("errorMessage", stageHistoryItem.getErrorMessage()); } jsonMap.put("getCanCancel", Boolean.toString(stageHistoryItem.getCanCancel())); jsonMap.put("scheduled", Boolean.toString(stageHistoryItem.isScheduled())); jsonMap.put("stageCounter", stageHistoryItem.getCounter()); handleApproval(stageHistoryItem, jsonMap); json.add(jsonMap); } return json; }
Source:
public static DialogueChatHandler queue(int max) { checkArgument(max > 0, "max > 0"); return new QueueingChatHandler(max); }

Target:
public static DialogueChatHandler queue(int max) { checkArgument(max > 0, "max must be greater than 0"); return new QueueingChatHandler(max); }
Source:
public boolean isValid() { return StringUtils.equals(NAME_PROPERTY, type) && properties != null && properties.keySet().size() == 1 && properties.containsKey(NAME_PROPERTY) && properties.get(NAME_PROPERTY).startsWith("EPSG"); }

Target:
public boolean isValid() { return NAME_PROPERTY.equals(type) && properties != null && properties.keySet().size() == 1 && properties.containsKey(NAME_PROPERTY) && properties.get(NAME_PROPERTY).startsWith("EPSG"); }
Source:
public static CreateDevice create(final String hostname, final String plan, final String billingCycle, final String facility, final Map<String, String> features, final String operatingSystem, final Boolean locked, final String userdata, final Set<String> tags) { return builder() .hostname(hostname) .plan(plan) .billingCycle(billingCycle) .facility(facility) .features(features) .operatingSystem(operatingSystem) .locked(locked) .userdata(userdata) .tags(tags) .build(); }

Target:
private static CreateDevice create(final String hostname, final String plan, final String billingCycle, final String facility, final Map<String, String> features, final String operatingSystem, final Boolean locked, final String userdata, final Set<String> tags) { return builder() .hostname(hostname) .plan(plan) .billingCycle(billingCycle) .facility(facility) .features(features) .operatingSystem(operatingSystem) .locked(locked) .userdata(userdata) .tags(tags) .build(); }
Source:
private void updateChapterPages() { final boolean wasOrganizer = mViewPagerAdapter != null && mViewPagerAdapter.getCount() == ORGANIZER_PAGES.length; if (organizerCheckCallback != null) { organizerCheckCallback.cancel(); } organizerCheckCallback = new OrganizerCheckCallback(wasOrganizer); App.getInstance().checkOrganizer( getGoogleApiClient(), organizerCheckCallback ); }

Target:
private void updateChapterPages() { if (organizerCheckCallback != null) { organizerCheckCallback.cancel(); } organizerCheckCallback = new OrganizerCheckCallback(isOrganizerFragmentShown()); App.getInstance().checkOrganizer( getGoogleApiClient(), organizerCheckCallback ); }
Source:
public final TmfModelResponse<List<M>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { if (fCached != null) { return fCached; } fAnalysisModule.waitForInitialization(); ITmfStateSystem ss = fAnalysisModule.getStateSystem(); if (ss == null) { return new TmfModelResponse<>(null, ITmfResponse.Status.FAILED, CommonStatusMessage.STATE_SYSTEM_FAILED); } boolean complete = ss.waitUntilBuilt(0); try (FlowScopeLog scope = new FlowScopeLogBuilder(LOGGER, Level.FINE, "AbstractTreeDataProvider#fetchTree") .setCategory(getClass().getSimpleName()).build()) { synchronized (fIdToQuark) { List<M> tree = getTree(ss, filter, monitor); if (complete) { TmfModelResponse<List<M>> response = new TmfModelResponse<>(tree, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); if (isCacheable()) { fCached = response; } return response; } return new TmfModelResponse<>(tree, ITmfResponse.Status.RUNNING, CommonStatusMessage.RUNNING); } } catch (StateSystemDisposedException e) { return new TmfModelResponse<>(null, ITmfResponse.Status.FAILED, CommonStatusMessage.STATE_SYSTEM_FAILED); } }

Target:
public final TmfModelResponse<List<M>> fetchTree(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { if (fCached != null) { return fCached; } fAnalysisModule.waitForInitialization(); ITmfStateSystem ss = fAnalysisModule.getStateSystem(); if (ss == null) { return new TmfModelResponse<>(null, ITmfResponse.Status.FAILED, CommonStatusMessage.STATE_SYSTEM_FAILED); } boolean complete = ss.waitUntilBuilt(0); fLock.writeLock().lock(); try (FlowScopeLog scope = new FlowScopeLogBuilder(LOGGER, Level.FINE, "AbstractTreeDataProvider#fetchTree") .setCategory(getClass().getSimpleName()).build()) { List<M> tree = getTree(ss, filter, monitor); if (complete) { TmfModelResponse<List<M>> response = new TmfModelResponse<>(tree, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); if (isCacheable()) { fCached = response; } return response; } return new TmfModelResponse<>(tree, ITmfResponse.Status.RUNNING, CommonStatusMessage.RUNNING); } catch (StateSystemDisposedException e) { return new TmfModelResponse<>(null, ITmfResponse.Status.FAILED, CommonStatusMessage.STATE_SYSTEM_FAILED); } finally { fLock.writeLock().unlock(); } }
Source:
public ZkCloudname connectWithTimeout(long waitTime, TimeUnit waitUnit) { try { zk = new ZooKeeper(connectString, SESSION_TIMEOUT, this); if (! connectedSignal.await(waitTime, waitUnit)) { throw new CloudnameException.CouldNotConnectToStorage(new RuntimeException( "Connecting to ZooKeeper timed out.")); } log.info("Connected to ZooKeeper " + connectString); } catch (IOException e) { throw new CloudnameException.CouldNotConnectToStorage(e); } catch (InterruptedException e) { throw new CloudnameException.CouldNotConnectToStorage(e); } return this; }

Target:
public ZkCloudname connectWithTimeout(long waitTime, TimeUnit waitUnit) { try { zk = new ZooKeeper(connectString, SESSION_TIMEOUT, this); if (! connectedSignal.await(waitTime, waitUnit)) { throw new CloudnameException.CouldNotConnectToStorage( "Connecting to ZooKeeper timed out."); } log.info("Connected to ZooKeeper " + connectString); } catch (IOException e) { throw new CloudnameException.CouldNotConnectToStorage(e); } catch (InterruptedException e) { throw new CloudnameException.CouldNotConnectToStorage(e); } return this; }
Source:
protected Object invokeInNoTx(InterceptorContext invocation, final EJBComponent component) throws Exception { try { return invocation.proceed(); } catch (EJBException | RemoteException e) { throw e; } catch (RuntimeException e) { throw new EJBException(e); } catch (Exception e) { throw e; } catch (Error e) { ApplicationExceptionDetails ae = component.getApplicationException(e.getClass(), invocation.getMethod()); if (ae != null) { throw e; } else { throw EjbLogger.ROOT_LOGGER.unexpectedError(e); } } catch (Throwable t2) { throw new UndeclaredThrowableException(t2); } }

Target:
protected Object invokeInNoTx(InterceptorContext invocation, final EJBComponent component) throws Exception { try { return invocation.proceed(); } catch (Error e) { throw EjbLogger.ROOT_LOGGER.unexpectedError(e); } catch (EJBException e) { throw e; } catch (RuntimeException e) { ApplicationExceptionDetails ae = component.getApplicationException(e.getClass(), invocation.getMethod()); throw ae != null ? e : new EJBException(e); } catch (Exception e) { throw e; } catch (Throwable t) { throw new EJBException(new UndeclaredThrowableException(t)); } }
Source:
public List<Protos.Key> serializeToProtobuf() { lock.lock(); try { LinkedList<Protos.Key> entries = newLinkedList(); boolean isWatchingChain = false; if (seed != null) { Protos.Key.Builder seedEntry = BasicKeyChain.serializeEncryptableItem(seed); seedEntry.setType(Protos.Key.Type.DETERMINISTIC_ROOT_SEED); entries.add(seedEntry.build()); } else { isWatchingChain = true; } Map<ECKey, Protos.Key.Builder> keys = basicKeyChain.serializeToEditableProtobufs(); for (Map.Entry<ECKey, Protos.Key.Builder> entry : keys.entrySet()) { DeterministicKey key = (DeterministicKey) entry.getKey(); Protos.Key.Builder proto = entry.getValue(); proto.setType(Protos.Key.Type.DETERMINISTIC_KEY); final Protos.DeterministicKey.Builder detKey = proto.getDeterministicKeyBuilder(); detKey.setChainCode(ByteString.copyFrom(key.getChainCode())); for (ChildNumber num : key.getPath()) detKey.addPath(num.i()); if (key.equals(externalKey)) { detKey.setIssuedSubkeys(issuedExternalKeys); detKey.setLookaheadSize(lookaheadSize); } else if (key.equals(internalKey)) { detKey.setIssuedSubkeys(issuedInternalKeys); detKey.setLookaheadSize(lookaheadSize); } if (entries.isEmpty() && isWatchingChain) { detKey.setIsFollowing(true); } entries.add(proto.build()); } return entries; } finally { lock.unlock(); } }

Target:
public List<Protos.Key> serializeToProtobuf() { lock.lock(); try { LinkedList<Protos.Key> entries = newLinkedList(); if (seed != null) { Protos.Key.Builder seedEntry = BasicKeyChain.serializeEncryptableItem(seed); seedEntry.setType(Protos.Key.Type.DETERMINISTIC_ROOT_SEED); entries.add(seedEntry.build()); } Map<ECKey, Protos.Key.Builder> keys = basicKeyChain.serializeToEditableProtobufs(); for (Map.Entry<ECKey, Protos.Key.Builder> entry : keys.entrySet()) { DeterministicKey key = (DeterministicKey) entry.getKey(); Protos.Key.Builder proto = entry.getValue(); proto.setType(Protos.Key.Type.DETERMINISTIC_KEY); final Protos.DeterministicKey.Builder detKey = proto.getDeterministicKeyBuilder(); detKey.setChainCode(ByteString.copyFrom(key.getChainCode())); for (ChildNumber num : key.getPath()) detKey.addPath(num.i()); if (key.equals(externalKey)) { detKey.setIssuedSubkeys(issuedExternalKeys); detKey.setLookaheadSize(lookaheadSize); } else if (key.equals(internalKey)) { detKey.setIssuedSubkeys(issuedInternalKeys); detKey.setLookaheadSize(lookaheadSize); } if (entries.isEmpty() && isFollowing()) { detKey.setIsFollowing(true); } entries.add(proto.build()); } return entries; } finally { lock.unlock(); } }
Source:
public static void createQueue(String queueName, String owner) throws RegistryClientException { if(log.isDebugEnabled()){ log.debug("Queue name going to put to the registry is: " + queueName); } if (!NameValidationUtils.isValidQueueName(queueName)) { throw new RegistryClientException("Queue name/subscription ID: " + queueName + " cannot contain any of following symbols ~!@#;%^*()+={}|<>\"', and space. " + "\" / \" can only use as the tenant separator\n"); } try { RegistryService registryService = CommonsDataHolder.getInstance().getRegistryService(); UserRegistry registry = registryService.getGovernanceSystemRegistry( PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() <= 0 ? MultitenantConstants.SUPER_TENANT_ID : PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() ); Collection queue; String queueID = CommonsUtil.getQueueID(queueName); if (!registry.resourceExists(queueID)) { queue = registry.newCollection(); queue.setProperty(OWNER, owner); queue.setProperty(NAME, queueName); queue.setProperty(CREATED_TIME, ConverterUtil.convertToString( Calendar.getInstance())); queue.setProperty(UPDATED_TIME, ConverterUtil.convertToString( Calendar.getInstance())); queue.setProperty(CREATED_FROM, CREATED_FROM_AMQP); queue.setProperty(USER_COUNT, "1"); } else { queue = (Collection) registry.get(queueID); queue.setProperty(UPDATED_TIME, ConverterUtil.convertToString( Calendar.getInstance())); String userCount = queue.getProperty(USER_COUNT); if (null != userCount) { int count = Integer.parseInt(userCount); queue.setProperty(USER_COUNT, Integer.toString(++count)); } } registry.put(queueID, queue); } catch (RegistryException e) { throw new RegistryClientException(e); } }

Target:
public static void createQueue(String queueName, String owner) throws RegistryClientException { if (log.isDebugEnabled()) { log.debug("Saving queue name \"" + queueName + "\" in Registry"); } try { RegistryService registryService = CommonsDataHolder.getInstance().getRegistryService(); UserRegistry registry = registryService.getGovernanceSystemRegistry( PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() <= 0 ? MultitenantConstants.SUPER_TENANT_ID : PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() ); Collection queue; String queueID = CommonsUtil.getQueueID(queueName); if (!registry.resourceExists(queueID)) { queue = registry.newCollection(); queue.setProperty(OWNER, owner); queue.setProperty(NAME, queueName); queue.setProperty(CREATED_TIME, ConverterUtil.convertToString( Calendar.getInstance())); queue.setProperty(UPDATED_TIME, ConverterUtil.convertToString( Calendar.getInstance())); queue.setProperty(CREATED_FROM, CREATED_FROM_AMQP); queue.setProperty(USER_COUNT, "1"); } else { queue = (Collection) registry.get(queueID); queue.setProperty(UPDATED_TIME, ConverterUtil.convertToString( Calendar.getInstance())); String userCount = queue.getProperty(USER_COUNT); if (null != userCount) { int count = Integer.parseInt(userCount); queue.setProperty(USER_COUNT, Integer.toString(++count)); } } registry.put(queueID, queue); } catch (RegistryException e) { throw new RegistryClientException(e); } }
Source:
public DiscoveredResourceDetails discoverResource(Configuration pluginConfig, ResourceDiscoveryContext context) throws InvalidPluginConfigurationException { DiscoveredResourceDetails discoveredResource = super.discoverResource(pluginConfig, context); discoverAdditionalJavaOpts(discoveredResource); return discoveredResource; }

Target:
public DiscoveredResourceDetails discoverResource(Configuration pluginConfig, ResourceDiscoveryContext context) throws InvalidPluginConfigurationException { DiscoveredResourceDetails discoveredResource = super.discoverResource(pluginConfig, context); discoverAdditionalJavaOpts(discoveredResource, context); return discoveredResource; }
Source:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = WidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); View answerView = binding.getRoot(); if (prompt.isReadOnly()) { binding.widgetButton.setVisibility(GONE); } else { binding.widgetButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.widgetButton.setText(getContext().getString(R.string.select_time)); binding.widgetButton.setOnClickListener(v -> onButtonClick()); } binding.widgetAnswerText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); if (getFormEntryPrompt().getAnswerValue() == null) { clearAnswer(); } else { Date date = (Date) getFormEntryPrompt().getAnswerValue().getValue(); DateTime dateTime = new DateTime(date); updateTime(dateTime); } return answerView; }

Target:
protected View onCreateAnswerView(Context context, FormEntryPrompt prompt, int answerFontSize) { binding = TimeWidgetAnswerBinding.inflate(((Activity) context).getLayoutInflater()); if (prompt.isReadOnly()) { binding.timeButton.setVisibility(GONE); } else { binding.timeButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); binding.timeButton.setOnClickListener(v -> { DateTimeWidgetUtils.setWidgetWaitingForData(prompt.getIndex()); widgetUtils.showTimePickerDialog(context, selectedTime); }); } binding.timeAnswerText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontSize); if (prompt.getAnswerValue() == null) { selectedTime = DateTimeUtils.getCurrentDateTime(); } else { DateTime dateTime = new DateTime(getFormEntryPrompt().getAnswerValue().getValue()); selectedTime = DateTimeUtils.getSelectedTime(dateTime.toLocalDateTime(), LocalDateTime.now()); binding.timeAnswerText.setText(DateTimeUtils.getTimeData(dateTime).getDisplayText()); } return binding.getRoot(); }