auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void acceptsNonProperlyEncodedURL() { final String url = "<LINK_0>[foo/bar]/read?file=%5B%5D%28%29.txt"; final String result = "<LINK_0>%5Bfoo/bar%5D/read?file=%5B%5D%28%29.txt"; MatcherAssert.assertThat( new Href(url).toString(), Matchers.equalTo(result) ); }

Target:
public void acceptsNonProperlyEncodedURL() { MatcherAssert.assertThat( new Href("<LINK_0>[foo/bar]/read?file=%5B%5D%28%29.txt").toString(), Matchers.equalTo("<LINK_0>%5Bfoo/bar%5D/read?file=%5B%5D%28%29.txt") ); }
Source:
protected List<String> getInputTables() throws FalconException { List<String> tables = new ArrayList<String>(); try { JSONArray inputs = message.getJSONObject(ADFJsonConstants.ADF_REQUEST_ACTIVITY) .getJSONArray(ADFJsonConstants.ADF_REQUEST_INPUTS); for (int i = 0; i < inputs.length(); i++) { tables.add(inputs.getJSONObject(i).getString(ADFJsonConstants.ADF_REQUEST_NAME)); } } catch (JSONException e) { throw new FalconException("Error while parsing input tables in ADF request."); } return tables; }

Target:
protected List<String> getInputTables() throws FalconException { List<String> tables = new ArrayList<String>(); try { JSONArray inputs = message.getJSONObject(ADFJsonConstants.ADF_REQUEST_ACTIVITY) .getJSONArray(ADFJsonConstants.ADF_REQUEST_INPUTS); for (int i = 0; i < inputs.length(); i++) { tables.add(inputs.getJSONObject(i).getString(ADFJsonConstants.ADF_REQUEST_NAME)); } } catch (JSONException e) { throw new FalconException("Error while reading input table names in ADF request."); } return tables; }
Source:
public void update(Operator operator) { List<OperatorEntity> entities = datastore.findAllObjectsByFilter(OperatorEntity.class, Filter.where("name").is(operator.name).limit(1)); if (!entities.isEmpty() && !entities.get(0).getId().equals(operator.id)) { throw new OperatorException("Operator with name: " + operator.name + " already exists."); } datastore.save(adapt(operator)); }

Target:
public void update(Operator operator) { Long count = datastore.entityCount(OperatorEntity.class, Filter.where("name").is(operator.name).and("_id").isNot(operator.id)); if (count != 0) { throw new OperatorException("Operator with name: " + operator.name + " already exists."); } datastore.save(adapt(operator)); }
Source:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { fViewInfo.setName(checkNotNull(TmfViewFactory.getBaseSecId(name))); } super.createPartControl(parent); }

Target:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { fViewInfo.setName(name); } super.createPartControl(parent); }
Source:
private void cacheResultEntry( ResultLevelCachePopulator resultLevelCachePopulator, T resultEntry, Function<T, Object> cacheFn ) { int cacheLimit = cacheConfig.getResultLevelCacheLimit(); if (cacheLimit > 0 && resultLevelCachePopulator.cacheObjectStream.size() > cacheLimit) { shouldPopulate = false; return; } try (JsonGenerator gen = mapper.getFactory().createGenerator(resultLevelCachePopulator.cacheObjectStream)) { gen.writeObject(cacheFn.apply(resultEntry)); } catch (IOException ex) { log.error("Failed to retrieve entry to be cached. Result Level caching will not be performed!"); shouldPopulate = false; } }

Target:
private void cacheResultEntry( ResultLevelCachePopulator resultLevelCachePopulator, T resultEntry, Function<T, Object> cacheFn ) { int cacheLimit = cacheConfig.getResultLevelCacheLimit(); try (JsonGenerator gen = mapper.getFactory().createGenerator(resultLevelCachePopulator.cacheObjectStream)) { gen.writeObject(cacheFn.apply(resultEntry)); if (cacheLimit > 0 && resultLevelCachePopulator.cacheObjectStream.size() > cacheLimit) { shouldPopulate = false; resultLevelCachePopulator.cacheObjectStream = null; return; } } catch (IOException ex) { log.error(ex, "Failed to retrieve entry to be cached. Result Level caching will not be performed!"); shouldPopulate = false; resultLevelCachePopulator.cacheObjectStream = null; } }
Source:
void verifyRawQueryBehaviorForInteger(@NonNull Integer actualNumberOfResults) { assertThat(actualNumberOfResults).isNotNull(); verify(storIOSQLite, times(1)).get(); verify(getResolverForNumberOfResults, times(1)).performGet(storIOSQLite, rawQuery); assertThat(actualNumberOfResults).isSameAs(numberOfResults); verify(cursor).close(); verifyNoMoreInteractions(storIOSQLite, internal, cursor); }

Target:
void verifyRawQueryBehaviorForInteger(@NonNull Integer actualNumberOfResults) { assertThat(actualNumberOfResults).isNotNull(); verify(storIOSQLite).get(); verify(getResolverForNumberOfResults).performGet(storIOSQLite, rawQuery); assertThat(actualNumberOfResults).isSameAs(numberOfResults); verify(cursor).close(); verifyNoMoreInteractions(storIOSQLite, internal, cursor); }
Source:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } finally { } }

Target:
public void close() { Closeables.closeQuietly(nettyConnectionPool); try { timer.stop(); } catch(Exception e) { } }
Source:
private void setSpinnerSelection(Spinner spinner) { if (isFormulaEnabled) { oldSelectedLook = look; spinner.setSelection(FORMULA_EDITOR_POSITION); return; } if (getSprite().getLookDataList().contains(look)) { oldSelectedLook = look; spinner.setSelection(getSprite().getLookDataList().indexOf(look) + 2, true); } else { if (spinner.getAdapter() != null && spinner.getAdapter().getCount() > 1) { if (getSprite().getLookDataList().indexOf(oldSelectedLook) >= 0) { spinner.setSelection(getSprite().getLookDataList() .indexOf(oldSelectedLook) + 2, true); } else { spinner.setSelection(FORMULA_EDITOR_POSITION + 1, true); } } else { spinner.setSelection(NEW_LOOK_POSITION, true); } } }

Target:
private void setSpinnerSelection(Spinner spinner) { if (isFormulaEnabled) { oldSelectedLook = look; spinner.setSelection(SPINNER_POSITION_FORMULA_EDITOR); return; } if (getSprite().getLookDataList().contains(look)) { oldSelectedLook = look; spinner.setSelection(getSprite().getLookDataList().indexOf(look) + 2, true); } else { if (spinner.getAdapter() != null && spinner.getAdapter().getCount() > 2) { if (getSprite().getLookDataList().indexOf(oldSelectedLook) >= 0) { spinner.setSelection(getSprite().getLookDataList() .indexOf(oldSelectedLook) + SPINNER_POSITION_FORMULA_EDITOR + 1, true); } else { spinner.setSelection(SPINNER_POSITION_FORMULA_EDITOR + 1, true); } } else { spinner.setSelection(SPINNER_POSITION_NEW_LOOK, true); } } }
Source:
public void init(ByteBuffer buf, int position) { buf.put(position, BYTE_FLAG_IS_NOT_SET); buf.putDouble(position + Byte.BYTES, NULL_VALUE); }

Target:
public void init(ByteBuffer buf, int position) { buf.put(position, BYTE_FLAG_IS_NOT_SET); buf.putDouble(position + Byte.BYTES, NullHandling.ZERO_DOUBLE); }
Source:
private boolean verifyChecksums(String originalFileChecksum, String replicatedFilePath) { String remoteChecksum = getFileChecksum(replicatedFilePath); if (originalFileChecksum.equals(remoteChecksum)) { log.info("Local and remote checksums match for {}", replicatedFilePath); return true; } else { throw new ReplicationException("Local and remote checksums did not match {}", originalFileChecksum, remoteChecksum); } }

Target:
private void verifyChecksums(String originalFileChecksum, String replicatedFilePath) { String remoteChecksum = getFileChecksum(replicatedFilePath); if (originalFileChecksum.equals(remoteChecksum)) { log.info("Local and remote checksums match for {}", replicatedFilePath); } else { String errorMsg = String.format("Local and remote checksums did not match %s %s", originalFileChecksum, remoteChecksum); throw new ReplicationException(errorMsg); } }
Source:
private double getHeight(final BaseGridRendererHelper.RenderingInformation renderingInformation) { double height = renderer.getHeaderHeight(); height = height + renderingInformation.getAllRowHeights().stream().reduce(0d, Double::sum); return height; }

Target:
private double getHeight(final BaseGridRendererHelper.RenderingInformation renderingInformation) { double height = renderer.getHeaderHeight(); for (double h : renderingInformation.getAllRowHeights()) { height = height + h; } return height; }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_editor_list, container, false); DroidPlannerApp app = ((DroidPlannerApp) getActivity().getApplication()); drone = app.getDrone(); missionProxy = app.missionProxy; adapter = new MissionItemProxyView(getActivity(), missionProxy.getItems()); if (savedInstanceState != null){ isInDeleteMode = savedInstanceState.getBoolean(DELETE_MODE_KEY); adapter.setDeleteModeEnabled(isInDeleteMode); } list = (HListView) view.findViewById(R.id.mission_item_list); list.setOnItemClickListener(this); list.setOnItemLongClickListener(this); list.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); list.setAdapter(adapter); leftArrow = (ImageButton) view.findViewById(R.id.listLeftArrow); rightArrow = (ImageButton) view.findViewById(R.id.listRightArrow); leftArrow.setOnClickListener(this); rightArrow.setOnClickListener(this); return view; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_editor_list, container, false); DroidPlannerApp app = ((DroidPlannerApp) getActivity().getApplication()); drone = app.getDrone(); missionProxy = app.missionProxy; adapter = new MissionItemProxyView(getActivity(), missionProxy.getItems()); list = (HListView) view.findViewById(R.id.mission_item_list); list.setOnItemClickListener(this); list.setOnItemLongClickListener(this); list.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); list.setAdapter(adapter); leftArrow = (ImageButton) view.findViewById(R.id.listLeftArrow); rightArrow = (ImageButton) view.findViewById(R.id.listRightArrow); leftArrow.setOnClickListener(this); rightArrow.setOnClickListener(this); return view; }
Source:
public void reelIn() { if (location.getBlock().getType() == Material.WATER) { if (getShooter() instanceof Player) { world.dropItemNaturally(((Player) getShooter()).getLocation(), getRewardItem()); ((Player) getShooter()).giveExp(ThreadLocalRandom.current().nextInt(1, 7)); } } remove(); }

Target:
public void reelIn() { if (location.getBlock().getType() == Material.WATER) { ProjectileSource shooter = getShooter(); if (shooter instanceof Player) { PlayerFishEvent fishEvent = new PlayerFishEvent((Player) shooter, this, null, CAUGHT_FISH); fishEvent.setExpToDrop(ThreadLocalRandom.current().nextInt(1, 7)); fishEvent = EventFactory.callEvent(fishEvent); if (!fishEvent.isCancelled()) { world.dropItemNaturally(((Player) getShooter()).getLocation(), getRewardItem()); ((Player) getShooter()).giveExp(fishEvent.getExpToDrop()); } } } remove(); }
Source:
public void setClientConfigs(List<ClientConfig> clientConfigs) { this.clientConfigs = clientConfigs; }

Target:
public ClientFailoverConfig setClientConfigs(List<ClientConfig> clientConfigs) { this.clientConfigs = clientConfigs; return this; }
Source:
private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { final boolean refreshSchema = (keyspace != null); executor.submit(new Runnable() { @Override public void run() { boolean schemaInAgreement = false; try { schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this); if (!schemaInAgreement) logger.warn("No schema agreement from live replicas after s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); if (refreshSchema) { submitSchemaRefresh(keyspace, table); Uninterruptibles.getUninterruptibly(schemaRefreshRequestDebouncer.deliverEvents()); if (table == null) { Uninterruptibles.getUninterruptibly(nodeListRefreshRequestDebouncer.deliverEvents()); } } } catch (Exception e) { if (refreshSchema) { logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage()); submitSchemaRefresh(keyspace, table); } else { logger.warn("Error while waiting for schema agreement", e); } } finally { rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); future.setResult(rs); } } }); }

Target:
private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) { final boolean refreshSchema = (keyspace != null); executor.submit(new Runnable() { @Override public void run() { boolean schemaInAgreement = false; try { schemaInAgreement = controlConnection.waitForSchemaAgreement(); if (!schemaInAgreement) logger.warn("No schema agreement from live replicas after s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(keyspace, table) : MoreFutures.VOID_SUCCESS; final boolean finalSchemaInAgreement = schemaInAgreement; schemaReady.addListener(new Runnable() { @Override public void run() { rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement); future.setResult(rs); } }, MoreExecutors.sameThreadExecutor()); } catch (Exception e) { logger.warn("Error while waiting for schema agreement", e); rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); future.setResult(rs); } } }); }
Source:
public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); if (networkInterface.getVnicProfileId() != null) { profileList.setSelectedItem(profiles.stream() .filter(profile -> Objects.equals(profile.getId(), networkInterface.getVnicProfileId())) .findAny() .orElse(VnicProfileView.EMPTY)); } else { profileList.setSelectedItem(VnicProfileView.EMPTY); } }

Target:
public void initSelectedProfile(ListModel<VnicProfileView> profileList, VmNetworkInterface networkInterface) { if (networkInterface.getVnicProfileId() != null) { Collection<VnicProfileView> profiles = Optional.ofNullable(profileList.getItems()).orElse(Collections.emptyList()); profileList.setSelectedItem(profiles.stream() .filter(profile -> Objects.equals(profile.getId(), networkInterface.getVnicProfileId())) .findAny() .orElse(VnicProfileView.EMPTY)); } else { profileList.setSelectedItem(VnicProfileView.EMPTY); } }
Source:
private static void restoreFromArchive(Configuration conf, String conglomId, String encodedRegionName) throws IOException{ Path region = getRegionPath(conf, conglomId, encodedRegionName); Path family = new Path(region, SIConstants.DEFAULT_FAMILY_NAME); Path regionArchive = getTmpPath(conf, conglomId, encodedRegionName); Path familyArchive = new Path(regionArchive, SIConstants.DEFAULT_FAMILY_NAME); FileSystem fs = region.getFileSystem(conf); if (fs.exists(familyArchive)) { FileStatus[] fileStatuses = fs.listStatus(familyArchive); for (FileStatus fileStatus : fileStatuses) { String name = fileStatus.getPath().getName(); Path src = fileStatus.getPath(); Path dest = new Path(family, name); SpliceLogUtils.info(LOG, "Move %s to %s", src.toString(), dest.toString()); fs.rename(src, dest); } fs.delete(familyArchive, true); } }

Target:
private static void restoreFromArchive(Configuration conf, String conglomId, String encodedRegionName) throws IOException{ Path region = getRegionPath(conf, conglomId, encodedRegionName); Path family = new Path(region, SIConstants.DEFAULT_FAMILY_NAME); Path regionArchive = getTmpPath(conf, conglomId, encodedRegionName); Path familyArchive = new Path(regionArchive, SIConstants.DEFAULT_FAMILY_NAME); FileSystem fs = region.getFileSystem(conf); if (fs.exists(familyArchive)) { FileStatus[] fileStatuses = fs.listStatus(familyArchive); for (FileStatus fileStatus : fileStatuses) { String name = fileStatus.getPath().getName(); Path src = fileStatus.getPath(); Path dest = new Path(family, name); if (fs.rename(src, dest)) { SpliceLogUtils.info(LOG, "Moved %s to %s", src.toString(), dest.toString()); } else { SpliceLogUtils.info(LOG, "Failed to move %s to %s", src.toString(), dest.toString()); } } if (!fs.delete(familyArchive, true)) { SpliceLogUtils.error(LOG, "Failed to remove %s", familyArchive.toString()); } } }
Source:
private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { if (this.currentFeature != currentFeature) { hadSuccess.set(false); abortions.clear(); failures.clear(); } this.currentFeature = currentFeature; return this; }

Target:
private SpockExecutionContext setCurrentFeature(FeatureInfo currentFeature) { this.currentFeature = currentFeature; return this; }
Source:
public Projection<T> project(int... fieldIndexes) { if(!(this.getType() instanceof TupleTypeInfo)) { throw new UnsupportedOperationException("project() can only be applied to DataSets of Tuples."); } if(fieldIndexes.length == 0) { throw new IllegalArgumentException("project() needs to select at least one (1) field."); } else if(fieldIndexes.length > 22) { throw new IllegalArgumentException("project() may to select at most twenty-two (22) fields."); } int maxFieldIndex = ((TupleTypeInfo<?>)this.getType()).getArity(); for(int i=0; i<fieldIndexes.length; i++) { if(fieldIndexes[i] > maxFieldIndex - 1) { throw new IndexOutOfBoundsException("Provided field index is out of bounds of input tuple."); } } return new Projection<T>(this, fieldIndexes); }

Target:
public Projection<T> project(int... fieldIndexes) { return new Projection<T>(this, fieldIndexes); }
Source:
public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> cir) { if (!this.isCubic) return; int blockX = pos.getX(); int blockY = pos.getY(); int blockZ = pos.getZ(); int cubeX = Coords.blockToCube(blockX) - originX; int cubeY = Coords.blockToCube(blockY) - originY; int cubeZ = Coords.blockToCube(blockZ) - originZ; if (cubeX < 0 || cubeX >= dx || cubeY < 0 || cubeY >= dy || cubeZ < 0 || cubeZ >= dz) { return; } Cube cube = this.cubes[cubeX][cubeY][cubeZ]; cir.setReturnValue(cube.getBiome(pos, this.world.getBiomeProvider())); cir.cancel(); }

Target:
public void getBiome(BlockPos pos, CallbackInfoReturnable<Biome> cir) { if (!this.isCubic()) return; Cube cube = this.getCube(pos); if (cube == null) cir.setReturnValue(Biomes.PLAINS); else cir.setReturnValue(cube.getBiome(pos)); cir.cancel(); }
Source:
public void setTitle(Session session) { StringBuilder strBuilder = new StringBuilder(); String sessionName = session == null ? "" : session.getSessionName(); strBuilder.append(sessionName).append(" - "); if (!session.isNewState()) { File file = new File(session.getFileName()); strBuilder.append(file.getName().replaceAll(".session\\z", "")).append(" - "); } strBuilder.append(Constant.PROGRAM_NAME).append(' ').append(Constant.PROGRAM_VERSION); super.setTitle(strBuilder.toString()); }

Target:
public void setTitle(Session session) { StringBuilder strBuilder = new StringBuilder(); if (session != null) { strBuilder.append(session.getSessionName()).append(" - "); if (!session.isNewState()) { File file = new File(session.getFileName()); strBuilder.append(file.getName().replaceAll(".session\\z", "")).append(" - "); } } strBuilder.append(Constant.PROGRAM_NAME).append(' ').append(Constant.PROGRAM_VERSION); super.setTitle(strBuilder.toString()); }
Source:
public MaildirMessageName getMessageNameByUid(final MailboxSession session, final MessageUid uid) throws MailboxException { return locker.executeWithLock(session, path, () -> { FileReader fileReader = null; BufferedReader reader = null; File uidList = uidFile; try { fileReader = new FileReader(uidList); reader = new BufferedReader(fileReader); String uidString = String.valueOf(uid.asLong()); String line = reader.readLine(); int lineNumber = 1; while ((line = reader.readLine()) != null) { if (!line.equals("")) { int gap = line.indexOf(" "); if (gap == -1) { LOGGER.info("Corrupted entry in uid-file line {}", uidList, lineNumber++); continue; } if (line.substring(0, gap).equals(uidString)) { return newMaildirMessageName(MaildirFolder.this, line.substring(gap + 1)); } } } return null; } catch (IOException e) { throw new MailboxException("Unable to read messagename for uid " + uid, e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(fileReader); } }, true); }

Target:
public MaildirMessageName getMessageNameByUid(final MailboxSession session, final MessageUid uid) throws MailboxException { return locker.executeWithLock(session, path, () -> { FileReader fileReader = null; BufferedReader reader = null; File uidList = uidFile; try { fileReader = new FileReader(uidList); reader = new BufferedReader(fileReader); String uidString = String.valueOf(uid.asLong()); String line = reader.readLine(); int lineNumber = 1; while ((line = reader.readLine()) != null) { lineNumber++; if (!line.equals("")) { int gap = line.indexOf(" "); if (gap == -1) { LOGGER.info("Corrupted entry in uid-file line {}", uidList, lineNumber); continue; } if (line.substring(0, gap).equals(uidString)) { return newMaildirMessageName(MaildirFolder.this, line.substring(gap + 1)); } } } return null; } catch (IOException e) { throw new MailboxException("Unable to read messagename for uid " + uid, e); } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(fileReader); } }, true); }
Source:
public ShareClient createShare(String shareName) { return createShare(shareName, null, null); }

Target:
public Response<ShareClient> createShare(String shareName) { return createShare(shareName, null, null); }
Source:
public void onEnter() { try { getContext().unregisterAuthorizationUpdates(); } catch (final RuntimeException ex) { getLog().error("Unexpected fail during removing callback for registration updates", ex); } try { if (null != exception) { getOut().onException(exception); } } finally { try { getContext().unregisterSession(); } finally { if (null != exception) { getContext().switchStateImmediately(StreamingContext.DEAD_STATE); } else{ switchState(StreamingContext.DEAD_STATE); } } try { getContext().getZkClient().close(); } catch (final IOException e) { getLog().error("Unexpected fail to release zk connection", e); } getContext().getCurrentSpan().finish(); } }

Target:
public void onEnter() { try { getContext().unregisterAuthorizationUpdates(); } catch (final RuntimeException ex) { getLog().error("Unexpected fail during removing callback for registration updates", ex); } try { if (null != exception) { getOut().onException(exception); } } finally { try { getContext().unregisterSession(); } finally { switchState(StreamingContext.DEAD_STATE); } try { getContext().getZkClient().close(); } catch (final IOException e) { getLog().error("Unexpected fail to release zk connection", e); } getContext().getCurrentSpan().finish(); } }
Source:
private void processErrorRequest(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response, Span spanFromRequest) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("The span was already detached once and we're processing an error"); } try { filterChain.doFilter(request, response); } finally { request.setAttribute(TRACE_ERROR_HANDLED_REQUEST_ATTR, true); this.tracer.close(spanFromRequest); } }

Target:
private void processErrorRequest(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response, Span spanFromRequest) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("The span [" + spanFromRequest + "] was already detached once and we're processing an error"); } try { filterChain.doFilter(request, response); } finally { request.setAttribute(TRACE_ERROR_HANDLED_REQUEST_ATTR, true); addResponseTags(response, null); this.tracer.close(spanFromRequest); } }
Source:
private <T> Bean<?> getBeanFrom(Class<T> type) { Set<Bean<?>> beans = beanManager.getBeans(type); logger.debug("beans for is {}", type, beans); if (beans.isEmpty()) return null; return beanManager.resolve(beans); }

Target:
private <T> Bean<?> getBeanFrom(Class<T> type) { type = (Class<T>) CDIProxies.extractRawType(type); logger.debug("asking cdi to get instance for {}", type); Set<Bean<?>> beans = beanManager.getBeans(type); logger.debug("beans for is {}", type, beans); if (beans.isEmpty()) { return null; } return beanManager.resolve(beans); }
Source:
public Binder<BindIn, Object> build(final BindIn bindIn) { return (q, param, index, bind, arg) -> { String name = bindIn.value(); if (name.isEmpty()) { if (param.isNamePresent()) { name = param.getName(); } else { throw new UnsupportedOperationException("A @BindIn parameter was not given a name, " + "and parameter name data is not present in the class file, for: " + param.getDeclaringExecutable() + " :: " + param); } } final String key = name; if (arg == null || Util.size(arg) == 0) { switch (bindIn.onEmpty()) { case VOID: break; case NULL: q.bind("__" + key + "_0", (String) null); break; case THROW: final Exception inner = new IllegalArgumentException("argument is null; null was explicitly forbidden on this instance of BindIn"); throw new IllegalStateException("Illegal argument value was caught too late. Please report this to the jdbi developers.", inner); default: throw new IllegalStateException(EmptyHandling.valueNotHandledMessage); } } else { Type parameterType = param == null ? Object.class : param.getParameterizedType(); Type elementType = findGenericParameter(parameterType, Iterable.class) .orElse(Object.class); final Iterator<?> it = Util.toIterator(arg); for (int i = 0; it.hasNext(); i++) { q.bindByType("__" + key + "_" + i, it.next(), elementType); } } }; }

Target:
public Binder<BindIn, Object> build(final BindIn bindIn) { return (q, param, index, bind, arg) -> { final String name = ParameterUtil.getParameterName(bindIn, bindIn.value(), param); if (arg == null || Util.size(arg) == 0) { switch (bindIn.onEmpty()) { case VOID: break; case NULL: q.bind("__" + name + "_0", (String) null); break; case THROW: final Exception inner = new IllegalArgumentException("argument is null; null was explicitly forbidden on this instance of BindIn"); throw new IllegalStateException("Illegal argument value was caught too late. Please report this to the jdbi developers.", inner); default: throw new IllegalStateException(EmptyHandling.valueNotHandledMessage); } } else { Type parameterType = param == null ? Object.class : param.getParameterizedType(); Type elementType = findGenericParameter(parameterType, Iterable.class) .orElse(Object.class); final Iterator<?> it = Util.toIterator(arg); for (int i = 0; it.hasNext(); i++) { q.bindByType("__" + name + "_" + i, it.next(), elementType); } } }; }
Source:
public <T> T getMojoParameterValue(final MavenProject project, final String parameter, final Class<T> type, final Plugin plugin, final ConfigurationContainer configuration, final String goal, IProgressMonitor monitor) throws CoreException { return context().execute(project, new ICallable<T>() { public T call(IMavenExecutionContext context, IProgressMonitor monitor) throws CoreException { return getMojoParameterValue(parameter, type, context.getSession(), plugin, configuration, goal); } }, monitor); }

Target:
public <T> T getMojoParameterValue(final MavenProject project, final String parameter, final Class<T> type, final Plugin plugin, final ConfigurationContainer configuration, final String goal, IProgressMonitor monitor) throws CoreException { return context().execute(project, (context, pm) -> getMojoParameterValue(parameter, type, context.getSession(), plugin, configuration, goal), monitor); }
Source:
private void recordValidTxns(HiveTxnManager txnMgr) throws LockException { String oldTxnString = conf.get(ValidTxnList.VALID_TXNS_KEY); if ((oldTxnString != null) && (oldTxnString.length() > 0)) { throw new IllegalStateException("calling recordValidTxn() more than once in the same " + JavaUtils.txnIdToString(txnMgr.getCurrentTxnId())); } ValidTxnList txnList = txnMgr.getValidTxns(); String txnStr = txnList.toString(); conf.set(ValidTxnList.VALID_TXNS_KEY, txnStr); LOG.info("Encoding valid txns info " + txnStr + " txnid:" + txnMgr.getCurrentTxnId()); }

Target:
private void recordValidTxns(HiveTxnManager txnMgr) throws LockException { String oldTxnString = conf.get(ValidTxnList.VALID_TXNS_KEY); if ((oldTxnString != null) && (oldTxnString.length() > 0)) { throw new IllegalStateException("calling recordValidTxn() more than once in the same " + JavaUtils.txnIdToString(txnMgr.getCurrentTxnId())); } ValidTxnList txnList = txnMgr.getValidTxns(); String txnStr = txnList.toString(); conf.set(ValidTxnList.VALID_TXNS_KEY, txnStr); LOG.debug("Encoding valid txns info " + txnStr + " txnid:" + txnMgr.getCurrentTxnId()); }
Source:
public void releaseStore(final Store<?, ?> resource) { ClusteredStore clusteredStore = (ClusteredStore)resource; this.clusteringService.releaseServerStoreProxy(clusteredStore.storeProxy); }

Target:
public void releaseStore(final Store<?, ?> resource) { if (createdStores.remove(resource) == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } ClusteredStore clusteredStore = (ClusteredStore)resource; this.clusteringService.releaseServerStoreProxy(clusteredStore.storeProxy); }
Source:
private void setSelectedNetworkQoSId(Guid networkQoSId) { for (Object item : getNetworkQoS().getItems()) { if (((NetworkQoS) item).getId().equals(networkQoSId)) { getNetworkQoS().setSelectedItem(item); return; } } setSelectedNetworkQoSId(Guid.Empty); }

Target:
private void setSelectedNetworkQoSId(Guid networkQoSId) { for (Object item : getNetworkQoS().getItems()) { if (((NetworkQoS) item).getId().equals(networkQoSId)) { getNetworkQoS().setSelectedItem(item); return; } } getNetworkQoS().setSelectedItem(getEmptyQos()); }
Source:
String getKey() { return keySet.get(random.nextInt(keySet.size())); }

Target:
protected String getKey() { return keySet.get(random.nextInt(keySet.size())); }
Source:
public void initialize(ResourceManager nerRm) { if (ViewNames.NER_ONTONOTES.equals(getViewName())) nerRm = new NerOntonotesConfigurator().getConfig(nerRm); else nerRm = new NerBaseConfigurator().getConfig(nerRm); ParametersForLbjCode.currentParameters.forceNewSentenceOnLineBreaks = false; Parameters.readConfigAndLoadExternalData(nerRm); String dataset; if(viewName.toLowerCase().contains("conll")) { dataset = "enron-conll"; } else { dataset = "ontonotes"; } String data_split = nerRm.getString(NerBaseConfigurator.TRAINED_ON); try { Datastore ds = new Datastore(new ResourceConfigurator().getDefaultConfig()); String artifact_id = "ner-model-" + dataset + "-" + data_split; File modelDir = ds.getDirectory("edu.illinois.cs.cogcomp.ner", artifact_id, 4.0, false); String model = ""; if(modelDir.getPath().contains("conll")) { model = modelDir.getPath() + "/model/EnronCoNLL.model"; } else { model = modelDir.getPath() + "/model/OntoNotes.model"; } NETaggerLevel1 tagger1 = new NETaggerLevel1(model + ".level1", model + ".level1.lex"); NETaggerLevel2 tagger2 = null; if (ParametersForLbjCode.currentParameters.featuresToUse.containsKey("PredictionsLevel1")) { tagger2 = new NETaggerLevel2(model + ".level2", model + ".level2.lex"); } this.t1 = tagger1; this.t2 = tagger2; } catch (InvalidPortException | DatastoreException | InvalidEndpointException e) { e.printStackTrace(); } }

Target:
public void initialize(ResourceManager nerRm) { if (ViewNames.NER_ONTONOTES.equals(getViewName())) nerRm = new NerOntonotesConfigurator().getConfig(nerRm); else nerRm = new NerBaseConfigurator().getConfig(nerRm); ParametersForLbjCode.currentParameters.forceNewSentenceOnLineBreaks = false; Parameters.readConfigAndLoadExternalData(nerRm); String dataset; if(viewName.toLowerCase().contains("conll")) { dataset = "enron-conll"; } else { dataset = "ontonotes"; } String data_split = nerRm.getString(NerBaseConfigurator.TRAINED_ON); try { Datastore ds = new Datastore(new ResourceConfigurator().getConfig(nerRm)); String artifact_id = "ner-model-" + dataset + "-" + data_split; File modelDir = ds.getDirectory("edu.illinois.cs.cogcomp.ner", artifact_id, 4.0, false); String model = ""; if(modelDir.getPath().contains("conll")) { model = modelDir.getPath() + "/model/EnronCoNLL.model"; } else { model = modelDir.getPath() + "/model/OntoNotes.model"; } NETaggerLevel1 tagger1 = new NETaggerLevel1(model + ".level1", model + ".level1.lex"); NETaggerLevel2 tagger2 = null; if (ParametersForLbjCode.currentParameters.featuresToUse.containsKey("PredictionsLevel1")) { tagger2 = new NETaggerLevel2(model + ".level2", model + ".level2.lex"); } this.t1 = tagger1; this.t2 = tagger2; } catch (InvalidPortException | DatastoreException | InvalidEndpointException e) { e.printStackTrace(); } }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if (null == mDisplayState) { cleanUp(); } else { mInAppView = inflater.inflate(R.layout.com_mixpanel_android_activity_notification_mini, container, false); final TextView bodyTextView = (TextView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_title); final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image); MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification(); bodyTextView.setText(inApp.getBody()); bodyTextView.setTextColor(inApp.getBorderColor()); notifImage.setImageBitmap(inApp.getImage()); mHandler.postDelayed(mRemover, MINI_REMOVE_TIME); GradientDrawable viewBackground = new GradientDrawable(); viewBackground.setColor(inApp.getBackgroundColor()); viewBackground.setCornerRadius(6); viewBackground.setStroke(2, inApp.getBorderColor()); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mInAppView.setBackgroundDrawable(viewBackground); } else { mInAppView.setBackground(viewBackground); } Drawable myIcon = new BitmapDrawable(getResources(), mDisplayState.getInAppNotification().getImage()); final int newColor = inApp.getImageTintColor(); myIcon.setColorFilter(newColor, PorterDuff.Mode.SRC_ATOP); notifImage.setImageDrawable(myIcon); } return mInAppView; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); if (null == mDisplayState) { cleanUp(); } else { mInAppView = inflater.inflate(R.layout.com_mixpanel_android_activity_notification_mini, container, false); final TextView bodyTextView = (TextView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_title); final ImageView notifImage = (ImageView) mInAppView.findViewById(R.id.com_mixpanel_android_notification_image); MiniInAppNotification inApp = (MiniInAppNotification) mDisplayState.getInAppNotification(); bodyTextView.setText(inApp.getBody()); bodyTextView.setTextColor(inApp.getBodyColor()); notifImage.setImageBitmap(inApp.getImage()); mHandler.postDelayed(mRemover, MINI_REMOVE_TIME); GradientDrawable viewBackground = new GradientDrawable(); viewBackground.setColor(inApp.getBackgroundColor()); viewBackground.setCornerRadius(6); viewBackground.setStroke(2, inApp.getBorderColor()); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mInAppView.setBackgroundDrawable(viewBackground); } else { mInAppView.setBackground(viewBackground); } Drawable myIcon = new BitmapDrawable(getResources(), mDisplayState.getInAppNotification().getImage()); myIcon.setColorFilter(inApp.getImageTintColor(), PorterDuff.Mode.SRC_ATOP); notifImage.setImageDrawable(myIcon); } return mInAppView; }
Source:
private ResourceSet createResourceSet() { final ResourceSet resourceSet = new ResourceSetImpl(); getSets().add(resourceSet); if (!EMFPlugin.IS_ECLIPSE_RUNNING) { UMLResourcesUtil.init(resourceSet); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("uml", new UMLResourceFactoryImpl()); resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("notation", new GMFResourceFactory()); EPackage.Registry.INSTANCE.put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE); EPackage.Registry.INSTANCE.put(NotationPackage.eNS_URI, NotationPackage.eINSTANCE); final URL UMLJarredFileLocation = ResourcesPlugin.class.getResource("ResourcesPlugin.class"); String UMLJarPath = UMLJarredFileLocation.toString(); UMLJarPath = UMLJarPath.substring(0, UMLJarPath.indexOf('!')); final Map<URI, URI> uriMap = URIConverter.URI_MAP; uriMap.put(URI.createURI(UMLResource.LIBRARIES_PATHMAP), URI.createURI(UMLJarPath + "!/libraries/")); uriMap.put(URI.createURI(UMLResource.METAMODELS_PATHMAP), URI.createURI(UMLJarPath + "!/metamodels/")); uriMap.put(URI.createURI(UMLResource.PROFILES_PATHMAP), URI.createURI(UMLJarPath + "!/profiles/")); } return resourceSet; }

Target:
private ResourceSet createResourceSet() { final ResourceSet resourceSet = new ResourceSetImpl(); getSets().add(resourceSet); if (!EMFPlugin.IS_ECLIPSE_RUNNING) { UMLRTResourcesUtil.init(resourceSet); } return resourceSet; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_already_registered); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(R.layout.custom_sherlock_bar); getSupportActionBar().setTitle(R.string.empty_app_title); devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class); context = this; resources = context.getResources(); Bundle extras = getIntent().getExtras(); if (extras != null) { if (extras.containsKey(getResources().getString(R.string.intent_extra_fresh_reg_flag))) { freshRegFlag = extras.getBoolean( getResources().getString(R.string.intent_extra_fresh_reg_flag)); } } String registrationId = Preference.getString(context, resources.getString(R.string.shared_pref_regId)); if (registrationId != null && !registrationId.isEmpty()) { regId = registrationId; } if (freshRegFlag) { Preference.putString(context, resources.getString(R.string.shared_pref_registered), resources.getString(R.string.shared_pref_reg_success)); if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) { startDeviceAdminPrompt(cdmDeviceAdmin); } freshRegFlag = false; } txtRegText = (TextView) findViewById(R.id.txtRegText); btnUnregister = (Button) findViewById(R.id.btnUnreg); btnUnregister.setTag(TAG_BTN_UNREGISTER); btnUnregister.setOnClickListener(onClickListenerButtonClicked); if (devicePolicyManager.isAdminActive(cdmDeviceAdmin)) { LocalNotification.startPolling(context); isPollingStarted = true; } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_already_registered); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(R.layout.custom_sherlock_bar); getSupportActionBar().setTitle(Constants.EMPTY_STRING); devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); cdmDeviceAdmin = new ComponentName(this, AgentDeviceAdminReceiver.class); context = this; resources = context.getResources(); Bundle extras = getIntent().getExtras(); if (extras != null) { if (extras.containsKey(getResources().getString(R.string.intent_extra_fresh_reg_flag))) { freshRegFlag = extras.getBoolean( getResources().getString(R.string.intent_extra_fresh_reg_flag)); } } String registrationId = Preference.getString(context, resources.getString(R.string.shared_pref_regId)); if (registrationId != null && !registrationId.isEmpty()) { regId = registrationId; } if (freshRegFlag) { Preference.putString(context, resources.getString(R.string.shared_pref_registered), resources.getString(R.string.shared_pref_reg_success)); if (!devicePolicyManager.isAdminActive(cdmDeviceAdmin)) { startDeviceAdminPrompt(cdmDeviceAdmin); } freshRegFlag = false; } txtRegText = (TextView) findViewById(R.id.txtRegText); btnUnregister = (Button) findViewById(R.id.btnUnreg); btnUnregister.setTag(TAG_BTN_UNREGISTER); btnUnregister.setOnClickListener(onClickListenerButtonClicked); }
Source:
private boolean pmwBankAccountTypeIsDefinedInKfs(String pmwBankAccountTypeToVerify) { List<PaymentWorksBankAccountType> matchingValues = getPaymentWorksBatchUtilityService().findAllPmwBankAccountTypesMaching(pmwBankAccountTypeToVerify); return matchingValues.size() == 1 ? true : false; }

Target:
private boolean pmwBankAccountTypeIsDefinedInKfs(String pmwBankAccountTypeToVerify) { List<PaymentWorksBankAccountType> matchingValues = getPaymentWorksBatchUtilityService().findAllPmwBankAccountTypesMatching(pmwBankAccountTypeToVerify); return (matchingValues.size() == 1); }
Source:
public void firstNumberCanBeGiven() throws Exception { final BigInteger initialCounterValue = new BigInteger("5001"); final CustomObjectBigIntegerNumberGeneratorConfigBuilder configBuilder = CustomObjectBigIntegerNumberGeneratorConfigBuilder.of(client(), randomKey()); configBuilder.container(randomKey()); configBuilder.initialValue(initialCounterValue); final CustomObjectBigIntegerNumberGeneratorConfig config = configBuilder.build(); final BigIntegerNumberGenerator generator = CustomObjectBigIntegerNumberGenerator.of(config); final BigInteger firstNumber = generator.getNextNumber().toCompletableFuture().join(); assertThat(firstNumber).isEqualTo(initialCounterValue); }

Target:
public void firstNumberCanBeGiven() throws Exception { final BigInteger initialCounterValue = new BigInteger("5001"); final CustomObjectBigIntegerNumberGeneratorConfig config = CustomObjectBigIntegerNumberGeneratorConfigBuilder.of(client(), randomKey()) .container(randomKey()) .initialValue(initialCounterValue) .build(); final BigIntegerNumberGenerator generator = CustomObjectBigIntegerNumberGenerator.of(config); final BigInteger firstNumber = generator.getNextNumber().toCompletableFuture().join(); assertThat(firstNumber).isEqualTo(initialCounterValue); }
Source:
public void serialize(PathDetail value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartArray(); gen.writeNumber(value.getFirst()); gen.writeNumber(value.getLast()); if (value.getValue() instanceof Double) gen.writeNumber((Double) value.getValue()); else if (value.getValue() instanceof Long) gen.writeNumber((Long) value.getValue()); else if (value.getValue() instanceof Integer) gen.writeNumber((Integer) value.getValue()); else if (value.getValue() instanceof Integer) gen.writeNumber((Integer) value.getValue()); else if (value.getValue() instanceof Boolean) gen.writeBoolean((Boolean) value.getValue()); else if (value.getValue() instanceof String) gen.writeString((String) value.getValue()); else throw new JsonGenerationException("Unsupported type for PathDetail.value" + value.getValue().getClass(), gen); gen.writeEndArray(); }

Target:
public void serialize(PathDetail value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartArray(); gen.writeNumber(value.getFirst()); gen.writeNumber(value.getLast()); if (value.getValue() instanceof Double) gen.writeNumber((Double) value.getValue()); else if (value.getValue() instanceof Long) gen.writeNumber((Long) value.getValue()); else if (value.getValue() instanceof Integer) gen.writeNumber((Integer) value.getValue()); else if (value.getValue() instanceof Boolean) gen.writeBoolean((Boolean) value.getValue()); else if (value.getValue() instanceof String) gen.writeString((String) value.getValue()); else throw new JsonGenerationException("Unsupported type for PathDetail.value" + value.getValue().getClass(), gen); gen.writeEndArray(); }
Source:
public void setUp() { System.setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); configuration = Configuration.DEFAULT; }

Target:
public void setUp() { configuration = Configuration.DEFAULT; }
Source:
private static OutputFormat<BaseRow> createBulkWriterOutputFormat( BulkWriter.Factory<BaseRow> factory, Path path) { return new OutputFormat<BaseRow>() { private BulkWriter<BaseRow> writer; @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { this.writer = factory.create(path.getFileSystem() .create(path, FileSystem.WriteMode.OVERWRITE)); } @Override public void writeRecord(BaseRow record) throws IOException { writer.addElement(record); } @Override public void close() throws IOException { writer.flush(); writer.finish(); } }; }

Target:
private static OutputFormat<BaseRow> createBulkWriterOutputFormat( BulkWriter.Factory<BaseRow> factory, Path path) { return new OutputFormat<BaseRow>() { private static final long serialVersionUID = 1L; private transient BulkWriter<BaseRow> writer; @Override public void configure(Configuration parameters) { } @Override public void open(int taskNumber, int numTasks) throws IOException { this.writer = factory.create(path.getFileSystem() .create(path, FileSystem.WriteMode.OVERWRITE)); } @Override public void writeRecord(BaseRow record) throws IOException { writer.addElement(record); } @Override public void close() throws IOException { writer.flush(); writer.finish(); } }; }
Source:
private boolean validateProxy() { if (!hasProxy()) { return true; } final String host = mProxyHost.getText().toString().trim(); final String port = mProxyPort.getText().toString().trim(); return ProxySelector.validate(host, port, "") == 0; }

Target:
private boolean validateProxy() { if (!hasProxy()) { return true; } final String host = mProxyHost.getText().toString().trim(); final String port = mProxyPort.getText().toString().trim(); return Proxy.validate(host, port, "") == Proxy.PROXY_VALID; }
Source:
protected boolean validate() { if (!super.validate() || !checkStorageDomain()) { return false; } oldDomain = storageDomainStaticDao.get(getStorageDomain().getId()); getStorageDomain().setLastTimeUsedAsMaster(oldDomain.getLastTimeUsedAsMaster()); return validateMasterDomainCannotBeBackup() && validateStoragePropertiesUpdate(); }

Target:
protected boolean validate() { if (!super.validate() || !checkStorageDomain()) { return false; } oldDomain = storageDomainStaticDao.get(getStorageDomain().getId()); getStorageDomain().setLastTimeUsedAsMaster(oldDomain.getLastTimeUsedAsMaster()); return validateStoragePropertiesUpdate(); }
Source:
public void disconnect() { Object lock = partitions != null ? partitions : new Object(); synchronized (lock) { document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }

Target:
public void disconnect() { synchronized (partitions) { document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }
Source:
private void prepareOpenShiftPVCs(OpenShiftEnvironment osEnv, String namespace) throws InfrastructureException { try (OpenShiftClient client = clientFactory.create()) { final Map<String, PersistentVolumeClaim> existing = new HashMap<>(); client.persistentVolumeClaims() .inNamespace(namespace) .list() .getItems() .forEach(p -> existing.put(p.getMetadata().getName(), p)); final Map<String, PersistentVolumeClaim> toCreate = Maps.difference(osEnv.getPersistentVolumeClaims(), existing).entriesOnlyOnLeft(); for (PersistentVolumeClaim pvc : toCreate.values()) { client.persistentVolumeClaims().inNamespace(namespace).create(pvc); } } catch (KubernetesClientException ex) { throw new InfrastructureException(ex.getMessage(), ex); } }

Target:
private void prepareOpenShiftPVCs(OpenShiftEnvironment osEnv, String namespace) throws InfrastructureException { try (OpenShiftClient client = clientFactory.create()) { final Set<String> existing = client.persistentVolumeClaims() .inNamespace(namespace) .list() .getItems() .stream() .map(p -> p.getMetadata().getName()) .collect(toSet()); osEnv.getPersistentVolumeClaims() .entrySet() .stream() .filter(e -> !existing.contains(e.getKey())) .map(Map.Entry::getValue) .forEach(e -> client.persistentVolumeClaims().inNamespace(namespace).create(e)); } catch (KubernetesClientException ex) { throw new InfrastructureException(ex.getMessage(), ex); } }