auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void expandInboundRelationships(List<SnomedConcept> results, final Set<String> conceptIds) { if (!expand().containsKey(SnomedConcept.Expand.INBOUND_RELATIONSHIPS)) { return; } final Options expandOptions = expand().get(SnomedConcept.Expand.INBOUND_RELATIONSHIPS, Options.class); final int relationshipSearchLimit = getLimit(expandOptions); final SnomedRelationships inboundRelationships = SnomedRequests.prepareSearchRelationship() .setLimit(relationshipSearchLimit) .filterByActive(expandOptions.containsKey("active") ? expandOptions.getBoolean("active") : null) .filterByCharacteristicType(expandOptions.containsKey("characteristicType") ? expandOptions.getString("characteristicType") : null) .filterByDestination(conceptIds) .setExpand(expandOptions.get("expand", Options.class)) .setLocales(locales()) .build() .execute(context()); final ListMultimap<String, SnomedRelationship> inboundRelationshipsByConceptId = Multimaps.index(inboundRelationships, inboundRelationship -> inboundRelationship.getDestinationId()); for (SnomedConcept concept : results) { final List<SnomedRelationship> conceptInboundRelationships = inboundRelationshipsByConceptId.get(concept.getId()); concept.setInboundRelationships(new SnomedRelationships(conceptInboundRelationships, null, null, conceptInboundRelationships.size(), conceptInboundRelationships.size())); } }

Target:
private void expandInboundRelationships(List<SnomedConcept> results, final Set<String> conceptIds) { if (!expand().containsKey(SnomedConcept.Expand.INBOUND_RELATIONSHIPS)) { return; } final Options expandOptions = expand().get(SnomedConcept.Expand.INBOUND_RELATIONSHIPS, Options.class); final int relationshipSearchLimit = getLimit(expandOptions); final SnomedRelationships inboundRelationships = SnomedRequests.prepareSearchRelationship() .setLimit(relationshipSearchLimit) .filterByType(expandOptions.containsKey("typeId") ? expandOptions.getCollection("typeId", String.class) : null) .filterBySource(expandOptions.containsKey("sourceId") ? expandOptions.getCollection("sourceId", String.class) : null) .filterByActive(expandOptions.containsKey("active") ? expandOptions.getBoolean("active") : null) .filterByCharacteristicType(expandOptions.containsKey("characteristicType") ? expandOptions.getString("characteristicType") : null) .filterByDestination(conceptIds) .setExpand(expandOptions.get("expand", Options.class)) .setLocales(locales()) .build() .execute(context()); final ListMultimap<String, SnomedRelationship> inboundRelationshipsByConceptId = Multimaps.index(inboundRelationships, inboundRelationship -> inboundRelationship.getDestinationId()); for (SnomedConcept concept : results) { final List<SnomedRelationship> conceptInboundRelationships = inboundRelationshipsByConceptId.get(concept.getId()); concept.setInboundRelationships(new SnomedRelationships(conceptInboundRelationships, null, null, conceptInboundRelationships.size(), conceptInboundRelationships.size())); } }
Source:
protected void handleEvent(PullRequestEvent event) { if (settingsService.getSettings(event.getPullRequest().getToRef() .getRepository()) == null) { return; } String strRef = event.getPullRequest().getFromRef().toString().split(":", 2)[1]; String strSha1 = event.getPullRequest().getFromRef().getLatestChangeset(); EventContext context = new EventContext(event, event.getPullRequest().getToRef().getRepository(), event.getUser().getName()); if (filterChain.shouldDeliverNotification(context)) notifier.notifyBackground(context.getRepository(), strRef, strSha1); }

Target:
protected void handleEvent(PullRequestEvent event) { }
Source:
public CosemDateTimeDto getDaylightSavingsEnd() { return new CosemDateTimeDto(this.daylightSavingsEnd); }

Target:
public CosemDateTimeDto getDaylightSavingsEnd() { return this.daylightSavingsEnd; }
Source:
public void VideosPageTest_002() { SpecialVideosPageObject specialVideos = new SpecialVideosPageObject(driver); YoutubeVideo video = YoutubeVideoProvider.getLatestVideoForQuery(VIDEO_QUERY); specialVideos.addVideoViaAjax(video.getUrl()); specialVideos.isNewVideoAdded(); ADDED_VIDEO_TITLE = specialVideos.getNewestVideoTitle(); specialVideos.deleteNewestVideo(); Assertion.assertTrue(specialVideos.getBannerNotifications().isNotificationMessageVisible(), "Banner notification is not visible"); Assertion.assertTrue(specialVideos.getBannerNotificationText().contains(ADDED_VIDEO_TITLE), "Banner notification text doesn't contains video title"); }

Target:
public void VideosPageTest_002() { SpecialVideosPageObject specialVideos = new SpecialVideosPageObject(driver); YoutubeVideo video = YoutubeVideoProvider.getLatestVideoForQuery(VIDEO_QUERY); specialVideos.addVideoViaAjax(video.getUrl()); specialVideos.isNewVideoAdded(); String addedVideoTitle = specialVideos.getNewestVideoTitle(); specialVideos.deleteNewestVideo(); Assertion.assertTrue(specialVideos.getBannerNotifications().isNotificationMessageVisible(), "Banner notification is not visible"); Assertion.assertTrue(specialVideos.getBannerNotificationText().contains(addedVideoTitle), "Banner notification text doesn't contains video title"); }
Source:
private static FileAppender getFileAppender() { Enumeration e = LogManager.getRootLogger().getAllAppenders(); FileAppender fileAppender = null; while (e.hasMoreElements()) { Appender appender = (Appender)e.nextElement(); if (appender instanceof FileAppender) { if (fileAppender == null) { fileAppender = (FileAppender)appender; } else { return null; } } } return fileAppender; }

Target:
private static FileAppender getFileAppender() { Enumeration<Appender> e = LogManager.getRootLogger().getAllAppenders(); FileAppender fileAppender = null; while (e.hasMoreElements()) { Appender appender = e.nextElement(); if (appender instanceof FileAppender) { if (fileAppender == null) { fileAppender = (FileAppender)appender; } else { return null; } } } return fileAppender; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { RevCommit commit = getSelectedItem(RevCommit.class, event); if (commit == null) return null; Repository repo = getSelectedItem(Repository.class, event); if (repo == null) return null; Shell shell = getPart(event).getSite().getShell(); String newMessage = promptCommitMessage(shell, commit); if (newMessage == null) return null; final RewordCommitOperation op = new RewordCommitOperation(repo, commit, newMessage); Job job = new Job(MessageFormat.format(UIText.RewordHandler_JobName, commit.name())) { @Override protected IStatus run(IProgressMonitor monitor) { try { op.execute(monitor); } catch (CoreException e) { Activator.logError(UIText.RewordHandler_InternalError, e); } return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { if (JobFamilies.CHERRY_PICK.equals(family)) return true; return super.belongsTo(family); } }; job.setUser(true); job.setRule(op.getSchedulingRule()); job.schedule(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RevCommit commit = getSelectedItem(RevCommit.class, event); if (commit == null) return null; Repository repo = getSelectedItem(Repository.class, event); if (repo == null) return null; Shell shell = getPart(event).getSite().getShell(); String newMessage = promptCommitMessage(shell, commit); if (newMessage == null) return null; final RewordCommitOperation op = new RewordCommitOperation(repo, commit, newMessage); Job job = new WorkspaceJob(MessageFormat.format( UIText.RewordHandler_JobName, commit.name())) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) { try { op.execute(monitor); } catch (CoreException e) { Activator.logError(UIText.RewordHandler_InternalError, e); } return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { if (JobFamilies.REWORD.equals(family)) return true; return super.belongsTo(family); } }; job.setUser(true); job.setRule(op.getSchedulingRule()); job.schedule(); return null; }
Source:
public boolean isTrue(State state, String[] params) { if (this.subgoal == null) { return false; } if (this.subgoal.getGoal().getClassName().equals(AffordanceCreator.CONTAINERGREASED_PF)) { if (!this.subgoal.goalCompleted(state)) { return true; } } for (BakingSubgoal precondition : this.subgoal.getPreconditions()) { if (precondition.getGoal().getClassName().equals(AffordanceCreator.CONTAINERGREASED_PF)) { if (!precondition.goalCompleted(state)) { return true; } } } return false; }

Target:
public boolean isTrue(State state, String[] params) { if (this.subgoal == null) { return false; } String subgoalClassName = this.subgoal.getGoal().getClassName(); if (subgoalClassName.equals(AffordanceCreator.CONTAINERGREASED_PF)) { if (!this.subgoal.goalCompleted(state)) { return true; } } List<BakingSubgoal> preconditions = this.subgoal.getPreconditions(); for (BakingSubgoal precondition : preconditions) { String preconditionClassName = precondition.getGoal().getClassName(); if (preconditionClassName.equals(AffordanceCreator.CONTAINERGREASED_PF)) { if (!precondition.goalCompleted(state)) { return true; } } } return false; }
Source:
public void restoreVersion(Node node, Node version) { Serializable versionableId = node.getId(); Serializable versionId = version.getId(); boolean excludeSpecialChildren = true; List<SimpleFragment> children = getChildren(versionableId, null, excludeSpecialChildren); for (SimpleFragment child : children.toArray(new SimpleFragment[children.size()])) { removePropertyNode(child); } session.flush(); Row overwriteRow = new Row(Model.HIER_TABLE_NAME, versionableId); SimpleFragment versionHier = version.getHierFragment(); for (String key : model.getFragmentKeysType(Model.HIER_TABLE_NAME).keySet()) { if (key.equals(Model.HIER_PARENT_KEY) || key.equals(Model.HIER_CHILD_NAME_KEY) || key.equals(Model.HIER_CHILD_POS_KEY) || key.equals(Model.HIER_CHILD_ISPROPERTY_KEY) || key.equals(Model.MAIN_PRIMARY_TYPE_KEY) || key.equals(Model.MAIN_CHECKED_IN_KEY) || key.equals(Model.MAIN_BASE_VERSION_KEY) || key.equals(Model.MAIN_IS_VERSION_KEY)) { continue; } overwriteRow.putNew(key, versionHier.get(key)); } overwriteRow.putNew(Model.MAIN_CHECKED_IN_KEY, Boolean.TRUE); overwriteRow.putNew(Model.MAIN_BASE_VERSION_KEY, versionId); overwriteRow.putNew(Model.MAIN_IS_VERSION_KEY, null); CopyResult res = mapper.copy(new IdWithTypes(version), node.getParentId(), null, overwriteRow, excludeSpecialChildren); markInvalidated(res.invalidations); }

Target:
public void restoreVersion(Node node, Node version) { Serializable versionableId = node.getId(); Serializable versionId = version.getId(); List<SimpleFragment> children = getChildren(versionableId, null, true); for (SimpleFragment child : children.toArray(new SimpleFragment[children.size()])) { removePropertyNode(child); } session.flush(); Row overwriteRow = new Row(Model.HIER_TABLE_NAME, versionableId); SimpleFragment versionHier = version.getHierFragment(); for (String key : model.getFragmentKeysType(Model.HIER_TABLE_NAME).keySet()) { if (key.equals(Model.HIER_PARENT_KEY) || key.equals(Model.HIER_CHILD_NAME_KEY) || key.equals(Model.HIER_CHILD_POS_KEY) || key.equals(Model.HIER_CHILD_ISPROPERTY_KEY) || key.equals(Model.MAIN_PRIMARY_TYPE_KEY) || key.equals(Model.MAIN_CHECKED_IN_KEY) || key.equals(Model.MAIN_BASE_VERSION_KEY) || key.equals(Model.MAIN_IS_VERSION_KEY)) { continue; } overwriteRow.putNew(key, versionHier.get(key)); } overwriteRow.putNew(Model.MAIN_CHECKED_IN_KEY, Boolean.TRUE); overwriteRow.putNew(Model.MAIN_BASE_VERSION_KEY, versionId); overwriteRow.putNew(Model.MAIN_IS_VERSION_KEY, null); boolean excludeSpecialChildren = true; CopyResult res = mapper.copy(new IdWithTypes(version), node.getParentId(), null, overwriteRow, excludeSpecialChildren); markInvalidated(res.invalidations); }
Source:
private List<Iterator<Entry<KeyType>>> parallelSortAndGetGroupersIterator() { final List<ListenableFuture<Iterator<Entry<KeyType>>>> futures = groupers .stream() .map(grouper -> grouperSorter.submit( new AbstractPrioritizedCallable<Iterator<Entry<KeyType>>>(priority) { @Override public Iterator<Entry<KeyType>> call() throws Exception { synchronized (grouper) { return grouper.iterator(true); } } } ) ).collect(Collectors.toList()); try { return Futures.allAsList(futures).get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }

Target:
private List<Iterator<Entry<KeyType>>> parallelSortAndGetGroupersIterator() { final ListenableFuture<List<Iterator<Entry<KeyType>>>> future = Futures.allAsList( groupers.stream() .map(grouper -> grouperSorter.submit( new AbstractPrioritizedCallable<Iterator<Entry<KeyType>>>(priority) { @Override public Iterator<Entry<KeyType>> call() throws Exception { return grouper.iterator(true); } } ) ) .collect(Collectors.toList()) ); try { final long timeout = queryTimeoutAt - System.currentTimeMillis(); return hasQueryTimeout ? future.get(timeout, TimeUnit.MILLISECONDS) : future.get(); } catch (InterruptedException | TimeoutException e) { future.cancel(true); throw new QueryInterruptedException(e); } catch (CancellationException e) { throw new QueryInterruptedException(e); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } }
Source:
protected void loadUrl() { if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); GutenbergWebViewAuthorizationData gutenbergWebViewAuthorizationData = bundle.getParcelable(ARG_GUTENBERG_WEB_VIEW_AUTH_DATA); String siteUrl = gutenbergWebViewAuthorizationData.getSiteUrl(); String urlToLoad = siteUrl + "/wp-admin/post-new.php"; boolean isSitePrivate = !gutenbergWebViewAuthorizationData.isWPCom(); String authenticationUrl = isSitePrivate ? siteUrl + "/wp-login.php" : WPCOM_LOGIN_URL; String userAgent = gutenbergWebViewAuthorizationData.getWordPressUserAgent(); mWebView.getSettings().setUserAgentString(userAgent); String username = gutenbergWebViewAuthorizationData.getWPComAccountUsername(); String password = gutenbergWebViewAuthorizationData.getWPComAccountPassword(); String token = gutenbergWebViewAuthorizationData.getWPComAccountToken(); mUserId = isSitePrivate ? gutenbergWebViewAuthorizationData.getSelfHostedSiteId() : gutenbergWebViewAuthorizationData.getWPComAccountUserId(); if (isSitePrivate && gutenbergWebViewAuthorizationData.isJetpackSsoEnabled()) { mIsJetpackSsoEnabled = true; mUrlToLoad = urlToLoad; mUserId = gutenbergWebViewAuthorizationData.getWPComAccountUserId(); loadAuthenticatedUrl(WPCOM_LOGIN_URL, "", username, password, token); return; } loadAuthenticatedUrl(authenticationUrl, urlToLoad, username, password, token); } }

Target:
protected void loadUrl() { if (getIntent() != null && getIntent().getExtras() != null) { Bundle bundle = getIntent().getExtras(); GutenbergWebViewAuthorizationData gutenbergWebViewAuthorizationData = bundle.getParcelable(ARG_GUTENBERG_WEB_VIEW_AUTH_DATA); String siteUrl = gutenbergWebViewAuthorizationData.getSiteUrl(); String urlToLoad = siteUrl + "/wp-admin/post-new.php"; boolean isSelfHosted = !gutenbergWebViewAuthorizationData.isWPCom(); String authenticationUrl = isSelfHosted ? siteUrl + "/wp-login.php" : WPCOM_LOGIN_URL; String userAgent = gutenbergWebViewAuthorizationData.getWordPressUserAgent(); mWebView.getSettings().setUserAgentString(userAgent); String username = gutenbergWebViewAuthorizationData.getWPComAccountUsername(); String password = gutenbergWebViewAuthorizationData.getWPComAccountPassword(); String token = gutenbergWebViewAuthorizationData.getWPComAccountToken(); mUserId = isSelfHosted ? gutenbergWebViewAuthorizationData.getSelfHostedSiteId() : gutenbergWebViewAuthorizationData.getWPComAccountUserId(); if (isSelfHosted && gutenbergWebViewAuthorizationData.isJetpackSsoEnabled()) { mIsJetpackSsoEnabled = true; mUrlToLoad = urlToLoad; mUserId = gutenbergWebViewAuthorizationData.getWPComAccountUserId(); loadAuthenticatedUrl(WPCOM_LOGIN_URL, "", username, password, token); return; } loadAuthenticatedUrl(authenticationUrl, urlToLoad, username, password, token); } }
Source:
public long downloadFile(File outFile, DropZone dropZone, String fileName) { if (outFile == null) { log.error("File download failed. File is required."); return -1; } if (fileName == null) { log.error("File download failed. No filename provided."); return -1; } long bytesTransferred = -1; try { FileOutputStream outputStream = new FileOutputStream(outFile); bytesTransferred = downloadFile(outputStream.getChannel(),dropZone,fileName); outputStream.close(); } catch (Exception e) { log.error("File download failed with error message: " + e.getMessage()); } return bytesTransferred; }

Target:
public long downloadFile(File outFile, DropZone dropZone, String fileName) { if (outFile == null) { log.error("File download failed. Valid output File object is required."); return -1; } if (fileName == null) { log.error("File download failed. No filename provided."); return -1; } long bytesTransferred = -1; try { FileOutputStream outputStream = new FileOutputStream(outFile); bytesTransferred = downloadFile(outputStream.getChannel(), dropZone, fileName); outputStream.close(); } catch (Exception e) { log.error("File download failed with error message: " + e.getMessage()); } return bytesTransferred; }
Source:
private void updatePolicyAwareAttributes() { sourcePolicyAwareAttributes = registeredPolicyInstanceProviders.stream() .map(pip -> pip.getApplicationPolicyInstance().getPointcut()) .flatMap(pointcut -> (pointcut instanceof AttributeAwarePointcut) ? ((AttributeAwarePointcut) pointcut).sourcePolicyAwareAttributes().stream() : Stream.empty()) .collect(toSet()); }

Target:
private synchronized void updatePolicyAwareAttributes() { sourcePolicyAwareAttributes = registeredPolicyInstanceProviders.stream() .map(pip -> pip.getApplicationPolicyInstance().getPointcut()) .flatMap(pointcut -> (pointcut instanceof AttributeAwarePointcut) ? ((AttributeAwarePointcut) pointcut).sourcePolicyAwareAttributes().stream() : empty()) .collect(toSet()); }
Source:
public void cleanupBuffers() { testServerMap.values().forEach(x -> { x.getLogUnitServer().shutdown(); x.getManagementServer().shutdown(); x.getLayoutServer().shutdown(); x.getSequencerServer().shutdown(); x.getBaseServer().shutdown(); }); while (runtime.getObjectsView().TXActive()) { runtime.getObjectsView().TXAbort(); } runtimeRouterMap.keySet().forEach(CorfuRuntime::shutdown); runtimeRouterMap.clear(); testServerMap.clear(); }

Target:
public void cleanupBuffers() { testServerMap.values().forEach(server -> { server.getLogUnitServer().shutdown(); server.getManagementServer().shutdown(); server.getLayoutServer().shutdown(); server.getSequencerServer().shutdown(); server.getBaseServer().shutdown(); }); while (runtime.getObjectsView().TXActive()) { runtime.getObjectsView().TXAbort(); } runtimeRouterMap.keySet().forEach(CorfuRuntime::shutdown); runtimeRouterMap.clear(); testServerMap.clear(); }
Source:
public static void startJMXServer() { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); JMXServiceURL url = new JMXServiceURL("rmi", null, 0); JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); cs.start(); System.out.println("JMX url: " + cs.getAddress().toString()); } catch (Exception e) { System.out.println("Failed to start JMX server: " + e.getMessage()); } }

Target:
public static void startJMXServer() { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); JMXServiceURL url = new JMXServiceURL("rmi", null, 0); JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); cs.start(); LOG.info("JMX url: " + cs.getAddress().toString()); } catch (Exception e) { LOG.error("Failed to start JMX server: " + e.getMessage()); } }
Source:
public void add(double value, double weight, long count) { int bucketIndex = getIndexForValue(bucketCount, min, max, value); add(bucketIndex, weight, count); }

Target:
public void add(double value, double weight, long count) { int logicalBucketIndex = getIndexForValue(bucketCount, min, max, value); add(logicalBucketIndex, weight, count); }
Source:
private void itemSelected(int itemId) { switch (itemId) { case R.id.nav_albums: break; case R.id.nav_manage_accounts: startActivity(new Intent(getApplicationContext(), ManageAccountsActivity.class)); break; case R.id.nav_create_album: AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.Theme_Piwigo_AlertDialog); builder.setTitle("Create album"); final AppCompatEditText input = new AppCompatEditText(MainActivity.this); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setPositiveButton("OK", (dialog, which) -> createAlbum(input.getText().toString())); builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel()); builder.show(); break; case R.id.nav_upload: if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { Toast.makeText(this,R.string.storage_permission_explaination, Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); } } else { selectPhoto(); } break; case R.id.nav_about: startActivity(new Intent(getApplicationContext(), AboutActivity.class)); break; case R.id.nav_privacy: startActivity(new Intent(getApplicationContext(), PrivacyPolicyActivity.class)); break; default: Toast.makeText(this,"not yet implemented",Toast.LENGTH_LONG).show(); break; } }

Target:
private void itemSelected(int itemId) { switch (itemId) { case R.id.nav_albums: break; case R.id.nav_manage_accounts: startActivity(new Intent(getApplicationContext(), ManageAccountsActivity.class)); break; case R.id.nav_create_album: AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.Theme_Piwigo_AlertDialog); builder.setTitle(R.string.create_album_title); final AppCompatEditText input = new AppCompatEditText(MainActivity.this); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setPositiveButton(R.string.button_ok, (dialog, which) -> createAlbum(input.getText().toString())); builder.setNegativeButton(R.string.button_cancel, (dialog, which) -> dialog.cancel()); builder.show(); break; case R.id.nav_upload: if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { Toast.makeText(this,R.string.storage_permission_explaination, Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); } } else { selectPhoto(); } break; case R.id.nav_about: startActivity(new Intent(getApplicationContext(), AboutActivity.class)); break; case R.id.nav_privacy: startActivity(new Intent(getApplicationContext(), PrivacyPolicyActivity.class)); break; default: Toast.makeText(this,"not yet implemented",Toast.LENGTH_LONG).show(); break; } }
Source:
private static void setHashtagConnectionPool(HostSupplier hostSupplier, ConnectionPoolConfigurationImpl config) { List<Host> hosts = (List<Host>) hostSupplier.getHosts(); Collections.sort(hosts); TokenMapSupplier tokenMapSupplier = config.getTokenSupplier(); List<HostToken> hostTokens; if (tokenMapSupplier != null) { Set<Host> hostSet = new HashSet<Host>(hosts); hostTokens = tokenMapSupplier.getTokens(hostSet); if (hostTokens.isEmpty()) { throw new DynoConnectException("No hosts in the TokenMapSupplier"); } } else { throw new DynoConnectException("TokenMapSupplier not provided"); } String hashtag = hostTokens.get(0).getHost().getHashtag(); short numHosts = 0; for (HostToken hToken : hostTokens) { String hashtagNew = hToken.getHost().getHashtag(); if (hashtag != null && !hashtag.equals(hashtagNew)) { logger.error("Hashtag mismatch across hosts"); throw new RuntimeException("Hashtags are different across hosts"); } else if (numHosts > 0 && hashtag == null && hashtagNew != null) { logger.error("Hashtag mismatch across hosts"); throw new RuntimeException("Hashtags are different across hosts"); } hashtag = hashtagNew; numHosts++; } if (hashtag != null) { config.withHashtag(hashtag); } }

Target:
private static void setHashtagConnectionPool(HostSupplier hostSupplier, ConnectionPoolConfigurationImpl config) { List<Host> hosts = (List<Host>) hostSupplier.getHosts(); Collections.sort(hosts); TokenMapSupplier tokenMapSupplier = config.getTokenSupplier(); List<HostToken> hostTokens; if (tokenMapSupplier != null) { Set<Host> hostSet = new HashSet<Host>(hosts); hostTokens = tokenMapSupplier.getTokens(hostSet); if (hostTokens.isEmpty()) { throw new DynoConnectException("No hosts in the TokenMapSupplier"); } } else { throw new DynoConnectException("TokenMapSupplier not provided"); } String hashtag = hostTokens.get(0).getHost().getHashtag(); Stream<String> htStream = hostTokens.stream().map(hostToken -> hostToken.getHost().getHashtag()); if (hashtag == null) { htStream.filter(ht -> ht != null).findAny().ifPresent(ignore -> { logger.error("Hashtag mismatch across hosts"); throw new RuntimeException("Hashtags are different across hosts"); }); } else { htStream.filter(ht -> !hashtag.equals(ht)).findAny().ifPresent(ignore -> { logger.error("Hashtag mismatch across hosts"); throw new RuntimeException("Hashtags are different across hosts"); }); } if (hashtag != null) { config.withHashtag(hashtag); } }
Source:
public static String decodeURIComponent(String s, boolean plus) { if (s == null) { return null; } final int size = s.length(); boolean modified = false; int i; for (i = 0; i < size; i++) { final char c = s.charAt(i); if (c == '%' || (plus && c == '+')) { modified = true; break; } } if (!modified) { return s; } final byte[] buf = s.getBytes(); int pos = i; for (; i < size; i++) { char c = s.charAt(i); if (c == '%') { if (i == size - 1) { throw new IllegalArgumentException("unterminated escape" + " sequence at end of string: " + s); } c = s.charAt(++i); if (c == '%') { buf[pos++] = '%'; break; } if (i == size - 1) { throw new IllegalArgumentException("partial escape" + " sequence at end of string: " + s); } c = decodeHexNibble(c); final char c2 = decodeHexNibble(s.charAt(++i)); if (c == Character.MAX_VALUE || c2 == Character.MAX_VALUE) { throw new IllegalArgumentException( "invalid escape sequence `%" + s.charAt(i - 1) + s.charAt(i) + "' at index " + (i - 2) + " of: " + s); } c = (char) (c * 16 + c2); buf[pos++] = (byte) c; } else { buf[pos++] = (byte) (plus && c == '+' ? ' ' : c); } } return new String(buf, 0, pos, CharsetUtil.UTF_8); }

Target:
public static String decodeURIComponent(String s, boolean plus) { if (s == null) { return null; } final int size = s.length(); boolean modified = false; int i; for (i = 0; i < size; i++) { final char c = s.charAt(i); if (c == '%' || (plus && c == '+')) { modified = true; break; } } if (!modified) { return s; } final byte[] buf = s.getBytes(StandardCharsets.UTF_8); int pos = i; for (; i < size; i++) { char c = s.charAt(i); if (c == '%') { if (i == size - 1) { throw new IllegalArgumentException("unterminated escape" + " sequence at end of string: " + s); } c = s.charAt(++i); if (c == '%') { buf[pos++] = '%'; break; } if (i >= size - 1) { throw new IllegalArgumentException("partial escape" + " sequence at end of string: " + s); } c = decodeHexNibble(c); final char c2 = decodeHexNibble(s.charAt(++i)); if (c == Character.MAX_VALUE || c2 == Character.MAX_VALUE) { throw new IllegalArgumentException( "invalid escape sequence `%" + s.charAt(i - 1) + s.charAt(i) + "' at index " + (i - 2) + " of: " + s); } c = (char) (c * 16 + c2); buf[pos++] = (byte) c; } else { buf[pos++] = (byte) (plus && c == '+' ? ' ' : c); } } return new String(buf, 0, pos, StandardCharsets.UTF_8); }
Source:
protected List<EAccessLevel> resolveList(List<?> list) { List<EAccessLevel> ret = new ArrayList<>(); for (Object elem : (Collection<?>) list) { ret.add(EAccessLevel.getAccessLevel(elem.toString()).get()); } return Collections.unmodifiableList(ret); }

Target:
protected List<EAccessLevel> resolveList(List<?> list) { List<EAccessLevel> ret = new ArrayList<>(); Optional<EAccessLevel> eAccessLevel; for (Object elem : (Collection<?>) list) { eAccessLevel = EAccessLevel.getAccessLevel(elem.toString()); if (eAccessLevel.isPresent()) { ret.add(eAccessLevel.get()); } } return Collections.unmodifiableList(ret); }
Source:
private void setTTLAllPartitionsAndWaitForCompletion(List<Data>[] keysPerPartition, Data expiryPolicy) { List<Future> futures = new ArrayList<Future>(keysPerPartition.length); for (int partitionId = 0; partitionId < keysPerPartition.length; partitionId++) { List<Data> keys = keysPerPartition[partitionId]; if (keys != null) { Operation operation = operationProvider.createSetExpiryPolicyOperation(keys, expiryPolicy); futures.add(invoke(operation, partitionId, true)); } } Throwable error = null; for (Future future: futures) { try { future.get(); } catch (Throwable t) { logger.finest("Error occured while batch operation!", t); if (error == null) { error = t; } } } if (error != null) { throw rethrow(error); } }

Target:
private void setTTLAllPartitionsAndWaitForCompletion(List<Data>[] keysPerPartition, Data expiryPolicy) { List<Future> futures = new ArrayList<Future>(keysPerPartition.length); for (int partitionId = 0; partitionId < keysPerPartition.length; partitionId++) { List<Data> keys = keysPerPartition[partitionId]; if (keys != null) { Operation operation = operationProvider.createSetExpiryPolicyOperation(keys, expiryPolicy); futures.add(invoke(operation, partitionId, true)); } } List<Throwable> throwables = FutureUtil.waitUntilAllResponded(futures); if (throwables.size() > 0) { throw rethrow(throwables.get(0)); } }
Source:
@Override public void load(Request request, int networkPolicy, Callback callback) { if (assetManager == null) { synchronized (lock) { if (assetManager == null) { assetManager = context.getAssets(); } } } try { Source source = Okio.source(assetManager.open(getFilePath(request))); callback.onSuccess(new Result(source, DISK)); } catch (Exception e) { callback.onError(e); } }

Target:
@Override public void load(Request request, int networkPolicy, Callback callback) { if (assetManager == null) { synchronized (lock) { if (assetManager == null) { assetManager = context.getAssets(); } } } boolean signaledCallback = false; try { Source source = Okio.source(assetManager.open(getFilePath(request))); signaledCallback = true; callback.onSuccess(new Result(source, DISK)); } catch (Exception e) { if (!signaledCallback) { callback.onError(e); } } }
Source:
public static void writeDSFID(DataSerializableFixedID o, DataOutput out) throws IOException { int dsfid = o.getDSFID(); try { if (dsfid != DataSerializableFixedID.NO_FIXED_ID) { dsfidSerializer.write(o, out); return; } out.writeByte(DSCODE.DS_NO_FIXED_ID.toByte()); DataSerializer.writeClass(o.getClass(), out); invokeToData(o, out); } catch (IOException | CancelException | ToDataException | GemFireRethrowable io) { throw io; } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); throw err; } catch (Throwable t) { SystemFailure.checkFailure(); t.printStackTrace(); throw new ToDataException("toData failed on dsfid=" + dsfid + " msg:" + t.getMessage(), t); } }

Target:
public static void writeDSFID(DataSerializableFixedID o, DataOutput out) throws IOException { int dsfid = o.getDSFID(); try { if (dsfid != DataSerializableFixedID.NO_FIXED_ID) { dsfidSerializer.write(o, out); return; } out.writeByte(DSCODE.DS_NO_FIXED_ID.toByte()); DataSerializer.writeClass(o.getClass(), out); invokeToData(o, out); } catch (IOException | CancelException | ToDataException | GemFireRethrowable io) { throw io; } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); throw err; } catch (Throwable t) { SystemFailure.checkFailure(); throw new ToDataException("toData failed on dsfid=" + dsfid + " msg:" + t.getMessage(), t); } }
Source:
public void open(final ProjectDiagram diagram) { final Graph<?, Node<org.kie.workbench.common.stunner.core.graph.content.view.View, ?>> graph = diagram.getGraph(); this.layoutHelper.applyLayout(diagram.getGraph()); final Optional<Node<org.kie.workbench.common.stunner.core.graph.content.view.View, ?>> dd = StreamSupport.stream(graph.nodes().spliterator(), false) .filter(n -> n.getContent().getDefinition() instanceof DMNDiagram) .findFirst(); if (dd.isPresent()) { dd.get().getContent().setBounds(BoundsImpl.build(0, 0, 0, 0)); } super.open(diagram); }

Target:
public void open(final ProjectDiagram diagram) { this.layoutHelper.applyLayout(diagram); super.open(diagram); }
Source:
public String toString() { String sb = String.valueOf(providerId) + " providerName:" + ((person != null) ? person.getNames() : ""); return "[Provider: providerId:" + sb + " ]"; }

Target:
public String toString() { String provider = String.valueOf(providerId) + " providerName:" + ((person != null) ? person.getNames() : ""); return "[Provider: providerId:" + provider + " ]"; }
Source:
public Image getImage(Object element) { if (element instanceof IConnectionProvider) { ConnectionProviderUI ui = UIExtensionManager .getConnectionProviderUI(((IConnectionProvider) element).getId()); if (ui != null) { if (images.containsKey(ui.getId())) return images.get(ui.getId()); images.put(ui.getId(), ui.getImageDescriptor().createImage()); return images.get(ui.getId()); } } return null; }

Target:
public Image getImage(Object element) { if (element instanceof IConnectionProvider) { ConnectionProviderUI ui = UIExtensionManager .getConnectionProviderUI(((IConnectionProvider) element).getId()); if (ui != null) { String id = ui.getId(); if (images.containsKey(id)) return images.get(id); images.put(id, ui.getImageDescriptor().createImage()); return images.get(id); } } return null; }
Source:
protected void setActionMessageParameters() { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RESUME); }

Target:
protected void setActionMessageParameters() { super.setActionMessageParameters(); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RESUME); }
Source:
public Response add(Step step) { validateParameters(step, "type", "status.state" , "description"); String id; if (step.isSetParentStep()) { validateParameters(step, "parentStep.id"); id = step.getParentStep().getId(); } else { id = jobId.toString(); } Response response = performCreate(VdcActionType.AddExternalStep, new AddExternalStepParameters(asGuid(id), step.getDescription(),StepMapper.map(StepEnum.fromValue(step.getType())), JobMapper.map(step.getStatus(), null)), new QueryIdResolver<Guid>(VdcQueryType.GetStepByStepId, IdQueryParameters.class)); Step createdStep = (Step)response.getEntity(); injectParent(createdStep); return response; }

Target:
public Response add(Step step) { validateParameters(step, "type", "status.state" , "description"); String id; if (step.isSetParentStep()) { validateParameters(step, "parentStep.id"); id = step.getParentStep().getId(); } else { id = jobId.toString(); } return performCreate(VdcActionType.AddExternalStep, new AddExternalStepParameters(asGuid(id), step.getDescription(),StepMapper.map(StepEnum.fromValue(step.getType())), JobMapper.map(step.getStatus(), null)), new QueryIdResolver<Guid>(VdcQueryType.GetStepByStepId, IdQueryParameters.class)); }
Source:
private boolean containsJavaSource(MavenProject proj) { File javaSourceDir = new File(proj.getBasedir(), "src/main/java"); if (javaSourceDir.exists() && javaSourceDir.isDirectory() && javaSourceDir.listFiles().length > 0) { return true; } else { return false; } }

Target:
private boolean containsJavaSource(MavenProject proj) { @SuppressWarnings("unchecked") List<String> srcDirs = proj.getCompileSourceRoots(); for (String dir : srcDirs) { File javaSourceDir = new File(dir); if (javaSourceDir.exists() && javaSourceDir.isDirectory() && containsJavaSource(javaSourceDir)) { return true; } } return false; }
Source:
public void removeProcessTest() throws Exception { if (SystemUtils.IS_OS_LINUX) { File scriptCreateDirMeta = new File(ConfigCore.getParameter("script_createDirMeta")); File scriptCreateDirUserHome = new File(ConfigCore.getParameter("script_createDirUserHome")); ExecutionPermission.setExecutePermission(scriptCreateDirMeta); ExecutionPermission.setExecutePermission(scriptCreateDirUserHome); } int numberOfProcessesDisplayed = Pages.getProcessesPage().countListedProcesses(); Assert.assertTrue("Process list is empty", numberOfProcessesDisplayed > 0); Pages.getProcessesPage().deleteFirstProcess(); Assert.assertTrue("Removal of first process was not successful!", Pages.getProcessesPage().countListedProcesses() < numberOfProcessesDisplayed); if (SystemUtils.IS_OS_LINUX) { File scriptCreateDirMeta = new File(ConfigCore.getParameter("script_createDirMeta")); File scriptCreateDirUserHome = new File(ConfigCore.getParameter("script_createDirUserHome")); ExecutionPermission.setNoExecutePermission(scriptCreateDirMeta); ExecutionPermission.setNoExecutePermission(scriptCreateDirUserHome); } }

Target:
public void removeProcessTest() throws Exception { if (SystemUtils.IS_OS_LINUX) { File scriptCreateDirMeta = new File(ConfigCore.getParameter("script_createDirMeta")); File scriptCreateDirUserHome = new File(ConfigCore.getParameter("script_createDirUserHome")); ExecutionPermission.setExecutePermission(scriptCreateDirMeta); ExecutionPermission.setExecutePermission(scriptCreateDirUserHome); } ProcessesPage processesPage = Pages.getProcessesPage(); int numberOfProcessesDisplayed = processesPage.countListedProcesses(); Assert.assertTrue("Process list is empty", processesPage.isResultSetNotEmpty(processesPage.getListOfProcessTitles())); Pages.getProcessesPage().deleteFirstProcess(); Assert.assertTrue("Removal of first process was not successful!", processesPage.countListedProcesses() < numberOfProcessesDisplayed); if (SystemUtils.IS_OS_LINUX) { File scriptCreateDirMeta = new File(ConfigCore.getParameter("script_createDirMeta")); File scriptCreateDirUserHome = new File(ConfigCore.getParameter("script_createDirUserHome")); ExecutionPermission.setNoExecutePermission(scriptCreateDirMeta); ExecutionPermission.setNoExecutePermission(scriptCreateDirUserHome); } }
Source:
public void payloadExpressionEvaluatedAgainstApplicationEvent() { QueueChannel channel = new QueueChannel(); ApplicationEventListeningMessageProducer adapter = new ApplicationEventListeningMessageProducer(); adapter.setPayloadExpression("'received: ' + source"); adapter.setOutputChannel(channel); GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); beanFactory.registerSingleton(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, new SimpleApplicationEventMulticaster(beanFactory)); adapter.setBeanFactory(beanFactory); beanFactory.registerSingleton("testListenerMessageProducer", adapter); adapter.afterPropertiesSet(); ctx.refresh(); Message<?> message1 = channel.receive(0); assertNotNull(message1); assertTrue(message1.getPayload().toString() .contains("org.springframework.integration.test.util.TestUtils$TestApplicationContext")); adapter.onApplicationEvent(new TestApplicationEvent1()); adapter.onApplicationEvent(new TestApplicationEvent2()); Message<?> message2 = channel.receive(20); assertNotNull(message2); Message<?> message3 = channel.receive(20); assertNotNull(message3); assertEquals("received: event2", message3.getPayload()); }

Target:
public void payloadExpressionEvaluatedAgainstApplicationEvent() { QueueChannel channel = new QueueChannel(); ApplicationEventListeningMessageProducer adapter = new ApplicationEventListeningMessageProducer(); adapter.setPayloadExpression("'received: ' + source"); adapter.setOutputChannel(channel); GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); beanFactory.registerSingleton(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, new SimpleApplicationEventMulticaster(beanFactory)); adapter.setBeanFactory(beanFactory); beanFactory.registerSingleton("testListenerMessageProducer", adapter); adapter.afterPropertiesSet(); ctx.refresh(); Message<?> message1 = channel.receive(0); assertNotNull(message1); assertTrue(message1.getPayload().toString() .contains("org.springframework.integration.test.util.TestUtils$TestApplicationContext")); adapter.onApplicationEvent(new TestApplicationEvent1()); adapter.onApplicationEvent(new TestApplicationEvent2()); Message<?> message2 = channel.receive(20); assertNotNull(message2); assertEquals("received: event1", message2.getPayload()); Message<?> message3 = channel.receive(20); assertNotNull(message3); assertEquals("received: event2", message3.getPayload()); }
Source:
public void cancel_shouldRemovePendingIntentForBroadcast() { Intent intent = new Intent(); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 99, intent, 100); assertNotNull(pendingIntent); pendingIntent.cancel(); assertThat(PendingIntent.getBroadcast(context, 99, intent, FLAG_NO_CREATE)).isNull(); }

Target:
public void cancel_shouldRemovePendingIntentForBroadcast() { Intent intent = new Intent(); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 99, intent, 100); assertThat(pendingIntent).isNotNull(); pendingIntent.cancel(); assertThat(PendingIntent.getBroadcast(context, 99, intent, FLAG_NO_CREATE)).isNull(); }
Source:
public CoordinationUtils getCoordinationService(String groupId, String participantId, Config config) { ZkConfig zkConfig = new ZkConfig(config); ZkClient zkClient = createZkClient(zkConfig.getZkConnect(), zkConfig.getZkSessionTimeoutMs(), zkConfig.getZkConnectionTimeoutMs()); ZkJobCoordinatorMetrics zkJobCoordinatorMetrics = getJobCoordinatorMetrics(config, participantId); ZkUtils zkUtils = new ZkUtils(new ZkKeyBuilder(groupId), zkClient, zkConfig.getZkConnectionTimeoutMs(), zkJobCoordinatorMetrics); return new ZkCoordinationUtils(participantId, zkConfig, zkUtils); }

Target:
public CoordinationUtils getCoordinationService(String groupId, String participantId, Config config) { ZkConfig zkConfig = new ZkConfig(config); ZkClient zkClient = createZkClient(zkConfig.getZkConnect(), zkConfig.getZkSessionTimeoutMs(), zkConfig.getZkConnectionTimeoutMs()); ZkUtils zkUtils = new ZkUtils(new ZkKeyBuilder(groupId), zkClient, zkConfig.getZkConnectionTimeoutMs(), new NoOpMetricsRegistry()); return new ZkCoordinationUtils(participantId, zkConfig, zkUtils); }
Source:
private void deleteDirOnExit(FileSystem fs, String target) throws Exception { Path path = new Path(target.replaceAll(".*://.*?(?=/)", "")); fs.deleteOnExit(path); info(path + " is scheduled to be deleted on exit."); }

Target:
private void deleteDirOnExit(FileSystem fs, String target) throws Exception { Path path = new Path(extractPathFromUrl(target)); fs.deleteOnExit(path); info(path + " is scheduled to be deleted on exit."); }
Source:
public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configurationContext) throws AxisFault { API api = getAPIFromSynapseConfig(request); if (api == null) { handleException(request.getRequestURI()); } else { String responseString; try { responseString = retrieveFromRegistry(api, request); if (responseString == null) { if (log.isDebugEnabled()) { log.debug("Generating swagger definition for: " + api.getName()); } JSONObject jsonDefinition = new JSONObject(new GenericApiObjectDefinition(api).getDefinitionMap()); responseString = jsonDefinition.toString(); } } catch (RegistryException e) { String errMsg = "Error occurred while retrieving swagger definition from registry"; log.error(errMsg, e); throw new AxisFault(errMsg, e); } updateResponse(response, responseString, SwaggerConstants.CONTENT_TYPE_JSON); } }

Target:
public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configurationContext) throws AxisFault { API api = getAPIFromSynapseConfig(request); if (api == null) { handleException(request.getRequestURI()); } else { String responseString; try { responseString = retrieveFromRegistry(api, request); if (responseString == null) { if (log.isDebugEnabled()) { log.debug("Generating swagger definition for: " + api.getName()); } JSONObject jsonDefinition = new JSONObject(new GenericApiObjectDefinition(api).getDefinitionMap()); responseString = jsonDefinition.toString(); } } catch (RegistryException e) { throw new AxisFault("Error occurred while retrieving swagger definition from registry", e); } updateResponse(response, responseString, SwaggerConstants.CONTENT_TYPE_JSON); } }
Source:
public void inject(final T instance, final CreationalContext<T> ctx, final BeanManagerImpl manager, final SlimAnnotatedType<T> type, final InjectionTarget<T> injectionTarget) { Beans.injectEEFields(resourceInjectionsHierarchy, instance, ctx); ResourceInjector.super.inject(instance, ctx, manager, type, injectionTarget); }

Target:
public void inject(final T instance, final CreationalContext<T> ctx, final BeanManagerImpl manager, final SlimAnnotatedType<T> type, final InjectionTarget<T> injectionTarget) { new InjectionContextImpl<T>(manager, injectionTarget, type, instance) { @Override public void proceed() { Beans.injectEEFields(resourceInjectionsHierarchy, instance, ctx); Beans.injectFieldsAndInitializers(instance, ctx, manager, getInjectableFields(), getInitializerMethods()); } }.run(); }
Source:
public String getHostNum() { return mHostNum; }

Target:
public Integer getHostNum() { return getHostNum(this.mPreferences); }
Source:
public static void inspectWithCustomRegex( String projectId, String textToInspect, String customRegexPattern) { try (DlpServiceClient dlp = DlpServiceClient.create()) { ProjectName project = ProjectName.of(projectId); ByteContentItem byteItem = ByteContentItem.newBuilder() .setType(BytesType.TEXT_UTF8) .setData(ByteString.copyFromUtf8(textToInspect)) .build(); ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build(); Regex regex = Regex.newBuilder().setPattern(customRegexPattern).build(); InfoType infoType = InfoType.newBuilder().setName("C_MRN").build(); CustomInfoType customInfoType = CustomInfoType.newBuilder().setInfoType(infoType).setRegex(regex).build(); InspectConfig config = InspectConfig.newBuilder() .addCustomInfoTypes(customInfoType) .setIncludeQuote(true) .setMinLikelihood(Likelihood.POSSIBLE) .build(); InspectContentRequest request = InspectContentRequest.newBuilder() .setParent(project.toString()) .setItem(item) .setInspectConfig(config) .build(); InspectContentResponse response = dlp.inspectContent(request); System.out.println("Findings: " + response.getResult().getFindingsCount()); for (Finding f : response.getResult().getFindingsList()) { System.out.println("\tQuote: " + f.getQuote()); System.out.println("\tInfo type: " + f.getInfoType().getName()); System.out.println("\tLikelihood: " + f.getLikelihood()); } } catch (Exception e) { System.out.println("Error during inspectString: \n" + e.toString()); } }

Target:
public static void inspectWithCustomRegex( String projectId, String textToInspect, String customRegexPattern) throws IOException { try (DlpServiceClient dlp = DlpServiceClient.create()) { ProjectName project = ProjectName.of(projectId); ByteContentItem byteItem = ByteContentItem.newBuilder() .setType(BytesType.TEXT_UTF8) .setData(ByteString.copyFromUtf8(textToInspect)) .build(); ContentItem item = ContentItem.newBuilder().setByteItem(byteItem).build(); Regex regex = Regex.newBuilder().setPattern(customRegexPattern).build(); InfoType infoType = InfoType.newBuilder().setName("C_MRN").build(); CustomInfoType customInfoType = CustomInfoType.newBuilder().setInfoType(infoType).setRegex(regex).build(); InspectConfig config = InspectConfig.newBuilder() .addCustomInfoTypes(customInfoType) .setIncludeQuote(true) .setMinLikelihood(Likelihood.POSSIBLE) .build(); InspectContentRequest request = InspectContentRequest.newBuilder() .setParent(project.toString()) .setItem(item) .setInspectConfig(config) .build(); InspectContentResponse response = dlp.inspectContent(request); System.out.println("Findings: " + response.getResult().getFindingsCount()); for (Finding f : response.getResult().getFindingsList()) { System.out.println("\tQuote: " + f.getQuote()); System.out.println("\tInfo type: " + f.getInfoType().getName()); System.out.println("\tLikelihood: " + f.getLikelihood()); } } }