auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public byte code(final byte refBase, final byte readBase) { if (Character.isLowerCase((char) refBase)) { log.warn(String.format("CRAM: Attempt to generate a substitution code for a lower case reference base '%c'", (char) refBase)); } return codeByBase[refBase][readBase]; }

Target:
public byte code(final byte refBase, final byte readBase) { if (refBase <= 0 || Character.isLowerCase((char) refBase)) { throw new IllegalArgumentException( String.format("CRAM: Attempt to generate a substitution code for invalid or lower case reference base '%c'", (char) refBase)); } if (readBase <= 0) { throw new IllegalArgumentException( String.format("CRAM: Attempt to generate a substitution code for an invalid read base value '%c'", (char) readBase)); } return codeByBase[refBase][readBase]; }
Source:
protected void onDestroy() { unitsFab.setOnClickListener(null); if (menu != null) { menu.clear(); } if (states != null) { states.clear(); } if (mapboxMap != null && mapboxMap.getStyle() != null) { mapboxMap.getStyle().removeImage(RED_PIN_IMAGE_ID); mapboxMap.getStyle().removeImage(BLUE_PIN_IMAGE_ID); mapboxMap.getStyle().removeLayer(MAX_TEMP_LAYER_ID); mapboxMap.getStyle().removeLayer(MIN_TEMP_LAYER_ID); mapboxMap.getStyle().removeSource(GEOJSON_SRC_ID); } mapView.onDestroy(); mapView = null; mapboxMap = null; unitsFab = null; menu = null; super.onDestroy(); }

Target:
protected void onDestroy() { unitsFab.setOnClickListener(null); if (menu != null) { menu.clear(); } states.clear(); mapView.onDestroy(); mapView = null; mapboxMap = null; unitsFab = null; menu = null; super.onDestroy(); }
Source:
List<ASTNode> getGroupByForClause(QBParseInfo parseInfo, String dest) throws SemanticException { ASTNode selectExpr = parseInfo.getSelForClause(dest); Collection<ASTNode> aggregateFunction = parseInfo.getDestToAggregationExprs().get(dest).values(); if (isSelectDistinct(selectExpr) && !isGroupBy(selectExpr) && !isAggregateInSelect(selectExpr, aggregateFunction)) { List<ASTNode> result = new ArrayList<ASTNode>(selectExpr == null ? 0 : selectExpr.getChildCount()); if (selectExpr != null) { for (int i = 0; i < selectExpr.getChildCount(); ++i) { if (((ASTNode) selectExpr.getChild(i)).getToken().getType() == HiveParser.QUERY_HINT) { continue; } ASTNode grpbyExpr = (ASTNode) selectExpr.getChild(i).getChild(0); result.add(grpbyExpr); } } return result; } else { ASTNode grpByExprs = parseInfo.getGroupByForClause(dest); List<ASTNode> result = new ArrayList<ASTNode>(grpByExprs == null ? 0 : grpByExprs.getChildCount()); if (grpByExprs != null) { for (int i = 0; i < grpByExprs.getChildCount(); ++i) { ASTNode grpbyExpr = (ASTNode) grpByExprs.getChild(i); if (grpbyExpr.getType() != HiveParser.TOK_GROUPING_SETS_EXPRESSION) { result.add(grpbyExpr); } } } return result; } }

Target:
List<ASTNode> getGroupByForClause(QBParseInfo parseInfo, String dest) throws SemanticException { ASTNode selectExpr = parseInfo.getSelForClause(dest); Collection<ASTNode> aggregateFunction = parseInfo.getDestToAggregationExprs().get(dest).values(); if (!(this instanceof CalcitePlanner) && isSelectDistinct(selectExpr) && hasGroupBySibling(selectExpr)) { throw new SemanticException("SELECT DISTINCT with GROUP BY is only supported with CBO"); } if (isSelectDistinct(selectExpr) && !hasGroupBySibling(selectExpr) && !isAggregateInSelect(selectExpr, aggregateFunction)) { List<ASTNode> result = new ArrayList<ASTNode>(selectExpr.getChildCount()); for (int i = 0; i < selectExpr.getChildCount(); ++i) { if (((ASTNode) selectExpr.getChild(i)).getToken().getType() == HiveParser.QUERY_HINT) { continue; } ASTNode grpbyExpr = (ASTNode) selectExpr.getChild(i).getChild(0); result.add(grpbyExpr); } return result; } else { ASTNode grpByExprs = parseInfo.getGroupByForClause(dest); List<ASTNode> result = new ArrayList<ASTNode>(grpByExprs == null ? 0 : grpByExprs.getChildCount()); if (grpByExprs != null) { for (int i = 0; i < grpByExprs.getChildCount(); ++i) { ASTNode grpbyExpr = (ASTNode) grpByExprs.getChild(i); if (grpbyExpr.getType() != HiveParser.TOK_GROUPING_SETS_EXPRESSION) { result.add(grpbyExpr); } } } return result; } }
Source:
@OnClick(R.id.email) void emailSupport() { String body = "Version: " + BuildConfig.VERSION_NAME + "\n" + "\n" + "-- Device --" + "\n" + "Make: " + Build.MANUFACTURER + "\n" + "Model: " + Build.MODEL + "\n" + "Release: " + Build.VERSION.RELEASE + "\n" + "API: " + Build.VERSION.SDK_INT + "\n" + "\n" + "-- Description --" + "\n"; Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")) .putExtra(Intent.EXTRA_EMAIL, new String[]{supportEmail}) .putExtra(Intent.EXTRA_TEXT, body); Context context = getView().getContext(); if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { Timber.w("No app available to handle email intent"); } }

Target:
void emailSupport() { String body = "Version: " + BuildConfig.VERSION_NAME + "\n" + "\n" + "-- Device --" + "\n" + "Make: " + Build.MANUFACTURER + "\n" + "Model: " + Build.MODEL + "\n" + "Release: " + Build.VERSION.RELEASE + "\n" + "API: " + Build.VERSION.SDK_INT + "\n" + "\n" + "-- Description --" + "\n"; Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")) .putExtra(Intent.EXTRA_EMAIL, new String[]{supportEmail}) .putExtra(Intent.EXTRA_TEXT, body); Context context = getView().getContext(); if (intent.resolveActivity(context.getPackageManager()) != null) { context.startActivity(intent); } else { Timber.w("No app available to handle email intent"); } }
Source:
private boolean addImageTicketToProxy(Guid imagedTicketId, String hostUri) { ImageTicket imageTicket = new ImageTicket(); imageTicket.setId(imagedTicketId); imageTicket.setTimeout(getClientTicketLifetime()); imageTicket.setSize(getParameters().getTransferSize()); imageTicket.setUrl(String.format("%s/images/%s", hostUri, imagedTicketId)); imageTicket.setTransferId(getParameters().getCommandId().toString()); imageTicket.setFilename(getParameters().getDownloadFilename()); imageTicket.setSparse(isSparseImage()); imageTicket.setOps(new String[] {getParameters().getTransferType().getAllowedOperation()}); try { log.info("Adding image ticket to ovirt-imageio-proxy, id {}", imagedTicketId); getImageioClient().putTicket(imageTicket); } catch (RuntimeException e) { log.error("Failed to add image ticket to ovirt-imageio-proxy: {}", e.getMessage(), e); return false; } return true; }

Target:
private boolean addImageTicketToProxy(Guid imagedTicketId, String hostUri) { ImageTicket imageTicket = new ImageTicket(); imageTicket.setId(imagedTicketId); imageTicket.setTimeout(getClientTicketLifetime()); imageTicket.setSize(getParameters().getTransferSize()); imageTicket.setUrl(String.format( "%s/%s/%s", hostUri, IMAGES_PATH, imagedTicketId)); imageTicket.setTransferId(getParameters().getCommandId().toString()); imageTicket.setFilename(getParameters().getDownloadFilename()); imageTicket.setSparse(isSparseImage()); imageTicket.setOps(new String[] {getParameters().getTransferType().getAllowedOperation()}); try { log.info("Adding image ticket to ovirt-imageio-proxy, id {}", imagedTicketId); getImageioClient().putTicket(imageTicket); } catch (RuntimeException e) { log.error("Failed to add image ticket to ovirt-imageio-proxy: {}", e.getMessage(), e); return false; } return true; }
Source:
public void run() { HTInterval currentInterval; try { currentInterval = intervalQueue.peekLast(); while (currentInterval.getStartTime() != -1) { getSHT().insertInterval(currentInterval); intervalQueue.take(); currentInterval = intervalQueue.peekLast(); } if (currentInterval.getAttribute() != -1) { throw new IllegalStateException(); } getSHT().closeTree(currentInterval.getEndTime()); return; } catch (TimeRangeException e) { Activator.getDefault().logError("Error starting the state system", e); } }

Target:
public void run() { try { synchronized (intervalQueue) { fCurrentInterval = intervalQueue.take(); } while (fCurrentInterval.getStartTime() != -1) { getSHT().insertInterval(fCurrentInterval); synchronized (intervalQueue) { fCurrentInterval = intervalQueue.take(); } } if (fCurrentInterval.getAttribute() != -1) { throw new IllegalStateException(); } getSHT().closeTree(fCurrentInterval.getEndTime()); return; } catch (TimeRangeException e) { Activator.getDefault().logError("Error starting the state system", e); } }
Source:
public void mercury_search_navigateUsingSearchSuggestionsOnDesktop() { Search search = new ArticlePage() .open("/d/") .getTopBar() .openSearch() .typeInSearch(this.SEARCH_PHRASE); String suggestionText = search.getSearchSuggestionText(0).replaceAll(" ", "_"); search.selectSearchSuggestion(0); Assertion.assertTrue(driver.getCurrentUrl().contains(suggestionText)); Assertion.assertTrue(new SkinHelper(driver).isSkin(Skin.OASIS)); }

Target:
public void mercury_search_navigateUsingSearchSuggestionsOnDesktop() { String clickedSuggestion = new ArticlePage() .open("/d/") .getTopBar() .openSearch() .typeInSearch(SEARCH_PHRASE) .clickSearchSuggestion(0); Assertion.assertTrue(new SkinHelper(driver).isSkin(Skin.OASIS)); Assertion.assertEquals(clickedSuggestion.toLowerCase(), new ArticlePageObject().getArticleName().toLowerCase()); }
Source:
public void verifySuggestAVideoOrArticleModalTopic() { waitForElementByElement(suggestVideoOrArticleModalTopic); PageObjectLogging.log("VerifySuggestAVideoOrArticleModalTopic", "Verify that suggest a video or an article", true); }

Target:
public void verifySuggestAVideoOrArticleModalTopic() { waitForElementByElement(suggestVideoOrArticleModalTopic); PageObjectLogging.log( "verifySuggestAVideoOrArticleModalTopic", "Verify that suggest a video or an article", true ); }
Source:
public int category(Object element) { if (element instanceof RepositoryTreeNode) { RepositoryTreeNode<?> node = (RepositoryTreeNode<?>) element; RepositoryTreeNodeType type = node.getType(); switch (type) { case REPOGROUP: return -1; case BRANCHHIERARCHY: return RepositoryTreeNodeType.REF.ordinal(); default: return type.ordinal(); } } return super.category(element); }

Target:
public int category(Object element) { if (element instanceof RepositoryTreeNode) { RepositoryTreeNode<?> node = (RepositoryTreeNode<?>) element; RepositoryTreeNodeType type = node.getType(); switch (type) { case REPOGROUP: return RepositoryTreeNodeType.values().length; case BRANCHHIERARCHY: return RepositoryTreeNodeType.REF.ordinal(); default: return type.ordinal(); } } return super.category(element); }
Source:
public ParallelTransferOptions(Integer blockSize, Integer numBuffers, ProgressReceiver progressReceiver) { if (blockSize != null) { StorageImplUtils.assertInBounds("blockSize", blockSize, 0, BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES); } this.blockSize = blockSize; if (numBuffers != null) { StorageImplUtils.assertInBounds("numBuffers", numBuffers, 2, Integer.MAX_VALUE); } this.numBuffers = numBuffers; this.progressReceiver = progressReceiver; }

Target:
public ParallelTransferOptions(Integer blockSize, Integer numBuffers, ProgressReceiver progressReceiver) { if (blockSize != null) { StorageImplUtils.assertInBounds("blockSize", blockSize, 1, BlockBlobAsyncClient.MAX_STAGE_BLOCK_BYTES); } this.blockSize = blockSize; if (numBuffers != null) { StorageImplUtils.assertInBounds("numBuffers", numBuffers, 2, Integer.MAX_VALUE); } this.numBuffers = numBuffers; this.progressReceiver = progressReceiver; }
Source:
public CoordinatorAdminClient(RESTClientConfig config) { this.config = config; this.httpClientFactory = new HttpClientFactory(); Map<String, String> properties = new HashMap<String, String>(); properties.put(HttpClientFactory.HTTP_POOL_SIZE, Integer.toString(this.config.getMaxR2ConnectionPoolSize())); this.client = new TransportClientAdapter(httpClientFactory.getClient(properties)); }

Target:
public CoordinatorAdminClient(RESTClientConfig config) { this.config = config; this.httpClientFactory = new HttpClientFactory(); Map<String, String> properties = Maps.newHashMap(); properties.put(HttpClientFactory.HTTP_POOL_SIZE, Integer.toString(this.config.getMaxR2ConnectionPoolSize())); this.client = new TransportClientAdapter(httpClientFactory.getClient(properties)); }
Source:
public void setActionConfirmationMessage(String message) { boolean isNonEmptyMessage = message != null; if (isNonEmptyMessage) { actionConfirmationMessage.setText(message); } actionConfirmationMessage.setVisible(isNonEmptyMessage); }

Target:
public void setActionConfirmationMessage(String message) { boolean isNonEmptyMessage = message != null; if (isNonEmptyMessage) { actionConfirmationMessage.setText(message); } }
Source:
protected static boolean checkProtocolPresent(String hostNames, String protocolName) { final String[] uris = hostNames.toString().split("\\r?\\n"); return Arrays.stream(uris) .map(uri -> uri.substring(0, uri.indexOf(PROTOCOL_SEPARATOR))) .anyMatch(uri -> uri.equals(protocolName)); }

Target:
protected static boolean checkProtocolPresent(String hostNames, String protocolName) { final String[] uris = hostNames.toString().split("\\r?\\n"); return Arrays.stream(uris) .map(uri -> uri.substring(0, uri.indexOf(PROTOCOL_SEPARATOR))) .anyMatch(uri -> Objects.equals(uri, protocolName)); }
Source:
public ILaunchDescriptor getDescriptor(Object element) { if (element instanceof ILaunchConfiguration) { ILaunchConfiguration config = (ILaunchConfiguration) element; try { if( config.getType().isPublic() && !(config.getAttribute(ILaunchManager.ATTR_PRIVATE, false))) { DefaultLaunchDescriptor descriptor = descriptors.get(config); if (descriptor == null) { descriptor = new DefaultLaunchDescriptor(this, config); descriptors.put(config, descriptor); } return descriptor; } } catch(CoreException ce) { Activator.log(ce.getStatus()); } catch(NullPointerException npe) { npe.printStackTrace(); } } return null; }

Target:
public ILaunchDescriptor getDescriptor(Object element) { if (element instanceof ILaunchConfiguration) { ILaunchConfiguration config = (ILaunchConfiguration) element; try { if( config.getType() != null && config.getType().isPublic() && !(config.getAttribute(ILaunchManager.ATTR_PRIVATE, false))) { DefaultLaunchDescriptor descriptor = descriptors.get(config); if (descriptor == null) { descriptor = new DefaultLaunchDescriptor(this, config); descriptors.put(config, descriptor); } return descriptor; } } catch(CoreException ce) { Activator.log(ce.getStatus()); } } return null; }
Source:
private ServerListReader getServerListReader() { if (serverListReaderRef.get() == null) { EurekaInterestClient interestClient; if (Eureka2Clients.getInterestClient() != null) { logger.info("Initializing Eureka2EnabledNIWSServerList with EurekaInterestClient provided by EurekaClients singleton"); interestClient = Eureka2Clients.getInterestClient(); } else { String writeClusterHost = clientConfig.getPropertyAsString(EUREKA2_WRITE_CLUSTER_HOST_KEY, null); int interestPort = clientConfig.getPropertyAsInteger(EUREKA2_WRITE_CLUSTER_INTEREST_PORT_KEY, EurekaTransports.DEFAULT_DISCOVERY_PORT); String readClusterVip = clientConfig.getPropertyAsString(EUREKA2_READ_CLUSTER_VIP_KEY, null); logger.info("Initializing Eureka2EnabledNIWSServerList from IClientConfig (writeClusterHost={}, interestPort={}, readClusterVip={})", new Object[]{writeClusterHost, interestPort, readClusterVip}); ServerResolver writeClusterResolver; if (writeClusterHost.indexOf('.') == -1) { writeClusterResolver = ServerResolvers.from(new Server(writeClusterHost, interestPort)); } else { writeClusterResolver = ServerResolvers.fromDnsName(writeClusterHost).withPort(interestPort); } ServerResolver readClusterResolver = ServerResolvers .fromEureka(writeClusterResolver) .forInterest(Interests.forVips(readClusterVip)); interestClient = Eurekas.newInterestClientBuilder().withServerResolver(readClusterResolver).build(); } String[] vipAddresses = this.vipAddresses.split(","); serverListReaderRef.compareAndSet(null, new ServerListReader(interestClient, vipAddresses, isSecure)); } return serverListReaderRef.get(); }

Target:
private ServerListReader getServerListReader() { ServerListReader current = serverListReaderRef.get(); if (current != null && current.isClosed()) { serverListReaderRef.compareAndSet(current, null); return getServerListReader(); } if (current == null) { ServerListReader serverListReader = new ServerListReader(clientConfig, isSecure, vipAddresses); if (!serverListReaderRef.compareAndSet(null, serverListReader)) { serverListReader.shutdown(); } } return serverListReaderRef.get(); }
Source:
public int getIndex() { return findex; }

Target:
public long getIndex() { return findex; }
Source:
private void setCommandExecutionAllowed(boolean isAllowed){ isExecutionAllowed = isAllowed; newCommand.setIsExecutionAllowed(isAllowed); updateRemoveActionAvailability(); }

Target:
private void setCommandExecutionAllowed(boolean isAllowed){ isExecutionAllowed = isAllowed; updateActionAvailability(); }
Source:
public void onSuccessfulResponse(ReplicaId replicaId) { super.onSuccessfulResponse(replicaId); if(isLocalDone) { coordinatorMetrics.crossColoProxyCallCount.inc(); logger.trace("Operation succeeded after going cross colo"); } logger.trace("Successful response from " + replicaId); onReplicaResponse(replicaId); }

Target:
public void onSuccessfulResponse(ReplicaId replicaId) { super.onSuccessfulResponse(replicaId); if(proxied) { coordinatorMetrics.crossColoProxyCallCount.inc(); logger.trace("Operation succeeded after going cross colo"); } logger.trace("Successful response from " + replicaId); onReplicaResponse(replicaId); }
Source:
public String modifyLanguage( final ModifyLanguageParamsJson params ) { return Optional.ofNullable( doApplyLanguage( params.getName(), params.getLanguage() ) ). map( Locale::toLanguageTag ). orElse( null ); }

Target:
public String modifyLanguage( final ModifyLanguageParamsJson params ) { return doApplyLanguage( params.getName(), params.getLanguage() ). map( Locale::toLanguageTag ). orElse( null ); }
Source:
public void testConfigHardwareMitigations() throws Exception { String mitigations[] = null; if (PropertyUtil.getFirstApiLevel(mDevice) < 28) { return; } if (CpuFeatures.isArm64(mDevice) && !CpuFeatures.kernelVersionLessThan(mDevice, 4, 4)) { mitigations = lookupMitigations(); if (mitigations != null) { for (String mitigation : mitigations) { assertTrue("Linux kernel must have " + mitigation + " enabled.", configSet.contains(mitigation)); } } } else if (CpuFeatures.isX86(mDevice)) { assertTrue("Linux kernel must have KPTI enabled: CONFIG_PAGE_TABLE_ISOLATION=y", configSet.contains("CONFIG_PAGE_TABLE_ISOLATION=y")); } }

Target:
public void testConfigHardwareMitigations() throws Exception { String mitigations[]; if (PropertyUtil.getFirstApiLevel(mDevice) < 28) { return; } if (CpuFeatures.isArm64(mDevice) && !CpuFeatures.kernelVersionLessThan(mDevice, 4, 4)) { mitigations = lookupMitigations(); if (mitigations != null) { for (String mitigation : mitigations) { assertTrue("Linux kernel must have " + mitigation + " enabled.", configSet.contains(mitigation)); } } } else if (CpuFeatures.isX86(mDevice)) { assertTrue("Linux kernel must have KPTI enabled: CONFIG_PAGE_TABLE_ISOLATION=y", configSet.contains("CONFIG_PAGE_TABLE_ISOLATION=y")); } }
Source:
public void addCommand(String rawLine) throws PackProtocolException { checkCommandLine(rawLine); String line = rawLine.substring(0, rawLine.length() - 1); ReceiveCommand cmd; try { cmd = parseCommand(line); } catch (IllegalArgumentException | StringIndexOutOfBoundsException e) { throw new PackProtocolException(MessageFormat.format( JGitText.get().pushCertificateInvalidFieldValue, "command", rawLine), e); } commands.add(cmd); rawCommands.append(rawLine); }

Target:
public void addCommand(String rawLine) throws PackProtocolException { checkCommandLine(rawLine); String line = rawLine.substring(0, rawLine.length() - 1); commands.add(parseCommand(line)); rawCommands.append(rawLine); }
Source:
private synchronized void resetGeneration() { this.generation = Generation.NO_GENERATION; rejoinNeeded = true; if (state != MemberState.REBALANCING) state = MemberState.UNJOINED; }

Target:
private synchronized void resetGeneration() { this.rejoinNeeded = true; this.generation = Generation.NO_GENERATION; }
Source:
public void before() { installTestMom(JmsTestMom.class); m_messageHandler = mock(IJmsMessageHandler.class); m_messageHandlerBean = BeanTestingHelper.get().registerBean(new BeanMetaData(IJmsMessageHandler.class, m_messageHandler).withAnnotation(AnnotationFactory.createApplicationScoped())); assertSame(m_messageHandler, BEANS.get(IJmsMessageHandler.class)); LOG.info("---------------------------------------------------"); LOG.info("<{}>", m_testName.getMethodName()); m_t0 = System.nanoTime(); m_testJobExecutionHint = UUID.randomUUID().toString(); m_disposables = new ArrayList<>(); }

Target:
public void before() { installTestMom(JmsTestMom.class); installTestMessageHandler(); LOG.info("---------------------------------------------------"); LOG.info("<{}>", m_testName.getMethodName()); m_t0 = System.nanoTime(); m_testJobExecutionHint = UUID.randomUUID().toString(); m_disposables = new ArrayList<>(); }
Source:
public static void publishNotification(PublishedCollection publishedCollection, boolean publishComplete) { if (publishedCollection == null) { logWarn("failed to send publish slack notification as published collection was null").log(); return; } String slackMessage = "Collection " + publishedCollection.getName() + " did not publish"; if (publishComplete) { Result result = publishedCollection.publishResults.get(0); StringBuilder msg = new StringBuilder("Published collection: " + publishedCollection.getName()); if (publishedCollection.publishStartDate != null && publishedCollection.publishEndDate != null) { msg.append(" publish time : " + format.format(publishedCollection.publishStartDate)); String timeTaken = String.format("%.2f", (publishedCollection.publishEndDate.getTime() - publishedCollection.publishStartDate.getTime()) / 1000.0); msg.append(" time taken: " + timeTaken + " "); } result.transaction.uriInfos .stream() .filter(info -> info.uri.endsWith("data.json")) .findFirst() .ifPresent(urlInfo -> { msg.append("Example Uri: <LINK_0>") .append(urlInfo.uri.substring(0, urlInfo.uri.length() - ("data" + ".json").length())); }); slackMessage = msg.toString(); } try { sendPublishNotification(slackMessage); } catch (Exception e) { logError(e, "Slack publish notification error") .collectionName(publishedCollection.getName()) .log(); } }

Target:
public static void publishNotification(PublishedCollection publishedCollection, boolean publishComplete) { if (publishedCollection == null) { logWarn("failed to send publish slack notification as published collection was null").log(); return; } String slackMessage = "Collection " + publishedCollection.getName() + " did not publish"; if (publishComplete) { Result result = publishedCollection.publishResults.get(0); StringBuilder msg = new StringBuilder("Published collection: " + publishedCollection.getName()); if (publishedCollection.publishStartDate != null && publishedCollection.publishEndDate != null) { msg.append(" publish time : " + format.format(publishedCollection.publishStartDate)); String timeTaken = String.format("%.2f", (publishedCollection.publishEndDate.getTime() - publishedCollection.publishStartDate.getTime()) / 1000.0); msg.append(" time taken: " + timeTaken + " "); } result.transaction.uriInfos .stream() .filter(info -> info.uri.endsWith(DATA_JSON)) .findFirst() .ifPresent(urlInfo -> { msg.append("Example Uri: <LINK_0>") .append(urlInfo.uri.substring(0, urlInfo.uri.length() - (DATA_JSON).length())); }); slackMessage = msg.toString(); } try { sendPublishNotification(slackMessage); } catch (Exception e) { logError(e, "Slack publish notification error") .collectionName(publishedCollection.getName()) .log(); } }
Source:
private void processShallow() throws IOException { DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(db, depth - 1, DepthWalk.CompareMode.EQUAL); for (RevCommit c : wantCommits) { RevCommit commit = depthWalk.parseCommit(c); depthWalk.markStart(commit); } RevObject o; while ((o = depthWalk.next()) != null) { localShallowCommits.add((RevCommit)o); boolean found = false; for (RevCommit c : remoteShallowCommits) { if (c.name() == o.name()) { found = true; break; } } if (!found) { pckOut.writeString("shallow " + o.name()); } } for (RevCommit remote : remoteShallowCommits) { boolean found = false; for(RevCommit local : localShallowCommits) { if(remote.name() == local.name()) { found = true; break; } } if (!found) { pckOut.writeString("unshallow " + remote.name()); } } pckOut.end(); }

Target:
private void processShallow() throws IOException { DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(walk.getObjectReader(), depth); for (RevObject o : wantAll) { if (o instanceof RevCommit) depthWalk.markStart(depthWalk.parseCommit(o)); } RevObject o; while ((o = depthWalk.next()) != null) { DepthWalk.Commit c = (DepthWalk.Commit)o; if (c.depth == depth && !clientShallowCommits.contains(c)) { pckOut.writeString("shallow " + o.name()); } if (c.depth < depth && clientShallowCommits.contains(c)) { unshallowCommits.add(c); pckOut.writeString("unshallow " + c.name()); } } pckOut.end(); }
Source:
public WeldBeanDeploymentArchive build() { if (id == null) { throw CommonLogger.LOG.idMustBeSet(); } return new WeldBeanDeploymentArchive(id, classes, getBeansXml()); }

Target:
public WeldBeanDeploymentArchive build() { Preconditions.checkArgumentNotNull(id, "id"); return new WeldBeanDeploymentArchive(id, classes, getBeansXml()); }
Source:
public LzoGenericB64LineRecordReader(TypeRef<M> typeRef, BinaryConverter<M> converter) { super(typeRef, new GenericWritable<M>(converter), converter); LOG.info("record type is " + typeRef.getRawClass()); }

Target:
public LzoGenericB64LineRecordReader(TypeRef<M> typeRef, BinaryConverter<M> converter) { super(typeRef, new GenericWritable<M>(converter), converter); }
Source:
void transformEntryTypeValues(final Map<Integer, List<ObservationUnitRow>> observationUnitRowMap) { final List<Enumeration> entryTypes = this.ontologyDataManager .getStandardVariable(TermId.ENTRY_TYPE.getId(), this.contextUtil.getCurrentProgramUUID()).getEnumerations(); final Map<String, String> entryTypeDescriptionNameMap = new HashMap<>(); for(final Enumeration entryType: entryTypes) { entryTypeDescriptionNameMap.put(entryType.getDescription(), entryType.getName()); } for(Integer instanceId: observationUnitRowMap.keySet()) { final List<ObservationUnitRow> observationUnitRows = observationUnitRowMap.get(instanceId); for(ObservationUnitRow row: observationUnitRows) { final ObservationUnitData data = row.getVariables().get(TermId.ENTRY_TYPE.name()); data.setValue(entryTypeDescriptionNameMap.get(data.getValue())); } } }

Target:
void transformEntryTypeValues(final Map<Integer, List<ObservationUnitRow>> observationUnitRowMap) { final List<Enumeration> entryTypes = this.ontologyDataManager .getStandardVariable(TermId.ENTRY_TYPE.getId(), this.contextUtil.getCurrentProgramUUID()).getEnumerations(); final Map<String, String> entryTypeDescriptionNameMap = entryTypes.stream().collect(Collectors.toMap(Enumeration::getDescription, Enumeration::getName)); final List<ObservationUnitRow> allRows = observationUnitRowMap.values().stream().flatMap(list -> list.stream()).collect(Collectors.toList()); allRows.forEach(row -> { final ObservationUnitData data = row.getVariables().get(TermId.ENTRY_TYPE.name()); data.setValue(entryTypeDescriptionNameMap.get(data.getValue())); }); }
Source:
private void clearCachefiles() { final File cacheDir = new File(MainActivity.getSDPath()); final File[] cacheFiles = cacheDir.listFiles(new FilenameFilter() { @Override public boolean accept( final File dir, final String name ) { return name.matches( ".*-cache\\.json" ); } } ); for (File cache: cacheFiles) { cache.delete(); } }

Target:
private void clearCachefiles() { final File cacheDir = new File(MainActivity.getSDPath()); final File[] cacheFiles = cacheDir.listFiles(new FilenameFilter() { @Override public boolean accept( final File dir, final String name ) { return name.matches( ".*-cache\\.json" ); } } ); if (null != cacheFiles) { for (File cache: cacheFiles) { boolean deleted = cache.delete(); if (!deleted) { MainActivity.warn("failed to delete cache file: "+cache.getAbsolutePath()); } } } }
Source:
public void star() throws IOException { root.createRequest().method("PUT").setRawUrlPath(getApiTailUrl("star")).send(); }

Target:
public void star() throws IOException { root.createRequest().method("PUT").withUrlPath(getApiTailUrl("star")).send(); }
Source:
private Player findVictim() { if (goingToAttack) { return null; } if (hasRan()) { return null; } long now = GameEngine.getTime(); if (getChasing() != null) { return null; } ActiveTile[][] tiles = getViewArea().getViewedArea(2, 2, 2, 2); for (int x = 0; x < tiles.length; x++) { for (int y = 0; y < tiles[x].length; y++) { ActiveTile t = tiles[x][y]; if (t != null) { for (Player p : t.getPlayers()) { if (p.inCombat()) { continue; } if (p.isBusy() || p.isNonaggro() || now - p.getCombatTimer() < (p .getCombatState() == CombatState.RUNNING || p.getCombatState() == CombatState.WAITING ? 3000 : 500) || !p.nextTo(this) || !p.getLocation().inBounds(loc.minX - 4, loc.minY - 4, loc.maxX + 4, loc.maxY + 4) || System.currentTimeInMillis() - p.getLastPing() > 60000) { continue; } if (getLocation().inWilderness() || p.getCombatLevel() < (getCombatLevel() * 2) + 1) { return p; } } } } } return null; }

Target:
private Player findVictim() { if (goingToAttack) { return null; } if (hasRan()) { return null; } long now = GameEngine.getTime(); if (getChasing() != null) { return null; } ActiveTile[][] tiles = getViewArea().getViewedArea(2, 2, 2, 2); for (int x = 0; x < tiles.length; x++) { for (int y = 0; y < tiles[x].length; y++) { ActiveTile t = tiles[x][y]; if (t != null) { for (Player p : t.getPlayers()) { if (p.inCombat()) { continue; } if (p.isBusy() || p.isNonaggro() || now - p.getCombatTimer() < (p .getCombatState() == CombatState.RUNNING || p.getCombatState() == CombatState.WAITING ? 3000 : 500) || !p.nextTo(this) || !p.getLocation().inBounds(loc.minX - 4, loc.minY - 4, loc.maxX + 4, loc.maxY + 4) || GameEngine.getTime() - p.getLastPing() > 60000) { continue; } if (getLocation().inWilderness() || p.getCombatLevel() < (getCombatLevel() * 2) + 1) { return p; } } } } } return null; }
Source:
public void reduce() throws Exception { int part = 0; for (File inputFile : _reducerInputDir.listFiles()) { RecordReader avroRecordReader = RecordReaderFactory .getRecordReaderByClass("org.apache.pinot.plugin.inputformat.avro.AvroRecordReader", inputFile, _pinotSchema.getColumnNames(), null); while (avroRecordReader.hasNext()) { GenericRow next = avroRecordReader.next(); _collector.collect(next); if (_collector.size() == MAX_RECORDS_TO_COLLECT) { int numFiles = flushRecords(_collector, part); part += numFiles; _collector.reset(); } } } if (_collector.size() > 0) { flushRecords(_collector, part); _collector.reset(); } }

Target:
public void reduce() throws Exception { int part = 0; for (File inputFile : _reducerInputDir.listFiles()) { RecordReader avroRecordReader = RecordReaderFactory .getRecordReaderByClass("org.apache.pinot.plugin.inputformat.avro.AvroRecordReader", inputFile, _pinotSchema.getColumnNames(), null); while (avroRecordReader.hasNext()) { GenericRow next = avroRecordReader.next(); _collector.collect(next); if (_collector.size() == _numRecordsPerPart) { flushRecords(_collector, createReducerOutputFileName(_reducerId, part++)); _collector.reset(); } } } if (_collector.size() > 0) { flushRecords(_collector, createReducerOutputFileName(_reducerId, part)); _collector.reset(); } }
Source:
public StoredConfig getSystemConfig() throws IOException, ConfigInvalidException { FileBasedConfig c = openSystemConfig(null, FS.DETECTED); if (c.isOutdated()) { LOG.debug("loading system config {}", systemConfig); c.load(); } return c; }

Target:
public StoredConfig getSystemConfig() throws IOException, ConfigInvalidException { FileBasedConfig c = systemConfig.get(); if (c == null) { systemConfig.compareAndSet(null, openSystemConfig(null, FS.DETECTED)); c = systemConfig.get(); } if (c.isOutdated()) { LOG.debug("loading system config {}", systemConfig); c.load(); } return c; }
Source:
public Metacard getBaseMetacard(Map<String, Object> properties, List<MetacardType> metacardTypes) throws CatalogTransformerException { final String propertyTypeName = (String) properties.get(METACARD_TYPE_PROPERTY_KEY); MetacardImpl metacard; if (isEmpty(propertyTypeName) || metacardTypes == null) { LOGGER.debug( "MetacardType specified in input is null or empty. Assuming default MetacardType"); metacard = new MetacardImpl(); } else { MetacardType metacardType = metacardTypes .stream() .filter(type -> type.getName().equals(propertyTypeName)) .findFirst() .orElseThrow( () -> new CatalogTransformerException( "MetacardType specified in input has not been registered with the system. Cannot parse input. MetacardType name: " + propertyTypeName)); LOGGER.debug("Found registered MetacardType: {}", propertyTypeName); metacard = new MetacardImpl(metacardType); } return metacard; }

Target:
protected Metacard getBaseMetacard( Map<String, Object> properties, List<MetacardType> metacardTypes) throws CatalogTransformerException { final String propertyTypeName = (String) properties.get(METACARD_TYPE_PROPERTY_KEY); MetacardImpl metacard; if (isEmpty(propertyTypeName) || metacardTypes == null) { LOGGER.debug( "MetacardType specified in input is null or empty. Assuming default MetacardType"); metacard = new MetacardImpl(); } else { MetacardType metacardType = metacardTypes .stream() .filter(type -> type.getName().equals(propertyTypeName)) .findFirst() .orElseThrow( () -> new CatalogTransformerException( "MetacardType specified in input has not been registered with the system. Cannot parse input. MetacardType name: " + propertyTypeName)); LOGGER.debug("Found registered MetacardType: {}", propertyTypeName); metacard = new MetacardImpl(metacardType); } return metacard; }
Source:
protected void onMethodInvocationFound(MethodInvocationTree mit) { if (!hasSemantic()) { return; } Arguments arguments = mit.arguments(); ExpressionTree argumentExpression; if (hasBooleanArgumentAtPosition(arguments, 0)) { argumentExpression = arguments.get(0); } else if (hasBooleanArgumentAtPosition(arguments, arguments.size() - 1)) { argumentExpression = arguments.get(arguments.size() - 1); } else { return; } Optional<Assertion> replacementAssertionOpt = getReplacementAssertion(argumentExpression); if (replacementAssertionOpt.isPresent()) { IdentifierTree problematicAssertionCallIdentifier = ExpressionUtils.methodName(mit); if (problematicAssertionCallIdentifier.name().equals("assertFalse")) { replacementAssertionOpt = complement(replacementAssertionOpt.get()); if (!replacementAssertionOpt.isPresent()) { return; } } Assertion replacementAssertion = replacementAssertionOpt.get(); List<JavaFileScannerContext.Location> secondaryLocation = Collections.singletonList(new JavaFileScannerContext.Location( String.format("%s is performed here, which is better expressed with %s.", replacementAssertion.actionDescription, replacementAssertion.methodName), argumentExpression)); String message = String.format("Use %s instead.", replacementAssertion.methodName); reportIssue(problematicAssertionCallIdentifier, message, secondaryLocation, null); } }

Target:
protected void onMethodInvocationFound(MethodInvocationTree mit) { mit.arguments().stream() .filter(argument -> argument.symbolType().isPrimitive(Type.Primitives.BOOLEAN)) .findFirst() .ifPresent(argument -> checkBooleanExpressionInAssertMethod(ExpressionUtils.methodName(mit), argument)); }
Source:
private VariantContextJavascriptFilter(final File scriptFile, final VCFHeader header) throws IOException { super(scriptFile, header); this.scriptFile = scriptFile; String fname = scriptFile.getName(); if (fname.toLowerCase().endsWith(".js")) { fname = fname.substring(0, fname.length() - 3); } else if (fname.toLowerCase().endsWith(".javascript")) { fname = fname.substring(0, fname.length() - 11); } if(fname.isEmpty()) fname="JSFILTER"; this.filterName = fname; }

Target:
private VariantContextJavascriptFilter(final File scriptFile, final VCFHeader header) throws IOException { super(scriptFile, header); this.scriptFile = scriptFile; String fname = IOUtil.basename(scriptFile); if(fname.isEmpty()) fname="JSFILTER"; this.filterName = fname; }
Source:
private boolean initGlusterHost() { glusterHostUuidFound = true; if (GlusterFeatureSupported.glusterHostUuidSupported(getVdsGroup().getcompatibility_version())) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHostUUID, new VdsIdVDSCommandParametersBase(getVds().getId())); Guid addedServerUuid = Guid.createGuidFromString((String) returnValue.getReturnValue()); if (returnValue.getSucceeded() && returnValue.getReturnValue() != null) { if (!checkIfHostUuidExists(addedServerUuid)) { glusterHostUuidFound = true; setNonOperational(NonOperationalReason.GLUSTER_HOST_UUID_ALREADY_EXISTS, null); return false; } saveGlusterHostUuid(addedServerUuid); } else { glusterHostUuidFound = false; setNonOperational(NonOperationalReason.GLUSTER_HOST_UUID_NOT_FOUND, null); } } return glusterHostUuidFound && initGlusterPeerProcess(); }

Target:
private boolean initGlusterHost() { glusterHostUuidFound = true; if (GlusterFeatureSupported.glusterHostUuidSupported(getVdsGroup().getcompatibility_version())) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterHostUUID, new VdsIdVDSCommandParametersBase(getVds().getId())); if (returnValue.getSucceeded() && returnValue.getReturnValue() != null) { Guid addedServerUuid = Guid.createGuidFromString((String) returnValue.getReturnValue()); if (hostUuidExists(addedServerUuid)) { setNonOperational(NonOperationalReason.GLUSTER_HOST_UUID_ALREADY_EXISTS, null); return false; } saveGlusterHostUuid(addedServerUuid); } else { glusterHostUuidFound = false; setNonOperational(NonOperationalReason.GLUSTER_HOST_UUID_NOT_FOUND, null); } } return glusterHostUuidFound && initGlusterPeerProcess(); }
Source:
protected Long nullUnsafeScalar(MonthDay value) { LocalDate date = value.atYear( LEAP_YEAR ); return date.atStartOfDay().atZone( ZoneOffset.UTC ).toInstant().toEpochMilli(); }

Target:
protected Long nullUnsafeScalar(MonthDay value) { LocalDate date = value.atYear( LEAP_YEAR ); return date.atStartOfDay().toInstant( ZoneOffset.UTC ).toEpochMilli(); }
Source:
public long skip(long n) throws IOException { if (n > MOVEMENT_LIMIT) { mSequentialReadCount = 0; mPos += n; return n; } else { long skipped = ((FSDataInputStream) in).skip(n); mPos += skipped; return skipped; } }

Target:
public long skip(long n) throws IOException { if (n <= 0) { return 0; } if (n > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } mPos += n; return n; }
Source:
private AssertionError clocksWentBackwards(long timestampLowerBound, long freshTimestamp) { return new AssertionError(String.format(CLOCKS_WENT_BACKWARDS_MESSAGE, timestampLowerBound, freshTimestamp)); }

Target:
private static AssertionError clocksWentBackwards(long timestampLowerBound, long freshTimestamp) { return new AssertionError(String.format(CLOCKS_WENT_BACKWARDS_MESSAGE, timestampLowerBound, freshTimestamp)); }
Source:
private void registerClearNotification(String alias, Cache<?, ?> cache) { OperationStatistic<ClearOutcome> clear = StatsUtils.findOperationStatisticOnChildren(cache, ClearOutcome.class, "clear"); clear.addDerivedStatistic(new OperationResultFilter<>(EnumSet.of(ClearOutcome.SUCCESS), (long time, long latency) -> cacheCleared(alias))); }

Target:
private void registerClearNotification(String alias, Cache<?, ?> cache) { OperationStatistic<ClearOutcome> clear = StatsUtils.findOperationStatisticOnChildren(cache, ClearOutcome.class, "clear"); clear.addDerivedStatistic(new OperationResultFilter<>(EnumSet.of(ClearOutcome.SUCCESS), (time, latency) -> cacheCleared(alias))); }
Source:
public @NotNull ConversionResult convertMessages(final Cursor cursor, DataType dataType) throws MessagingException { final Map<String, String> msgMap = getMessageMap(cursor); final Message m; switch (dataType) { case WHATSAPP: m = mMessageGenerator.messageFromMapWhatsApp(cursor); break; default: m = mMessageGenerator.messageForDataType(msgMap, dataType); break; } final ConversionResult result = new ConversionResult(dataType); if (m != null) { if(mSyncReadFlag) { switch (dataType) { case SMS: m.setFlag(Flag.SEEN, msgMap.get(SmsConsts.READ).equals("1")); break; case MMS: m.setFlag(Flag.SEEN, msgMap.get(MmsConsts.READ).equals("1")); break; default: m.setFlag(Flag.SEEN, mMarkAsRead); break; } } else { m.setFlag(Flag.SEEN, mMarkAsRead); } result.add(m, msgMap); } return result; }

Target:
public @NotNull ConversionResult convertMessages(final Cursor cursor, DataType dataType) throws MessagingException { final Map<String, String> msgMap = getMessageMap(cursor); final Message m; switch (dataType) { case WHATSAPP: m = mMessageGenerator.messageFromMapWhatsApp(cursor); break; default: m = mMessageGenerator.messageForDataType(msgMap, dataType); break; } final ConversionResult result = new ConversionResult(dataType); if (m != null) { m.setFlag(Flag.SEEN, markAsSeen(dataType, msgMap)); result.add(m, msgMap); } return result; }
Source:
public static boolean hasTelephony(Context context) { PackageManager pm = context.getPackageManager(); return pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) || ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getNetworkType()!= TelephonyManager.NETWORK_TYPE_UNKNOWN; }

Target:
public static boolean hasTelephony(Context context) { PackageManager pm = context.getPackageManager(); TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean hasNetwork = tm!=null ? tm.getNetworkType() != TelephonyManager.NETWORK_TYPE_UNKNOWN : false; return pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) || hasNetwork; }
Source:
double compute(OperationMetricKey key, ASTMethodOrConstructorDeclaration node, String name, boolean force) { for (OperationSignature sig : operations.keySet()) { for (OperationStats stats : operations.get(sig)) { if (stats.equals(name)) { return stats.compute(key, node, force); } } } return Double.NaN; }

Target:
double compute(OperationMetricKey key, ASTMethodOrConstructorDeclaration node, String name, boolean force) { Map<String, OperationStats> sigMap = operations.get(OperationSignature.buildFor(node)); if (sigMap == null) { return Double.NaN; } OperationStats stats = sigMap.get(name); return stats == null ? Double.NaN : stats.compute(key, node, force); }
Source:
static void register(Class<? extends Directive> directiveClass) { if (NestedContextDirective.class.isAssignableFrom(directiveClass)) { nestedContextDirectives.add(directiveClass); } if (FetchDirective.class.isAssignableFrom(directiveClass) && directiveClass != DefaultSrcDirective.class && directiveClass != FrameSrcDirective.class && directiveClass != WorkerSrcDirective.class) { fetchDirectives.add(directiveClass); } }

Target:
static void register(Class<? extends Directive> directiveClass) { if (NestedContextDirective.class.isAssignableFrom(directiveClass)) { nestedContextDirectives.add(directiveClass); } else if (FetchDirective.class.isAssignableFrom(directiveClass) && directiveClass != DefaultSrcDirective.class && directiveClass != FrameSrcDirective.class && directiveClass != WorkerSrcDirective.class) { fetchDirectives.add(directiveClass); } }
Source:
public void testLoginNotActivatedUserShouldFail() throws UnexpectedErrorException, NoConnectionException { HttpServletRequest httpRequest = new MockHttpServletRequest(); HttpServletResponse httpResponse = new MockHttpServletResponse(); LoginUserDto loginUserDto = new LoginUserDto("username", "password", true, "192.168.1.1"); when(authenticator.authenticate(loginUserDto, httpRequest, httpResponse)) .thenReturn(AuthenticationStatus.NOT_ENABLED); AuthenticationStatus result = userService.loginUser(loginUserDto, httpRequest, httpResponse); assertEquals(result, AuthenticationStatus.NOT_ENABLED, "Login not activated user should fail."); }

Target:
public void testLoginNotActivatedUserShouldFail() throws Exception { HttpServletRequest httpRequest = new MockHttpServletRequest(); HttpServletResponse httpResponse = new MockHttpServletResponse(); LoginUserDto loginUserDto = new LoginUserDto("username", "password", true, "192.168.1.1"); when(authenticator.authenticate(loginUserDto, httpRequest, httpResponse)) .thenReturn(AuthenticationStatus.NOT_ENABLED); AuthenticationStatus result = userService.loginUser(loginUserDto, httpRequest, httpResponse); assertEquals(result, AuthenticationStatus.NOT_ENABLED, "Login not activated user should fail."); }
Source:
public void testMappingDoesNotExistInInput() throws Exception { Schema inputSchema = Schema.recordOf("sourceRecord", Schema.Field.of(ID, Schema.of(Schema.Type.STRING)), Schema.Field.of(NAME, Schema.of(Schema.Type.STRING)), Schema.Field.of(SALARY, Schema.of(Schema.Type.STRING)), Schema.Field.of(DESIGNATIONID, Schema.of(Schema.Type.STRING))); ValueMapper.Config config = new ValueMapper.Config("does_not_exist:designation_lookup_table:designationName", "does_not_exist:DEFAULTID"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(inputSchema); ValueMapper mapper = new ValueMapper(config); String caughtException = ""; try { mapper.configurePipeline(configurer); } catch (Exception e) { caughtException = e.getMessage(); } Assert.assertEquals(validationExceptionMessage, caughtException); FailureCollector collector = configurer.getStageConfigurer().getFailureCollector(); Assert.assertEquals(1, collector.getValidationFailures().size()); Assert.assertEquals(1, collector.getValidationFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(stage, mockStage); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, MAPPING); expectedCause.addAttribute(CauseAttributes.CONFIG_ELEMENT, "does_not_exist:designation_lookup_table:designationName"); Assert.assertEquals(expectedCause, collector.getValidationFailures().get(0).getCauses().get(0)); }

Target:
public void testMappingDoesNotExistInInput() throws Exception { Schema inputSchema = Schema.recordOf("sourceRecord", Schema.Field.of(ID, Schema.of(Schema.Type.STRING)), Schema.Field.of(NAME, Schema.of(Schema.Type.STRING)), Schema.Field.of(SALARY, Schema.of(Schema.Type.STRING)), Schema.Field.of(DESIGNATIONID, Schema.of(Schema.Type.STRING))); ValueMapper.Config config = new ValueMapper.Config("does_not_exist:designation_lookup_table:designationName", "does_not_exist:DEFAULTID"); MockPipelineConfigurer configurer = new MockPipelineConfigurer(inputSchema); ValueMapper mapper = new ValueMapper(config); try { mapper.configurePipeline(configurer); Assert.fail(); } catch (ValidationException e) { Assert.assertEquals(1, e.getFailures().size()); Assert.assertEquals(1, e.getFailures().get(0).getCauses().size()); Cause expectedCause = new Cause(); expectedCause.addAttribute(STAGE, MOCK_STAGE); expectedCause.addAttribute(CauseAttributes.STAGE_CONFIG, ValueMapper.Config.MAPPING); expectedCause.addAttribute(CauseAttributes.CONFIG_ELEMENT, "does_not_exist:designation_lookup_table:designationName"); Assert.assertEquals(expectedCause, e.getFailures().get(0).getCauses().get(0)); } }