auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void errorWhenItemWithTextNotMatchedButShouldBe() { String expectedText = "Luis"; assertThatThrownBy(() -> $$("#user-table tbody tr td.firstname").shouldBe(itemWithText(expectedText))) .isInstanceOf(TextsMismatch.class) .hasMessageContaining( String.format(String.format("Texts mismatch" + "%nActual: %s" + "%nExpected: %s", Arrays.asList("Bob", "John"), Collections.singletonList(expectedText)))); }

Target:
void errorWhenItemWithTextNotMatchedButShouldBe() { String expectedText = "Luis"; assertThatThrownBy(() -> $$("#user-table tbody tr td.firstname").shouldHave(itemWithText(expectedText))) .isInstanceOf(ElementWithTextNotFound.class) .hasMessageContaining( String.format(String.format("Element with text not found" + "%nActual: %s" + "%nExpected: %s", Arrays.asList("Bob", "John"), Collections.singletonList(expectedText)))); }
Source:
CompletableFuture<Void> failedFuture(Throwable ex) { Preconditions.checkNotNull(ex); CompletableFuture<Void> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(ex); return failedFuture; }

Target:
private static CompletableFuture<Void> failedFuture(Throwable ex) { Preconditions.checkNotNull(ex); CompletableFuture<Void> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(ex); return failedFuture; }
Source:
public void getVirtualAttributesByHolders() throws Exception { System.out.println(CLASS_NAME + "getVirtualAttributesByHolders"); AttributeDefinition memberVirtAttr = setUpVirtualMemberAttribute(); AttributeDefinition memberResourceVirtAttr = setUpVirtualMemberResourceAttribute(); setUpGroupAttribute(); setUpMemberGroupAttributeDefinition(); List<Attribute> attrs = cacheManager.getVirtualAttributes(Holder.HolderType.MEMBER, Holder.HolderType.RESOURCE); assertTrue("result should contain virtual member-resource attribute definition", attrs.contains(new Attribute(memberResourceVirtAttr))); assertTrue("result should not contain virtual member attribute definition", !attrs.contains(new Attribute(memberVirtAttr))); assertTrue("it should return only 1 attribute", attrs.size() == 1); }

Target:
public void getVirtualAttributesByHolders() throws Exception { System.out.println(CLASS_NAME + "getVirtualAttributesByHolders"); AttributeDefinition memberVirtAttr = setUpVirtualMemberAttribute(); AttributeDefinition memberResourceVirtAttr = setUpVirtualMemberResourceAttribute(); setUpGroupAttribute(); setUpMemberGroupAttributeDefinition(); List<Attribute> attrs = cacheManager.getVirtualAttributes(Holder.HolderType.MEMBER, Holder.HolderType.RESOURCE); assertTrue("result should contain virtual member-resource attribute definition", attrs.contains(memberResourceVirtAttr)); assertTrue("result should not contain virtual member attribute definition", !attrs.contains(memberVirtAttr)); assertTrue("it should return only 1 attribute", attrs.size() == 1); }
Source:
public Page getOutput() { if (!spillInProgress.isDone()) { return null; } checkSuccess(spillInProgress, "spilling failed"); if (probe == null && pageBuilder.isEmpty() && !finishing) { return null; } if (!tryFetchLookupSourceProvider()) { return null; } if (probe == null && finishing && !unspilling) { verify(partitionedConsumption == null, "partitioned consumption already started"); partitionedConsumption = lookupSourceFactory.finishProbeOperator(lookupJoinsCount); unspilling = true; } if (probe == null && unspilling && !finished) { tryUnspillNext(); } if (probe != null) { processProbe(); } if (outputPage != null) { checkState(pageBuilder.isEmpty()); Page output = outputPage; outputPage = null; return output; } return null; }

Target:
public Page getOutput() { if (!spillInProgress.isDone()) { return null; } checkSuccess(spillInProgress, "spilling failed"); if (probe == null && pageBuilder.isEmpty() && !finishing) { return null; } if (!tryFetchLookupSourceProvider()) { return null; } if (probe == null && finishing && !unspilling) { verify(partitionedConsumption == null, "partitioned consumption already started"); partitionedConsumption = lookupSourceFactory.finishProbeOperator(lookupJoinsCount); unspilling = true; } if (probe == null && unspilling && !finished) { tryUnspillNext(); } if (probe != null) { processProbe(); } if (outputPage != null) { verify(pageBuilder.isEmpty()); Page output = outputPage; outputPage = null; return output; } if (!pageBuilder.isEmpty() && probe == null && finished && !useDictionaryProcessing) { Page page = pageBuilder.build(null); pageBuilder.reset(); return page; } return null; }
Source:
public void deserialize(byte[] message, Collector<RowData> out) throws IOException { RowData row = jsonDeserializer.deserialize(message); String type = row.getString(2).toString(); if (OP_INSERT.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.INSERT); out.collect(insert); } } else if (OP_UPDATE.equals(type)) { ArrayData data = row.getArray(0); ArrayData old = row.getArray(1); for (int i = 0; i < data.size(); i++) { GenericRowData after = (GenericRowData) data.getRow(i, fieldCount); GenericRowData before = (GenericRowData) old.getRow(i, fieldCount); for (int f = 0; f < fieldCount; f++) { if (before.isNullAt(f)) { before.setField(f, after.getField(f)); } } before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } } else if (OP_DELETE.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.DELETE); out.collect(insert); } } else { if (!ignoreParseErrors) { throw new IOException(format("Failed to deserialize Canal JSON '%s'.", new String(message))); } } }

Target:
public void deserialize(byte[] message, Collector<RowData> out) throws IOException { try { RowData row = jsonDeserializer.deserialize(message); String type = row.getString(2).toString(); if (OP_INSERT.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.INSERT); out.collect(insert); } } else if (OP_UPDATE.equals(type)) { ArrayData data = row.getArray(0); ArrayData old = row.getArray(1); for (int i = 0; i < data.size(); i++) { GenericRowData after = (GenericRowData) data.getRow(i, fieldCount); GenericRowData before = (GenericRowData) old.getRow(i, fieldCount); for (int f = 0; f < fieldCount; f++) { if (before.isNullAt(f)) { before.setField(f, after.getField(f)); } } before.setRowKind(RowKind.UPDATE_BEFORE); after.setRowKind(RowKind.UPDATE_AFTER); out.collect(before); out.collect(after); } } else if (OP_DELETE.equals(type)) { ArrayData data = row.getArray(0); for (int i = 0; i < data.size(); i++) { RowData insert = data.getRow(i, fieldCount); insert.setRowKind(RowKind.DELETE); out.collect(insert); } } else { if (!ignoreParseErrors) { throw new IOException(format( "Unknown \"type\" value \"%s\". The Canal JSON message is '%s'", type, new String(message))); } } } catch (Throwable t) { if (!ignoreParseErrors) { throw new IOException(format( "Corrupt Canal JSON message '%s'.", new String(message)), t); } } }
Source:
public void addQueryDateRange(final String name, LocalDate lowerBound, LocalDate upperBound) { if (lowerBound != null && upperBound != null) { int comparison = lowerBound.compareTo(upperBound); if (comparison > 0) { LocalDate temp = lowerBound; lowerBound = upperBound; upperBound = temp; } } if (lowerBound != null) { String value = lowerBound.toString(); addQueryParam(name + ">", value); } if (upperBound != null) { String value = upperBound.toString(); addQueryParam(name + "<", value); } }

Target:
public void addQueryDateRange(final String name, LocalDate lowerBound, LocalDate upperBound) { if (lowerBound != null) { String value = lowerBound.toString(); addQueryParam(name + ">", value); } if (upperBound != null) { String value = upperBound.toString(); addQueryParam(name + "<", value); } }
Source:
private void setContentsInternal(@Nullable InputStream input) throws IOException { VirtualFile virtualFile = getVirtualFile(); if (!existsInternal(virtualFile)) { throw new FileNotFoundException( "Could not set contents of " + this + " as it does not exist or is not valid."); } OutputStream out = virtualFile.getOutputStream(this); InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input; byte[] buffer = new byte[BUFFER_SIZE]; int read; try { while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } }

Target:
private void setContentsInternal(@Nullable InputStream input) throws IOException { VirtualFile virtualFile = getVirtualFile(); if (!existsInternal(virtualFile)) { throw new FileNotFoundException( "Could not set contents of " + this + " as it does not exist or is not valid."); } try (InputStream in = input == null ? new ByteArrayInputStream(new byte[0]) : input; OutputStream out = virtualFile.getOutputStream(this)) { IOUtils.copy(in, out); } }
Source:
private void serverRemovedSegment(DruidServerMetadata server, DataSegment segment) { String segmentId = segment.getIdentifier(); final Set<DruidServerMetadata> servers; synchronized (lock) { log.debug("Removing segment[%s] from server[%s].", segmentId, server); servers = selectors.get(segmentId); if (servers == null) { log.warn("Told to remove non-existant segment[%s]", segmentId); return; } servers.remove(server); if (servers.isEmpty()) { VersionedIntervalTimeline<String, SegmentLoadInfo> timeline = timelines.get(segment.getDataSource()); selectors.remove(segmentId); final PartitionChunk<SegmentLoadInfo> removedPartition = timeline.remove( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk( new SegmentLoadInfo( segment, Sets .<DruidServerMetadata>newHashSet() ) ) ); if (removedPartition == null) { log.warn( "Asked to remove timeline entry[interval: %s, version: %s] that doesn't exist", segment.getInterval(), segment.getVersion() ); } } } }

Target:
private void serverRemovedSegment(DruidServerMetadata server, DataSegment segment) { String segmentId = segment.getIdentifier(); synchronized (lock) { log.debug("Removing segment[%s] from server[%s].", segmentId, server); final SegmentLoadInfo segmentLoadInfo = segmentLoadInfos.get(segmentId); if (segmentLoadInfo == null) { log.warn("Told to remove non-existant segment[%s]", segmentId); return; } segmentLoadInfo.removeServer(server); if (segmentLoadInfo.isEmpty()) { VersionedIntervalTimeline<String, SegmentLoadInfo> timeline = timelines.get(segment.getDataSource()); segmentLoadInfos.remove(segmentId); final PartitionChunk<SegmentLoadInfo> removedPartition = timeline.remove( segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk( new SegmentLoadInfo( segment ) ) ); if (removedPartition == null) { log.warn( "Asked to remove timeline entry[interval: %s, version: %s] that doesn't exist", segment.getInterval(), segment.getVersion() ); } } } }
Source:
protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) { if ((e instanceof EntityNotFoundException) && (notFoundAs404)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } else if ((e instanceof BackendFailureException) && (!StringUtils.isEmpty(e.getMessage()))) { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage(), null); throw new WebFaultException(null, e.getMessage(), Response.Status.BAD_REQUEST); } else if (e instanceof UrlParamException){ UrlParamException e2 = (UrlParamException) e; throw e2; } else { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e), e); throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR); } }

Target:
protected <T> T handleError(Class<T> clz, Exception e, boolean notFoundAs404) { if ((e instanceof EntityNotFoundException) && (notFoundAs404)) { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build()); } else if ((e instanceof BackendFailureException) && (!StringUtils.isEmpty(e.getMessage()))) { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), e.getMessage(), null); throw new WebFaultException(null, e.getMessage(), Response.Status.BAD_REQUEST); } else if (e instanceof WebFaultException) { WebFaultException e2 = (WebFaultException) e; LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e2), e2); throw e2; } else { LOG.errorFormat(localize(Messages.BACKEND_FAILED_TEMPLATE), detail(e), e); throw new WebFaultException(e, detail(e), Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
public ChannelPipelineFactory newChannelPipelineFactory(final int maxFrameSize, NettyClientConfig clientConfig) { return new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline cp = Channels.pipeline(); TimeoutHandler.addToPipeline(cp); cp.addLast("frameEncoder", new LengthFieldPrepender(LENGTH_FIELD_LENGTH)); cp.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( maxFrameSize, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); if (clientConfig.sslClientConfiguration() != null) { cp.addFirst("ssl", clientConfig.sslClientConfiguration().initializeHandler()); } return cp; } }; }

Target:
public ChannelPipelineFactory newChannelPipelineFactory(final int maxFrameSize, NettyClientConfig clientConfig) { return new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline cp = Channels.pipeline(); TimeoutHandler.addToPipeline(cp); cp.addLast("frameEncoder", new LengthFieldPrepender(LENGTH_FIELD_LENGTH)); cp.addLast( "frameDecoder", new LengthFieldBasedFrameDecoder( maxFrameSize, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP)); if (clientConfig.sslClientConfiguration() != null) { cp.addFirst("ssl", clientConfig.sslClientConfiguration().createHandler(address)); } return cp; } }; }
Source:
String encodeUrlForRedirect(String urlStr) throws MalformedURLException { try { URL url = new URL(urlStr); UriBuilder builder = UriBuilder.fromUri(url.toURI()); builder.host(url.getHost()); builder.port(url.getPort()); builder.replacePath(url.getPath()); URI uri = builder.build(); LOGGER.info("encodeUrlForRedirect - from [{}]", uri, urlStr); return uri.toString(); } catch (URISyntaxException exc) { throw new MalformedURLException(exc.getMessage()); } }

Target:
String encodeUrlForRedirect(String urlStr) throws MalformedURLException { try { URL url = new URL(urlStr); UriBuilder builder = UriBuilder.fromUri(url.toURI()); builder.host(url.getHost()); builder.port(url.getPort()); builder.replacePath(url.getPath()); String encodedUrl = builder.build().toString(); LOGGER.info("encodeUrlForRedirect - from [{}]", encodedUrl, urlStr); return encodedUrl; } catch (URISyntaxException exc) { throw new MalformedURLException(exc.getMessage()); } }
Source:
public void writeTo( Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { new PrintWriter(new OutputStreamWriter(entityStream)).print(GSON.toJson(o)); }

Target:
public void writeTo( Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException { GSON.toJson(o, new OutputStreamWriter(entityStream)); }
Source:
protected String getFontName(String fontNameExpression, EAttribute eAttribute, FontData defaultFontData) { String fontName = defaultFontData.getName(); Eval eval = new Eval(interpreter, variableManager); if (fontNameExpression != null && !fontNameExpression.isEmpty()) { String fontNameValue = eval.get(eAttribute, fontNameExpression, String.class); if (fontNameValue != null) { fontName = fontNameValue; } } return fontName; }

Target:
private String getFontName(String fontNameExpression, EAttribute eAttribute, FontData defaultFontData) { String fontName = defaultFontData.getName(); Eval eval = new Eval(interpreter, variableManager); if (fontNameExpression != null && !fontNameExpression.isEmpty()) { String fontNameValue = eval.get(eAttribute, fontNameExpression, String.class); if (fontNameValue != null) { fontName = fontNameValue; } } return fontName; }
Source:
public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); if (parentAction != null) { ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); } } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } }

Target:
public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } }
Source:
public boolean canCreateChildProject() { return user.getCapabilityByProject(state.getProject().getNameKey()) .canCreateProject(); }

Target:
public boolean canCreateChildProject() { return user.getCapabilities().canAdministrateServer() || user.getCapabilityByProject(state.getProject().getNameKey()) .canCreateProject(); }
Source:
private void addInterfacesFromTemplate() { String macRegex = "^(\\p{XDigit}{2}:){5}\\p{XDigit}{2}$"; VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); for (VmNetworkInterface iface : getVm().getInterfaces()) { if (iface.getId() == null) { iface.setId(Guid.NewGuid()); } if (StringHelper.isNullOrEmpty(iface.getMacAddress())) { iface.setMacAddress(MacPoolManager.getInstance().allocateNewMac()); } if (!Regex.IsMatch(iface.getMacAddress(), macRegex)) { AuditLogableBase logable = new AuditLogableBase(); logable.AddCustomValue("MacAddress", iface.getMacAddress()); logable.AddCustomValue("IfaceName", iface.getName()); AuditLogDirector.log(logable, AuditLogType.IMPORTEXPORT_IMPORT_INTERFACES_WITH_INVALID_MAC_ADDRESS); } iface.setVmTemplateId(null); iface.setVmId(getVm().getStaticData().getId()); iface.setVmName(getVm().getvm_name()); if (getParameters().isImportAsNewEntity()) { macAdded = true; } else { macAdded = vmInterfaceManager.add(iface, getCompensationContext()); } } }

Target:
private void addInterfacesFromTemplate() { VmInterfaceManager vmInterfaceManager = new VmInterfaceManager(); for (VmNetworkInterface iface : getVm().getInterfaces()) { if (iface.getId() == null) { iface.setId(Guid.NewGuid()); } validateImportMacAddress(iface); iface.setVmTemplateId(null); iface.setVmId(getVm().getStaticData().getId()); iface.setVmName(getVm().getvm_name()); if (getParameters().isImportAsNewEntity()) { macAdded = true; } else { macAdded = vmInterfaceManager.add(iface, getCompensationContext()); } } }
Source:
private void scheduleRefreshAccessToken(final AuthenticationServer authServer, long expireDateInMs) { long refreshAfter = expireDateInMs - System.currentTimeMillis() - REFRESH_MARGIN_DELAY; if (refreshAfter < 0) { RealmLog.debug("Expires time already reached for the access token, refresh soon"); refreshAfter = REFRESH_MARGIN_DELAY; } RealmLog.debug("Scheduling an access_token refresh in " + (refreshAfter) + " milliseconds"); if (refreshTokenTask != null) { refreshTokenTask.cancel(); } ScheduledFuture<?> task = REFRESH_TOKENS_EXECUTOR.schedule(new Runnable() { @Override public void run() { if (!isClosed && !Thread.currentThread().isInterrupted()) { refreshAccessToken(authServer); } } }, refreshAfter, TimeUnit.MILLISECONDS); refreshTokenTask = new RealmAsyncTaskImpl(task, REFRESH_TOKENS_EXECUTOR); }

Target:
private void scheduleRefreshAccessToken(final AuthenticationServer authServer, long expireDateInMs) { long refreshAfter = expireDateInMs - System.currentTimeMillis() - REFRESH_MARGIN_DELAY; if (refreshAfter < 0) { RealmLog.debug("Expires time already reached for the access token, refresh as soon as possible"); refreshAfter = REFRESH_MARGIN_DELAY; } RealmLog.debug("Scheduling an access_token refresh in " + (refreshAfter) + " milliseconds"); if (refreshTokenTask != null) { refreshTokenTask.cancel(); } ScheduledFuture<?> task = REFRESH_TOKENS_EXECUTOR.schedule(new Runnable() { @Override public void run() { if (!isClosed && !Thread.currentThread().isInterrupted()) { refreshAccessToken(authServer); } } }, refreshAfter, TimeUnit.MILLISECONDS); refreshTokenTask = new RealmAsyncTaskImpl(task, REFRESH_TOKENS_EXECUTOR); }
Source:
public void stopJoiningNodes() throws Exception { deployer.undeploy(getJoiningNodeName()); deployer.undeploy(COORDINATOR_NODE); try { controller.stop(getJoiningNodeName()); controller.stop(COORDINATOR_NODE); } catch(Exception e) { LOG.warn("Server stop failed with %s", e.getCause()); controller.kill(COORDINATOR_NODE); controller.kill(getJoiningNodeName()); } assertFalse(controller.isStarted(getJoiningNodeName())); assertFalse(controller.isStarted(COORDINATOR_NODE)); }

Target:
public void stopJoiningNodes() throws Exception { deployer.undeploy(getJoiningNodeName()); deployer.undeploy(COORDINATOR_NODE); try { controller.stop(getJoiningNodeName()); } catch(Exception e) { LOG.warn("Joining node stop failed with %s", e.getCause()); controller.kill(getJoiningNodeName()); } try { controller.stop(COORDINATOR_NODE); } catch(Exception e) { LOG.warn("Coordinator node stop failed with %s", e.getCause()); controller.kill(COORDINATOR_NODE); } assertFalse(controller.isStarted(getJoiningNodeName())); assertFalse(controller.isStarted(COORDINATOR_NODE)); }
Source:
public ChemComp getChemComp(String recordName) { recordName = recordName.toUpperCase().trim(); boolean haveFile = true; if ( recordName.equals("?")){ return null; } if ( ! fileExists(recordName)) { checkDoFirstInstall(); } if ( ! fileExists(recordName)) { haveFile = downloadChemCompRecord(recordName); } if (haveFile) { String filename = getLocalFileName(recordName); InputStream inStream = null; try { InputStreamProvider isp = new InputStreamProvider(); inStream = isp.getInputStream(filename); MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(inStream))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(recordName); if(chemComp != null) { return chemComp; } } catch (IOException e) { logger.error("Could not parse chemical component file {}. Error: {}. " + "There will be no chemical component info available for {}", filename, e.getMessage(), recordName); } finally{ if(inStream!=null){ try { inStream.close(); } catch (IOException e) { logger.error("Could not close chemical component file {}. A resource leak could occur!!", filename); } } } } if( fallback == null) { fallback = new ReducedChemCompProvider(); } return fallback.getChemComp(recordName); }

Target:
public ChemComp getChemComp(String recordName) { recordName = recordName.toUpperCase().trim(); boolean haveFile = true; if ( recordName.equals("?")){ return null; } if ( ! fileExists(recordName)) { checkDoFirstInstall(); } if ( ! fileExists(recordName)) { haveFile = downloadChemCompRecord(recordName); } if (haveFile) { String filename = getLocalFileName(recordName); InputStream inStream = null; try { InputStreamProvider isp = new InputStreamProvider(); inStream = isp.getInputStream(filename); MMcifParser parser = new SimpleMMcifParser(); ChemCompConsumer consumer = new ChemCompConsumer(); parser.addMMcifConsumer(consumer); parser.parse(new BufferedReader(new InputStreamReader(inStream))); ChemicalComponentDictionary dict = consumer.getDictionary(); ChemComp chemComp = dict.getChemComp(recordName); if(chemComp != null) { return chemComp; } } catch (IOException e) { logger.error("Could not parse chemical component file {}. Error: {}. " + "There will be no chemical component info available for {}", filename, e.getMessage(), recordName); } finally{ if(inStream!=null){ try { inStream.close(); } catch (IOException e) { logger.error("Could not close chemical component file {}. A resource leak could occur!!", filename); } } } } if( fallback == null) { fallback = new ReducedChemCompProvider(); } logger.warn("Falling back to ReducedChemCompProvider for {}. This could indicate a network error.", recordName); return fallback.getChemComp(recordName); }
Source:
Properties loadCostProperties(Path cachePath, String machineType) { Properties prop = new Properties(); try { InputStream inp = new FileInputStream(cachePath.toString()); prop.load(inp); return prop; } catch (FileNotFoundException fnf) { LOG.error("cost properties does not exist, using default values"); return null; } catch (IOException e) { LOG.error("error loading properties, using default values"); return null; } }

Target:
Properties loadCostProperties(Path cachePath, String machineType) { Properties prop = new Properties(); InputStream inp = null; try { inp = new FileInputStream(cachePath.toString()); prop.load(inp); return prop; } catch (FileNotFoundException fnf) { LOG.error("cost properties does not exist, using default values"); return null; } catch (IOException e) { LOG.error("error loading properties, using default values"); return null; } finally { if (inp != null) { try { inp.close(); } catch (IOException ignore) { } } } }
Source:
public final void readURL(URLConnection url) throws IOException { DataInputStream in = new DataInputStream(url.getInputStream()); printHeader(url); try { while (true) { System.out.println((char) in.readUnsignedByte()); } } catch (EOFException e) { LOGGER.error("EOF Exception while reading url : ",e); } catch (IOException e) { LOGGER.error("IO Exception while reading url : ",e); } }

Target:
public final void readURL(URLConnection url) throws IOException { DataInputStream in = new DataInputStream(url.getInputStream()); printHeader(url); try { while (true) { System.out.println((char) in.readUnsignedByte()); } } catch (EOFException e) { LOGGER.error("EOF Exception while reading url, ", url.toString(), e); } catch (IOException e) { LOGGER.error("IO Exception while reading url, [{}]", url.toString(), e); } }
Source:
public URL registerBlob (File blob) { String key = blob.getName(); blobs.put(key, blob); URL url = null; try { url = new URL(protocol, host, port, path + "/" + key); } catch (Exception exception) { log.error("Can't generate URL for blob \"" + blob.getAbsolutePath() + "\".", exception); url = null; } if (url != null) { log.info("Registered URL \"" + url + "\" for blob \"" + blob.getAbsolutePath() + "\"."); } return url; }

Target:
public URL registerBlob (File blob) { String key = blob.getName(); blobs.put(key, blob); URL url = null; try { url = new URL(protocol, host, port, path + "/" + key); } catch (Exception exception) { log.error("Can't generate URL for blob \"" + blob.getAbsolutePath() + "\".", exception); url = null; } return url; }
Source:
private void addHeaders(final HttpRequest httpRequest) throws IOException, SignatureException { final String date = DateFormatter.dateToRfc882(); httpRequest.addHeader(HOST, NetUtils.buildHostField(NetworkClientImpl.this.connectionDetails)); httpRequest.addHeader(DATE, date); httpRequest.addHeader(CONTENT_TYPE, this.ds3Request.getContentType().toString()); for(final Map.Entry<String, String> header: this.ds3Request.getHeaders().entrySet()) { httpRequest.addHeader(header.getKey(), header.getValue()); } if (this.hash != "") { httpRequest.addHeader("Content-MD5", this.hash); } httpRequest.addHeader(AUTHORIZATION, this.getSignature(new SignatureDetails( this.ds3Request.getVerb(), this.hash, this.ds3Request.getContentType().toString(), date, "", this.ds3Request.getPath(), NetworkClientImpl.this.connectionDetails.getCredentials() ))); }

Target:
private void addHeaders(final HttpRequest httpRequest) throws IOException, SignatureException { final String date = DateFormatter.dateToRfc882(); httpRequest.addHeader(HOST, NetUtils.buildHostField(NetworkClientImpl.this.connectionDetails)); httpRequest.addHeader(DATE, date); httpRequest.addHeader(CONTENT_TYPE, this.ds3Request.getContentType().toString()); for(final Map.Entry<String, String> header: this.ds3Request.getHeaders().entrySet()) { httpRequest.addHeader(header.getKey(), header.getValue()); } if (!this.hash.isEmpty()) { httpRequest.addHeader(CONTENT_MD5, this.hash); } httpRequest.addHeader(AUTHORIZATION, this.getSignature(new SignatureDetails( this.ds3Request.getVerb(), this.hash, this.ds3Request.getContentType().toString(), date, "", this.ds3Request.getPath(), NetworkClientImpl.this.connectionDetails.getCredentials() ))); }
Source:
public void testBlobExpired() throws Exception { initialize(false, "9"); ServerErrorCode[] serverErrorCodes = {ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Not_Found, ServerErrorCode.Blob_Expired}; writeBlobRecordToServers(serverErrorCodes); blobRecordVerification(serverErrorCodes); future = router.deleteBlob(blobIdString, new UserCallback()); try { future.get(); fail(); } catch (Exception e) { assertEquals(RouterErrorCode.BlobExpired, ((RouterException) exception).getErrorCode()); } }

Target:
public void testBlobExpired() throws Exception { ServerErrorCode[] serverErrorCodes = new ServerErrorCode[9]; Arrays.fill(serverErrorCodes, ServerErrorCode.Blob_Not_Found); serverErrorCodes[5] = ServerErrorCode.Blob_Expired; presetServerErrorCode(serverErrorCodes); future = router.deleteBlob(blobIdString, new ClientCallback()); try { future.get(); fail("Deletion should be unsuccessful. Error is expected."); } catch (Exception e) { assertEquals("RouterErrorCode should be BlobExpired", RouterErrorCode.BlobExpired, ((RouterException) e.getCause()).getErrorCode()); } }
Source:
public <T> T api(Class<T> serviceInterface) { final ServiceCall serviceCall = this; final Map<Method, MethodInfo> genericReturnTypes = Reflect.methodsInfo(serviceInterface); return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {serviceInterface}, (proxy, method, params) -> { final MethodInfo methodInfo = genericReturnTypes.get(method); final Class<?> returnType = methodInfo.parameterizedReturnType(); final boolean isServiceMessage = methodInfo.isRequestTypeServiceMessage(); Optional<Object> check = toStringOrEqualsOrHashCode(method.getName(), serviceInterface, params); if (check.isPresent()) { return check.get(); } switch (methodInfo.communicationMode()) { case FIRE_AND_FORGET: return serviceCall.oneWay(toServiceMessage(methodInfo, params)); case REQUEST_RESPONSE: return serviceCall .requestOne(toServiceMessage(methodInfo, params), returnType) .transform(monoRespFn.apply(isServiceMessage)); case REQUEST_STREAM: return serviceCall .requestMany(toServiceMessage(methodInfo, params), returnType) .transform(fluxRespFn.apply(isServiceMessage)); case REQUEST_CHANNEL: return serviceCall .requestBidirectional( Flux.from((Publisher) params[0]) .map(data -> toServiceMessage(methodInfo, data)), returnType) .transform(fluxRespFn.apply(isServiceMessage)); default: throw new IllegalArgumentException( "Communication mode is not supported: " + method); } }); }

Target:
public <T> T api(Class<T> serviceInterface) { final ServiceCall serviceCall = this; final Map<Method, MethodInfo> genericReturnTypes = Reflect.methodsInfo(serviceInterface); return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {serviceInterface}, (proxy, method, params) -> { final MethodInfo methodInfo = genericReturnTypes.get(method); final Class<?> returnType = methodInfo.parameterizedReturnType(); final boolean isServiceMessage = methodInfo.isRequestTypeServiceMessage(); Optional<Object> check = toStringOrEqualsOrHashCode(method.getName(), serviceInterface, params); if (check.isPresent()) { return check.get(); } switch (methodInfo.communicationMode()) { case FIRE_AND_FORGET: return serviceCall.oneWay(toServiceMessage(methodInfo, params)); case REQUEST_RESPONSE: return serviceCall .requestOne(toServiceMessage(methodInfo, params), returnType) .transform(asMono(isServiceMessage)); case REQUEST_STREAM: return serviceCall .requestMany(toServiceMessage(methodInfo, params), returnType) .transform(asFlux(isServiceMessage)); case REQUEST_CHANNEL: return serviceCall .requestBidirectional( Flux.from((Publisher) params[0]) .map(data -> toServiceMessage(methodInfo, data)), returnType) .transform(asFlux(isServiceMessage)); default: throw new IllegalArgumentException( "Communication mode is not supported: " + method); } }); }
Source:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta incomingContainer : containers) { if (isInterestingContainer(incomingContainer)) { ITask task = (ITask) incomingContainer.getElement(); if (task != null) { if (isArtifactCandidate(task)) { setArtifactState(task, isArtifact(task)); } else { setArtifactState(task, false); } } } } }

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta incomingContainer : containers) { if (isInterestingContainer(incomingContainer)) { ITask task = (ITask) incomingContainer.getElement(); if (task != null) { setArtifactState(task, usesIssueTrackerWorkflow(task) && isArtifact(task)); } } } }
Source:
public static SslContext newServerContext( SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout, String keyStore) throws SSLException { try { return newServerContextInternal(provider, null, toX509Certificates(trustCertCollectionFile), trustManagerFactory, toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword), keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, ClientAuth.NONE, null, false, false, keyStore); } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the server-side SSL context", e); } }

Target:
static SslContext newServerContext( SslProvider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout, String keyStore) throws SSLException { try { return newServerContextInternal(provider, null, toX509Certificates(trustCertCollectionFile), trustManagerFactory, toX509Certificates(keyCertChainFile), toPrivateKey(keyFile, keyPassword), keyPassword, keyManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, ClientAuth.NONE, null, false, false, keyStore); } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the server-side SSL context", e); } }
Source:
protected TaskWrapper getNextTask() throws InterruptedException { while (runningThread != null) { TaskWrapper nextScheduledTask = scheduleQueue.peekFirst(); TaskWrapper nextExecuteTask = executeQueue.peek(); if (nextExecuteTask != null) { if (nextScheduledTask != null) { long scheduleDelay; long executeDelay; clockWrapper.stopForcingUpdate(); try { scheduleDelay = nextScheduledTask.getDelay(TimeUnit.MILLISECONDS); executeDelay = nextExecuteTask.getDelay(TimeUnit.MILLISECONDS); } finally { clockWrapper.resumeForcingUpdate(); } if (scheduleDelay < executeDelay) { synchronized (scheduleQueue.getModificationLock()) { if (scheduleQueue.remove(nextScheduledTask)) { nextScheduledTask.executing(); return nextScheduledTask; } } } else { synchronized (executeQueueRemoveLock) { if (executeQueue.remove(nextExecuteTask)) { nextExecuteTask.executing(); return nextExecuteTask; } } } } else { synchronized (executeQueueRemoveLock) { if (executeQueue.remove(nextExecuteTask)) { nextExecuteTask.executing(); return nextExecuteTask; } } } } else if (nextScheduledTask != null) { if (nextScheduledTask.getDelay(TimeUnit.MILLISECONDS) <= 0) { synchronized (scheduleQueue.getModificationLock()) { if (scheduleQueue.remove(nextScheduledTask)) { nextScheduledTask.executing(); return nextScheduledTask; } } } else { LockSupport.parkNanos(Clock.NANOS_IN_MILLISECOND * nextScheduledTask.getDelay(TimeUnit.MILLISECONDS)); } } else { LockSupport.park(); } if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } } return null; }

Target:
protected TaskWrapper getNextTask() throws InterruptedException { while (runningThread != null) { TaskWrapper nextScheduledTask = scheduleQueue.peekFirst(); TaskWrapper nextExecuteTask = executeQueue.peek(); if (nextExecuteTask != null) { if (nextScheduledTask != null) { long scheduleDelay; long executeDelay; clockWrapper.stopForcingUpdate(); try { scheduleDelay = nextScheduledTask.getDelay(TimeUnit.MILLISECONDS); executeDelay = nextExecuteTask.getDelay(TimeUnit.MILLISECONDS); } finally { clockWrapper.resumeForcingUpdate(); } if (scheduleDelay < executeDelay) { synchronized (scheduleQueue.getModificationLock()) { if (scheduleQueue.remove(nextScheduledTask)) { nextScheduledTask.executing(); return nextScheduledTask; } } } else { if (executeQueue.remove(nextExecuteTask)) { nextExecuteTask.executing(); return nextExecuteTask; } } } else { if (executeQueue.remove(nextExecuteTask)) { nextExecuteTask.executing(); return nextExecuteTask; } } } else if (nextScheduledTask != null) { if (nextScheduledTask.getDelay(TimeUnit.MILLISECONDS) <= 0) { synchronized (scheduleQueue.getModificationLock()) { if (scheduleQueue.remove(nextScheduledTask)) { nextScheduledTask.executing(); return nextScheduledTask; } } } else { LockSupport.parkNanos(Clock.NANOS_IN_MILLISECOND * nextScheduledTask.getDelay(TimeUnit.MILLISECONDS)); } } else { LockSupport.park(); } if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } } return null; }
Source:
public void entriesExpire() { SlidingWindowWeightedMeanGauge expiringGauge = new SlidingWindowWeightedMeanGauge(Duration.ZERO); expiringGauge.update(100.0, 50); expiringGauge.update(50.0, 4); assertThat(expiringGauge.getValue()).isCloseTo(0.0, withinPercentage(1)); }

Target:
public void entriesExpire() { SlidingWindowWeightedMeanGauge expiringGauge = new SlidingWindowWeightedMeanGauge(Duration.ZERO); expiringGauge.update(100.0, 50); expiringGauge.update(50.0, 4); assertThat(expiringGauge.getValue()).isCloseTo(0.0, withinPercentage(0.1)); }
Source:
public void processErrorWithChildContextAndHandledByParent() { Reference<EventContext> contextReference = new Reference<>(); InternalReactiveProcessor backPressureError = publisher -> from(publisher).map(in -> { throw propagateWrappingFatal(new FlowBackPressureMaxConcurrencyExceededException("flowName", MAX_CONCURRENCY_EXCEEDED)); }); Flux.from(MessageProcessors.applyWithChildContext(Mono.just(input), createChain(backPressureError), Optional.empty(), (exception, event) -> { contextReference .set(((MessagingException) exception).getEvent().getContext()); return null; })) .subscribe(); assertThat(contextReference.get(), notNullValue()); assertThat(contextReference.get(), is(not(input.getContext()))); BaseEventContext context = (BaseEventContext) contextReference.get(); assertThat(context.getParentContext().get(), is(input.getContext())); }

Target:
public void processErrorWithChildContextAndHandledByParent() { Reference<EventContext> contextReference = new Reference<>(); Reference<CoreEvent> eventReference = new Reference<>(); InternalReactiveProcessor backPressureError = publisher -> from(publisher).map(in -> { throw propagateWrappingFatal(new FlowBackPressureMaxConcurrencyExceededException("flowName", MAX_CONCURRENCY_EXCEEDED)); }); Flux.from(applyWithChildContext(just(input), createChain(backPressureError), Optional.empty(), (exception, event) -> { contextReference .set(((MessagingException) exception).getEvent().getContext()); eventReference .set(event); return event; })) .subscribe(); assertThat(contextReference.get(), notNullValue()); assertThat(contextReference.get(), is(not(input.getContext()))); BaseEventContext context = (BaseEventContext) contextReference.get(); assertThat(context.getParentContext().get(), is(input.getContext())); assertThat(context, is(eventReference.get().getContext())); }
Source:
public List<String> getRequestIds() { List<String> request_ids = new ArrayList<String>(); try { Statement st = db.getConnection().createStatement(); ResultSet rs = st.executeQuery(ALL_REQUESTS_QUERY); while (rs.next()) { String id = rs.getString(1); request_ids.add(id); } } catch (SQLException ex) { LOGGER.error("failed to retrieve processes", ex); } return request_ids; }

Target:
private List<String> getRequestIds() { Statement st = null; ResultSet rs = null; List<String> request_ids = new ArrayList<String>(); try { st = db.getConnection().createStatement(); rs = st.executeQuery(ALL_REQUESTS_QUERY); while (rs.next()) { String id = rs.getString(1); request_ids.add(id); } } catch (SQLException ex) { LOGGER.error("failed to retrieve processes", ex); } finally { closeResultSet(rs); closeStatement(st); } return request_ids; }
Source:
public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "onStartCommand"); if (v1ToV2Migrator != null && !v1ToV2Migrator.isRunning()) { executor.execute(new Runnable() { @Override public void run() { Log.d(TAG, "Begin Migration"); v1ToV2Migrator.migrate(); } }); } return START_STICKY; }

Target:
public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Log.d(TAG, "onStartCommand"); executor.execute(new Runnable() { @Override public void run() { Migrator migrator = MigrationFactory.createVersionOneToVersionTwoMigrator( getApplicationContext(), getDatabasePath("downloads.db"), migrationCallback() ); Log.d(TAG, "Begin Migration: " + migrator.getClass()); migrator.migrate(); } }); return START_STICKY; }
Source:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = MarshallUtil.unmarshallArray(input, WriteCommand::array); }

Target:
public void readFrom(ObjectInput input) throws IOException, ClassNotFoundException { super.readFrom(input); onePhaseCommit = input.readBoolean(); retriedCommand = input.readBoolean(); modifications = MarshallUtil.unmarshallArray(input, WriteCommand[]::new); }
Source:
private void writeDoc(String file) throws IOException { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setDefaultScalarStyle(ScalarStyle.LITERAL); Yaml yaml = new Yaml(options); Writer writer; if (Strings.isNullOrEmpty(file)) { writer = new StringWriter(); } else { writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8); } try { Map<String, Map<String, Map<String, String>>> docs = docEntries.entrySet() .stream() .collect(Collectors.toMap( e -> e.getKey(), e -> e.getValue().entrySet() .stream() .collect(Collectors.toMap( e1 -> e1.getKey(), e1 -> e1.getValue().properties() )) )); yaml.dump(docs, writer); writer.flush(); if (writer instanceof StringWriter) { StringWriter sw = (StringWriter) writer; System.out.println(sw.toString()); } } finally { writer.close(); } }

Target:
private void writeDoc(String file) throws IOException { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(FlowStyle.BLOCK); options.setDefaultScalarStyle(ScalarStyle.LITERAL); Yaml yaml = new Yaml(options); Writer writer; if (Strings.isNullOrEmpty(file)) { writer = new OutputStreamWriter(System.out, UTF_8); } else { writer = new OutputStreamWriter(new FileOutputStream(file), UTF_8); } try { Map<String, Map<String, Map<String, String>>> docs = docEntries.entrySet() .stream() .collect(Collectors.toMap( e -> e.getKey(), e -> e.getValue().entrySet() .stream() .collect(Collectors.toMap( e1 -> e1.getKey(), e1 -> e1.getValue().properties() )) )); yaml.dump(docs, writer); writer.flush(); } finally { writer.close(); } }
Source:
public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); refresh(); }

Target:
public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); }
Source:
public boolean processResponse(Intent intent, ODKView currentView, FormInstance instance, File destination) { if(intent == null){ return false; } String result = intent.getStringExtra(INTENT_RESULT_VALUE); ((ODKView) currentView).setBinaryData(result); Bundle response = intent.getBundleExtra(INTENT_RESULT_BUNDLE); if(responses != null) { for (String key : responses.keySet()) { if (!response.containsKey(key)) { continue; } String responseValue = response.getString(key); if (key == null) { key = ""; } for (TreeReference ref : responses.get(key)) { EvaluationContext context = new EvaluationContext(form.getEvaluationContext(), ref); AbstractTreeElement node = context.resolveReference(ref); if (node == null) { continue; } int dataType = node.getDataType(); if (dataType == Constants.DATATYPE_BINARY) { if (responseValue == null || responseValue.equals("")) { form.setValue(null, ref); continue; } File src = new File(responseValue); if (!src.exists()) { Log.w(TAG, "ODK received a link to a file at " + src.toString() + " to be included in the form, but it was not present on the phone!"); form.setValue(null, ref); continue; } File newFile = new File(destination, src.getName()); FileUtils.copyFile(src, newFile); if (newFile.exists() && newFile.length() == src.length()) { form.setValue(new StringData(newFile.toString()), ref); continue; } else { Log.e(TAG, "ODK Failed to property write a file to " + newFile.toString()); form.setValue(null, ref); continue; } } IAnswerData val = Recalculate.wrapData(responseValue, dataType); form.setValue(val == null ? null : AnswerDataFactory.templateByDataType(dataType).cast(val.uncast()), ref); } } } return (result != null); }

Target:
public boolean processResponse(Intent intent, ODKView currentView, FormInstance instance, File destination) { if(intent == null){ return false; } String result = intent.getStringExtra(INTENT_RESULT_VALUE); ((ODKView) currentView).setBinaryData(result); Bundle response = intent.getBundleExtra(INTENT_RESULT_BUNDLE); if(responses != null) { for (String key : responses.keySet()) { if (!response.containsKey(key)) { continue; } String responseValue = response.getString(key); if (key == null) { key = ""; } for (TreeReference ref : responses.get(key)) { processResponseItem(ref, responseValue, destination); } } } return (result != null); }