auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<CatalogProtos.PartitionDescProto> getPartitions(String databaseName, String tableName) throws CatalogException { throw new RuntimeException("not supported!"); }

Target:
public List<CatalogProtos.PartitionDescProto> getPartitions(String databaseName, String tableName) throws CatalogException { List<CatalogProtos.PartitionDescProto> protos = new ArrayList<CatalogProtos.PartitionDescProto>(); if (partitions.containsKey(tableName)) { for (CatalogProtos.PartitionDescProto proto : partitions.get(tableName).values()) { protos.add(proto); } } return protos; }
Source:
public void render(Context context, GlusterBrickEntity brick, SafeHtmlBuilder sb, String id) { if (brick == null) { return; } GlusterStatus status = brick.getStatus(); ImageResource statusImage = null; switch (status) { case DOWN: statusImage = resources.downImage(); break; case UP: statusImage = resources.upImage(); break; case UNKNOWN: statusImage = resources.questionMarkImage(); break; default: statusImage = resources.downImage(); } SafeHtml statusImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML()); if (brick.getUnSyncedEntries() != null && brick.getUnSyncedEntries() > 0) { SafeHtml alertImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.alertImage()).getHTML()); sb.append(templates.statusWithAlertTemplate(statusImageHtml, alertImageHtml, id, status.toString())); } else { sb.append(templates.statusTemplate(statusImageHtml, id, status.toString())); } }

Target:
public void render(Context context, GlusterBrickEntity brick, SafeHtmlBuilder sb, String id) { if (brick == null) { return; } GlusterStatus status = brick.getStatus(); ImageResource statusImage = null; switch (status) { case DOWN: statusImage = resources.downImage(); break; case UP: statusImage = resources.upImage(); break; case UNKNOWN: statusImage = resources.questionMarkImage(); break; default: statusImage = resources.downImage(); } SafeHtml statusImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML()); if (brick.getUnSyncedEntries() > 0) { SafeHtml alertImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(resources.alertImage()).getHTML()); sb.append(templates.statusWithAlertTemplate(statusImageHtml, alertImageHtml, id, status.toString())); } else { sb.append(templates.statusTemplate(statusImageHtml, id, status.toString())); } }
Source:
private static boolean isMessageContinue(@NotNull String messagePart) { return Character.isWhitespace(messagePart.charAt(0)); }

Target:
private static boolean isMessageContinue(@NotNull String messagePart) { return messagePart.isEmpty() || Character.isWhitespace(messagePart.charAt(0)); }
Source:
public MetadataResponse sync(@PathParam("entity") String entity, @PathParam("system") String system, @PathParam("key") String key, @QueryParam("values") String values) { if(entity!=null && entity.length()>0 && system!=null && system.length()>0 && key!=null && key.length()>0 && values!=null && values.length()>0) { String valueArray[] = values.split(","); return client.get().sync(entity, system, key, valueArray); } return null; }

Target:
public MetadataResponse sync(@PathParam("entity") String entity, @PathParam("system") String system, @PathParam("key") String key, @QueryParam("values") String values) { if(StringUtils.isNotBlank(entity) && StringUtils.isNotBlank(system) && StringUtils.isNotBlank(key) && StringUtils.isNotBlank(values)) { String valueArray[] = values.split(","); return client.get().sync(entity, system, key, valueArray); } return null; }
Source:
public HelixTaskResult handleMessage() throws InterruptedException { verifyMessage(_message); HelixTaskResult result = new HelixTaskResult(); assert (_correlationId.equalsIgnoreCase(_message.getCorrelationId())); _logger.info("invoking reply message " + _message.getMsgId() + ", correlationid:" + _correlationId); AsyncCallback callback = _callbackMap.get(_correlationId); if (callback != null) { synchronized (callback) { callback.onReply(_message); if (callback.isDone()) { _logger.info("Removing finished callback, correlationid:" + _correlationId); _callbackMap.remove(_correlationId); } } } else { String msg = "Message " + _message.getMsgId() + " does not have correponding callback. Probably timed out already. Correlation id: " + _correlationId; _logger.warn(msg); } result.setSuccess(true); return result; }

Target:
public HelixTaskResult handleMessage() throws InterruptedException { verifyMessage(_message); HelixTaskResult result = new HelixTaskResult(); assert (_correlationId.equalsIgnoreCase(_message.getCorrelationId())); _logger.info("invoking reply message " + _message.getMsgId() + ", correlationid:" + _correlationId); AsyncCallback callback = _callbackMap.get(_correlationId); synchronized (callback) { callback.onReply(_message); if (callback.isDone()) { _logger.info("Removing finished callback, correlationid:" + _correlationId); _callbackMap.remove(_correlationId); } } result.setSuccess(true); return result; }
Source:
public void add(Event<T> windowEvent) { if (!windowEvent.isWatermark() && !windowEvent.isTimer()) { queue.add(windowEvent); } else { LOG.fine(String.format("Got watermark event with ts %d", windowEvent.getTimestamp())); } track(windowEvent); compactWindow(); }

Target:
public void add(Event<T> windowEvent) { if (windowEvent.isWatermark()) { LOG.fine(String.format("Got watermark event with ts %d", windowEvent.getTimestamp())); } else if (windowEvent.isTimer()) { LOG.fine(String.format("Got timer event with ts %d", windowEvent.getTimestamp())); } else { queue.add(windowEvent); } track(windowEvent); compactWindow(); }
Source:
public static boolean isBundleClassUri(String uri) { if (uri != null && uri.startsWith(BUNDLECLASS_SCHEMA)) { String[] split = uri.substring(14).split("/"); if (split.length == 2) { return true; } ; } return false; }

Target:
public static boolean isBundleClassUri(String uri) { if (uri != null && uri.startsWith(BUNDLECLASS_SCHEMA)) { String[] split = uri.substring(BUNDLECLASS_SCHEMA.length()).split("/"); if (split.length == 2) { return true; } } return false; }
Source:
public Row next() throws IOException { while (true) { try { Row result = currentDelegate.next(); if (result != null) { lastRowKey = result.getKey(); rowCount.incrementAndGet(); currentErrorBackoff = null; timeoutRetryCount.set(0); } return result; } catch (ScanTimeoutException rte) { handleScanTimeout(rte); } catch (IOExceptionWithStatus ioe) { handleIOException(ioe); } } }

Target:
public Row next() throws IOException { while (true) { try { Row result = currentDelegate.next(); if (result != null) { lastRowKey = result.getKey(); rowCount++; currentErrorBackoff = null; timeoutRetryCount = null; } return result; } catch (ScanTimeoutException rte) { handleScanTimeout(rte); } catch (IOExceptionWithStatus ioe) { handleIOException(ioe); } } }
Source:
public void registerCustomDataRegistration(SpongeDataRegistration registration) { Preconditions.checkState(SpongeDataManager.allowRegistrations); Preconditions.checkState(registration.key.getNamespace().equals(registration.plugin.getMetadata().getId()), "Registration namespace (%s) is not matching plugin id (%s)", registration.key, registration.plugin.getMetadata().getId()); this.registrations.put(registration.getKey(), registration); this.registrationByPluginContainerId.computeIfAbsent(registration.getPluginContainer().getMetadata().getId(), k -> new ArrayList<>()).add(registration); for (DataStore dataStore : registration.getDataStores()) { this.dataStoreRegistry.register(dataStore, registration.getKeys()); } for (Key key : registration.getKeys()) { this.registerCustomDataProviderForKey(registration, key); } }

Target:
public void registerCustomDataRegistration(SpongeDataRegistration registration) { if (!SpongeDataManager.allowRegistrations) { throw new IllegalStateException("Data Registration is not allowed anymore."); } if (!registration.key.getNamespace().equals(registration.plugin.getMetadata().getId())) { throw new IllegalStateException(String.format("Registration namespace (%s) is not matching plugin id (%s)", registration.key, registration.plugin.getMetadata().getId())); } this.registrations.put(registration.getKey(), registration); this.registrationByPluginContainerId.computeIfAbsent(registration.getPluginContainer().getMetadata().getId(), k -> new ArrayList<>()).add(registration); for (final DataStore dataStore : registration.getDataStores()) { this.dataStoreRegistry.register(dataStore, registration.getKeys()); } for (Key key : registration.getKeys()) { this.registerCustomDataProviderForKey(registration, key); } }
Source:
public void verifyCertificate(CertificateMessage message) throws HandshakeException { if (message.getCertificateChain() != null) { if (certificateVerifier != null) { certificateVerifier.verifyCertificate(message, session); } else { LOGGER.debug("Certificate validation failed: x509 could not be trusted!"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Trust is not possible!", alert); } } else { RawPublicKeyIdentity rpk = new RawPublicKeyIdentity(message.getPublicKey()); if (!rpkStore.isTrusted(rpk)) { LOGGER.debug("Certificate validation failed: Raw public key is not trusted"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Raw public key is not trusted", alert); } } }

Target:
public void verifyCertificate(CertificateMessage message) throws HandshakeException { if (message.getCertificateChain() != null) { if (certificateVerifier != null) { certificateVerifier.verifyCertificate(message, session); } else { LOGGER.debug("Certificate validation failed: x509 could not be trusted!"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.UNEXPECTED_MESSAGE, session.getPeer()); throw new HandshakeException("Trust is not possible!", alert); } } else { RawPublicKeyIdentity rpk = new RawPublicKeyIdentity(message.getPublicKey()); if (!rpkStore.isTrusted(rpk)) { LOGGER.debug("Certificate validation failed: Raw public key is not trusted"); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.BAD_CERTIFICATE, session.getPeer()); throw new HandshakeException("Raw public key is not trusted", alert); } } }
Source:
private static String urlCombine(final String url, final String... parts) { final StringBuilder sb = new StringBuilder(); sb.append(url); for(final String s : parts) { if (StringUtils.isNotBlank(s)) { if (sb.charAt(sb.length() - 1) != '/') { sb.append("/"); } sb.append(s); } } return sb.toString(); }

Target:
private static String urlCombine(final String url, final String... parts) { final StringBuilder sb = new StringBuilder(); if (url != null) { sb.append(url); for (final String s : parts) { if (StringUtils.isNotBlank(s)) { if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') { sb.append("/"); } sb.append(s); } } } return sb.toString(); }
Source:
public void updateAccount(Account account) { notNull(account, "account"); try { restTemplate.put(account.getUri(), account.createAccountUpdate()); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new AccountNotFoundException(account.getUri(), e); } else { throw e; } } catch (GoodDataException e) { throw new GoodDataException("Unable to remove account", e); } }

Target:
public void updateAccount(Account account) { notNull(account, "account"); try { final MappingJacksonValue jacksonValue = new MappingJacksonValue(account); jacksonValue.setSerializationView(Account.UpdateView.class); restTemplate.put(account.getUri(), jacksonValue); } catch (GoodDataRestException e) { if (HttpStatus.NOT_FOUND.value() == e.getStatusCode()) { throw new AccountNotFoundException(account.getUri(), e); } else { throw e; } } catch (GoodDataException e) { throw new GoodDataException("Unable to update account", e); } }
Source:
protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { final CosmosQueryCreator creator = new CosmosQueryCreator(tree, accessor, mappingContext); final CosmosQuery query = creator.createQuery(); query.setTree(tree); return query; }

Target:
protected CosmosQuery createQuery(CosmosParameterAccessor accessor) { final CosmosQueryCreator creator = new CosmosQueryCreator(tree, accessor, mappingContext); final CosmosQuery query = creator.createQuery(); if (tree.isLimiting()) { Integer limit = tree.getMaxResults(); if (limit != null) { query.setLimit(limit); } } return query; }
Source:
public void fill(Control control, MouseEvent event, Point pt) { Chart chart = getChart(); if (chart.getSeriesSet().getSeries().length != 0) { if (event == null || chart.getAxisSet().getXAxes().length == 0 || chart.getAxisSet().getYAxes().length == 0 || getDensityViewer().getControl().getSeriesSet().getSeries().length == 0) { return; } ISeries series = getDensityViewer().getControl().getSeriesSet().getSeries()[0]; chart.getPlotArea().setToolTipText(null); if (series.getXSeries().length < 2) { return; } double delta = series.getXSeries()[1] - series.getXSeries()[0]; double[] xValues = series.getXSeries(); double coords = chart.getAxisSet().getXAxis(0).getDataCoordinate(event.x); int index = Arrays.binarySearch(xValues, coords); if (index < 0) { index = -index - 2; } if (index < 0) { return; } long x2 = (long) series.getXSeries()[index]; long x1 = (long) (x2 - delta); long y = Math.round(series.getYSeries()[index]); if (y > 0) { addItem(Messages.SimpleTooltipProvider_duration, FORMAT.format(x1) + '-' + FORMAT.format(x2)); addItem(null, ToolTipString.fromString(Messages.SimpleTooltipProvider_count), ToolTipString.fromDecimal(y)); } } }

Target:
public void fill(Control control, MouseEvent event, Point pt) { Chart chart = getChart(); if (chart.getSeriesSet().getSeries().length != 0) { if (event == null || chart.getAxisSet().getXAxes().length == 0 || chart.getAxisSet().getYAxes().length == 0 || getDensityViewer().getControl().getSeriesSet().getSeries().length == 0) { return; } ISeries series = getDensityViewer().getControl().getSeriesSet().getSeries()[0]; chart.getPlotArea().setToolTipText(null); double[] xValues = series.getXSeries(); if (xValues.length < 2) { return; } double delta = xValues[1] - xValues[0]; double coords = chart.getAxisSet().getXAxis(0).getDataCoordinate(event.x); int index = Arrays.binarySearch(xValues, coords); if (index < 0) { index = -index - 2; } if (index < 0) { return; } long x2 = (long) xValues[index]; long x1 = (long) (x2 - delta); long y = Math.round(series.getYSeries()[index]); if (y > 0) { addItem(Messages.SimpleTooltipProvider_duration, FORMAT.format(x1) + '-' + FORMAT.format(x2)); addItem(null, ToolTipString.fromString(Messages.SimpleTooltipProvider_count), ToolTipString.fromDecimal(y)); } } }
Source:
protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { final ServerWebExchange exchange = webFilterExchange.getExchange(); final SecurityContextImpl securityContext = new SecurityContextImpl(authentication); return securityContextRepository.save(exchange, securityContext) .then(this.successHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); }

Target:
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { final ServerWebExchange exchange = webFilterExchange.getExchange(); final SecurityContextImpl securityContext = new SecurityContextImpl(authentication); return securityContextRepository.save(exchange, securityContext) .then(this.successHandler.onAuthenticationSuccess(webFilterExchange, authentication)) .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))); }
Source:
static Collection<RouteInfo> getRoutesFromTrafficSelectors( List<IkeTrafficSelector> trafficSelectors) { final HashSet<IpPrefix> prefixes = new HashSet<>(); final HashSet<RouteInfo> routes = new HashSet<>(); for (final IkeTrafficSelector selector : trafficSelectors) { for (final IpPrefix prefix : new IpRange(selector.startingAddress, selector.endingAddress).asIpPrefixes()) { routes.add(new RouteInfo(prefix, null)); } } return routes; }

Target:
static Collection<RouteInfo> getRoutesFromTrafficSelectors( List<IkeTrafficSelector> trafficSelectors) { final HashSet<RouteInfo> routes = new HashSet<>(); for (final IkeTrafficSelector selector : trafficSelectors) { for (final IpPrefix prefix : new IpRange(selector.startingAddress, selector.endingAddress).asIpPrefixes()) { routes.add(new RouteInfo(prefix, null)); } } return routes; }
Source:
public void remove() throws BlogServiceException{ if(StringUtil.isNotEmpty(getBlogHandle())){ getService().removeBlogPost(getPostUuid(), getBlogHandle()); } else{ getService().removeBlogPost(getPostUuid(), getAsString(BlogXPath.handle)); } }

Target:
public void remove() throws BlogServiceException{ getService().removeBlogPost(getPostUuid(), getBlogHandle()); }
Source:
public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) { final MountableFile mountableFile = MountableFile.forHostPath(hostPath); binds.add(new Bind(mountableFile.getFilesystemPath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext)); }

Target:
public void addFileSystemBind(final String hostPath, final String containerPath, final BindMode mode, final SelinuxContext selinuxContext) { final MountableFile mountableFile = MountableFile.forHostPath(hostPath); binds.add(new Bind(mountableFile.getMountablePath(), new Volume(containerPath), mode.accessMode, selinuxContext.selContext)); }
Source:
private int indexOfBatchChunkSizeParameter(Method method) { Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { if (Stream.of(parameterAnnotations[i]).anyMatch(BatchChunkSize.class::isInstance)) { return i; } } return -1; }

Target:
private int indexOfBatchChunkSizeParameter(Method method) { Annotation[][] parameterAnnotations = method.getParameterAnnotations(); return IntStream.range(0, parameterAnnotations.length) .filter(i -> Stream.of(parameterAnnotations[i]).anyMatch(BatchChunkSize.class::isInstance)) .findFirst() .orElse(-1); }
Source:
protected void createStatesGroup(Composite composite) { String stateTypeName = fProvider.getStateTypeName(); StringBuilder buffer = new StringBuilder(); if (!stateTypeName.isEmpty()) { buffer.append(stateTypeName); buffer.append(" "); } buffer.append(Messages.TmfTimeLegend_StateTypeName); StateItem[] stateTable = fProvider.getStateTable(); List<StateItem> stateItems = stateTable != null ? Arrays.asList(stateTable) : Collections.emptyList(); Multimap<String, StateItem> groupedStateItems = ArrayListMultimap.create(); for (StateItem stateItem : stateItems) { if (!isLinkState(stateItem)) { Object group = stateItem.getStyleMap().get(ITimeEventStyleStrings.group()); if (group instanceof String) { groupedStateItems.put((String) group, stateItem); } else { groupedStateItems.put(buffer.toString(), stateItem); } } } for (String groupedStateLabel : groupedStateItems.keySet()) { Group gs = new Group(composite, SWT.NONE); gs.setText(groupedStateLabel); GridLayout layout = new GridLayout(); layout.marginWidth = 20; layout.marginBottom = 10; gs.setLayout(layout); GridData gridData = new GridData(); gridData.verticalAlignment = SWT.TOP; gs.setLayoutData(gridData); for (StateItem stateItem : groupedStateItems.get(groupedStateLabel)) { new LegendEntry(gs, stateItem); } } }

Target:
protected void createStatesGroup(Composite composite) { String stateTypeName = fProvider.getStateTypeName(); StringBuilder buffer = new StringBuilder(); if (!stateTypeName.isEmpty()) { buffer.append(stateTypeName); buffer.append(" "); } buffer.append(Messages.TmfTimeLegend_StateTypeName); StateItem[] stateTable = fProvider.getStateTable(); List<StateItem> stateItems = stateTable != null ? Arrays.asList(stateTable) : Collections.emptyList(); Multimap<String, StateItem> groupedStateItems = LinkedHashMultimap.create(); for (StateItem stateItem : stateItems) { if (!isLinkState(stateItem)) { Object group = stateItem.getStyleMap().get(ITimeEventStyleStrings.group()); if (group instanceof String) { groupedStateItems.put((String) group, stateItem); } else { groupedStateItems.put(buffer.toString(), stateItem); } } } for (String groupedStateLabel : groupedStateItems.keySet()) { Group gs = new Group(composite, SWT.NONE); gs.setText(groupedStateLabel); GridLayout layout = new GridLayout(); layout.marginWidth = 20; layout.marginBottom = 10; gs.setLayout(layout); GridData gridData = new GridData(); gridData.verticalAlignment = SWT.TOP; gs.setLayoutData(gridData); for (StateItem stateItem : groupedStateItems.get(groupedStateLabel)) { new LegendEntry(gs, stateItem); } } }
Source:
public Response seedNodes() { StringWriter sw = new StringWriter(); try { CassandraFrameworkProtos.CassandraFrameworkConfiguration configuration = cluster.getConfiguration().get(); JsonFactory factory = new JsonFactory(); JsonGenerator json = factory.createGenerator(sw); json.setPrettyPrinter(new DefaultPrettyPrinter()); json.writeStartObject(); json.writeNumberField("native_port", CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_NATIVE)); json.writeNumberField("rpc_port", CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_RPC)); writeSeedIps(json); json.writeEndObject(); json.close(); } catch (Exception e) { LOGGER.error("Failed to build seed list", e); return Response.serverError().build(); } return Response.ok(sw.toString(), "application/json").build(); }

Target:
public Response seedNodes() { StringWriter sw = new StringWriter(); try { CassandraFrameworkProtos.CassandraFrameworkConfiguration configuration = cluster.getConfiguration().get(); JsonFactory factory = new JsonFactory(); JsonGenerator json = factory.createGenerator(sw); json.setPrettyPrinter(new DefaultPrettyPrinter()); json.writeStartObject(); json.writeNumberField("nativePort", CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_NATIVE)); json.writeNumberField("rpcPort", CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_RPC)); writeSeedIps(json); json.writeEndObject(); json.close(); } catch (Exception e) { LOGGER.error("Failed to build seed list", e); return Response.serverError().build(); } return Response.ok(sw.toString(), "application/json").build(); }
Source:
public void checkNameProjectTest() throws Exception { driver.navigate().to(swaggerUrl); Assert.assertTrue(swagger.getWsNamesFromWorkspacePage().contains(workspace.getName())); }

Target:
public void checkNameProjectTest() throws Exception { driver.navigate().to(swaggerUrl); assertTrue(swagger.getWsNamesFromWorkspacePage().contains(workspace.getName())); }
Source:
public void testScriptTaskFEEL() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-ScriptTaskFEEL.bpmn2"); ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); Map<String, Object> params = new HashMap<String, Object>(); params.put("name", "krisv"); Person person = new Person(); person.setName("krisv"); params.put("person", person); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("ScriptTask", params); assertEquals("Entry", processInstance.getVariable("x")); assertNull(processInstance.getVariable("y")); ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); assertEquals("Exit", getProcessVarValue(processInstance, "y")); assertEquals("tester", processInstance.getVariable("surname")); }

Target:
public void testScriptTaskFEEL() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-ScriptTaskFEEL.bpmn2"); ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); Map<String, Object> params = new HashMap<String, Object>(); params.put("name", "krisv"); Person person = new Person(); person.setName("krisv"); params.put("person", person); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("ScriptTask", params); assertEquals("Entry", processInstance.getVariable("x")); assertNull(processInstance.getVariable("y")); ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); assertEquals("Exit", getProcessVarValue(processInstance, "y")); assertEquals("tester", processInstance.getVariable("surname")); assertNodeTriggered(processInstance.getId(), "Script1"); }
Source:
public Optional<String> getCloseArgString() { return Optional.ofNullable(closeArg); }

Target:
public String getCloseArgString() { return this.closeArg; }
Source:
public void shouldCreateNewVisitWithVisitType() throws Exception { Patient patient = new Patient(); Location visitLocation = new Location(); String successMessage = "Success message"; String formattedPatient = "Patient name"; when(uiUtils.format(patient)).thenReturn(formattedPatient); when(uiUtils.message("coreapps.visit.createQuickVisit.successMessage", formattedPatient)).thenReturn(successMessage); HttpSession session = mock(HttpSession.class); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getSession()).thenReturn(session); Visit visit = createVisit(); List<VisitType> visitTypes = visitService.getAllVisitTypes(); VisitType visitType = null; if(visitTypes.size() > 0){ visitType = visitTypes.get(0); } when(adtService.ensureVisit(eq(patient), any(Date.class), eq(visitLocation))).thenReturn(visit); FragmentActionResult result = controller.create(adtService, patient, visitLocation, uiUtils, visitType, emrContext, request); verify(session).setAttribute(AppUiConstants.SESSION_ATTRIBUTE_INFO_MESSAGE, successMessage); verify(session).setAttribute(AppUiConstants.SESSION_ATTRIBUTE_TOAST_MESSAGE, "true"); assertThat(result, is(CoreMatchers.any(FragmentActionResult.class))); }

Target:
public void shouldCreateNewVisitWithVisitType() throws Exception { Patient patient = new Patient(); Location visitLocation = new Location(); String successMessage = "Success message"; String formattedPatient = "Patient name"; when(uiUtils.format(patient)).thenReturn(formattedPatient); when(uiUtils.message("coreapps.visit.createQuickVisit.successMessage", formattedPatient)).thenReturn(successMessage); HttpSession session = mock(HttpSession.class); HttpServletRequest request = mock(HttpServletRequest.class); when(request.getSession()).thenReturn(session); Visit visit = createVisit(); VisitType visitType = new VisitType(); visitType.setId(1); visitType.setName("Outpatient"); when(visitService.saveVisitType(visitType)).thenReturn(visitType); when(adtService.ensureVisit(eq(patient), any(Date.class), eq(visitLocation))).thenReturn(visit); FragmentActionResult result = controller.create(adtService, visitService, patient, visitLocation, uiUtils, visitType, emrContext, request); verify(session).setAttribute(AppUiConstants.SESSION_ATTRIBUTE_INFO_MESSAGE, successMessage); verify(session).setAttribute(AppUiConstants.SESSION_ATTRIBUTE_TOAST_MESSAGE, "true"); assertThat(result, is(CoreMatchers.any(FragmentActionResult.class))); }
Source:
@Test public void queryParamsSkippedIfConvertedToNull() throws IOException, InterruptedException { class Example { @POST("/query") Call<String> queryPath(@Query("a") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, "Ignored"); if(request.url().toString().contains("Ignored")){ fail(); } }

Target:
@Test public void queryParamsSkippedIfConvertedToNull() throws IOException, InterruptedException { class Example { @POST("/query") Call<String> queryPath(@Query("a") Object a) { return null; } } Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(new NullObjectConverterFactory()); Request request = buildRequest(Example.class, retrofitBuilder, "Ignored"); assertThat(request.url().toString()).doesNotContain("Ignored"); }
Source:
public UserPrivate getUserPrivate() { CryptoSession.getCurrent().setInitializationVector(initializationVector); return userPrivate; }

Target:
private UserPrivate getUserPrivate() { CryptoSession.getCurrent().setInitializationVector(initializationVector); return userPrivate; }
Source:
private Object getElementForView(ViewGroup parentView, View view) { if (view == null) { return null; } Object element = mViewToElementMap.get(view); if (element != null) { if (view.getParent() == parentView) { return element; } mViewToElementMap.remove(view); } Object fragment = FragmentCompatUtil.findFragmentForView(view); if (fragment != null) { mViewToElementMap.put(view, fragment); return fragment; } else { mViewToElementMap.put(view, view); return view; } }

Target:
private Object getElementForView(ViewGroup parentView, View view) { Object element = mViewToElementMap.get(view); if (element != null) { if (view.getParent() == parentView) { return element; } mViewToElementMap.remove(view); } Object fragment = FragmentCompatUtil.findFragmentForView(view); if (fragment != null) { mViewToElementMap.put(view, fragment); return fragment; } else { mViewToElementMap.put(view, view); return view; } }
Source:
public static synchronized UserContainer getInstance() { if (container != null && initialized == false) { List<User> users = Collections.emptyList(); UserService userService = UserServices.getUserService(); if (userService != null) { users = userService.getUsers(); } container.addContainerProperty(User.PROPERTY_FIRSTNAME, String.class, null); container.addContainerProperty(User.PROPERTY_LASTNAME, String.class, null); container.addContainerProperty(User.PROPERTY_EMAIL, String.class, null); container.addContainerProperty(User.PROPERTY_DISPLAY_NAME, String.class, null); container.addContainerProperty(PROPERTY_USER, User.class, null); for (User user : users) { container.addItem(user); } initialized = true; } return container; }

Target:
public static synchronized IndexedUserContainer getInstance() { return container; }
Source:
public void disconnected(SchedulerDriver driver) { getMainThreadExecutor().executeWithoutFencing(() -> MesosResourceManagerDriver.this.disconnected(new Disconnected())); }

Target:
public void disconnected(SchedulerDriver driver) { getMainThreadExecutor().execute(() -> MesosResourceManagerDriver.this.disconnected(new Disconnected())); }
Source:
ReleasedMessage(int id, String name) { assert name != null; this.name = name; cacheId(id); }

Target:
private ReleasedMessage(int id, String name) { assert name != null; this.name = name; cacheId(id); }
Source:
public void resendPhoneVerificationNoStudy() throws Exception { mockPlayContextWithJson(new Identifier((StudyIdentifier) null, TestConstants.PHONE)); controller.resendPhoneVerification(); }

Target:
public void resendPhoneVerificationNoStudy() throws Exception { String json = TestUtils.createJson("{'phone':{'number':'4082588569','regionCode':'US'}}"); mockPlayContextWithJson(json); controller.resendPhoneVerification(); }
Source:
public void setId(String id) { this.id = id; }

Target:
void setId(String id) { this.id = id; }
Source:
public void configure(Binder binder) { JsonConfigProvider.bind(binder, "druid.publish", SegmentPublisherProvider.class); JsonConfigProvider.bind(binder, "druid.db.tables", DbSegmentPublisherConfig.class); binder.bind(SegmentPublisher.class).toProvider(SegmentPublisherProvider.class); JsonConfigProvider.bind(binder, "druid.realtime", RealtimeManagerConfig.class); binder.bind(RealtimeManager.class).toProvider(RealtimeManagerProvider.class).in(ManageLifecycle.class); }

Target:
public void configure(Binder binder) { JsonConfigProvider.bind(binder, "druid.publish", SegmentPublisherProvider.class); binder.bind(SegmentPublisher.class).toProvider(SegmentPublisherProvider.class); JsonConfigProvider.bind(binder, "druid.realtime", RealtimeManagerConfig.class); binder.bind( new TypeLiteral<List<FireDepartment>>() { } ).toProvider(FireDepartmentsProvider.class); binder.bind(RealtimeManager.class).in(ManageLifecycle.class); }
Source:
public final boolean eq( Object other ) { if ( other == null ) { return false; } if ( other instanceof SequenceValue ) { return this.equals( (SequenceValue) other ); } return other instanceof Value && equals( (Value) other ); }

Target:
public final boolean eq( Object other ) { if ( other == null ) { return false; } return other instanceof SequenceValue && this.equals( (SequenceValue) other ); }
Source:
public List<String> getAllTagStrings(User user, String query) { List<String> allString = new ArrayList<>(); for (Tag each : getAllTags(user, query)) { allString.add(each.getTagValue()); } Collections.sort(allString); return allString; }

Target:
public List<String> getAllTagStrings(User user, String query) { return getAllTags(user, query).stream() .map(Tag::getTagValue) .sorted() .collect(toList()); }
Source:
public Future<RecordMetadata> send(ProducerRecord<K, V> record, Callback callback) { Span span = tracing.tracer().nextSpan(); span.tag(KAFKA_TOPIC_TAG, record.topic()); span.tag(KAFKA_KEY_TAG, record.key().toString()); injector.inject(span.context(), record.headers()); Future<RecordMetadata> recordMetadataFuture = wrappedProducer.send(record, callback); span.kind(Kind.CLIENT).start().flush(); return recordMetadataFuture; }

Target:
public Future<RecordMetadata> send(ProducerRecord<K, V> record, Callback callback) { Span span = tracing.tracer().nextSpan(); span.tag(KAFKA_TOPIC_TAG, record.topic()); injector.inject(span.context(), record.headers()); Future<RecordMetadata> recordMetadataFuture = wrappedProducer.send(record, callback); span.kind(Kind.CLIENT).start().flush(); return recordMetadataFuture; }
Source:
private Tuple2<Integer, Integer> readLength(MemorySegment segment, int segmentPosition, int segmentRemaining) throws IOException { int numBytes = min(lengthBuffer.remaining(), segmentRemaining); segment.get(segmentPosition, lengthBuffer, numBytes); if (lengthBuffer.hasRemaining()) { return POSITION_AND_SIZE_IF_LENGTH_NOT_FULLY_READ; } else { updateLength(lengthBuffer.getInt(0)); return Tuple2.of(segmentPosition + numBytes, segmentRemaining - numBytes); } }

Target:
private int readLength(MemorySegment segment, int segmentPosition, int segmentRemaining) throws IOException { int bytesToRead = min(lengthBuffer.remaining(), segmentRemaining); segment.get(segmentPosition, lengthBuffer, bytesToRead); if (!lengthBuffer.hasRemaining()) { updateLength(lengthBuffer.getInt(0)); } return bytesToRead; }
Source:
protected void testExecute_fakeCourse_shouldFail() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); loginAsInstructor(instructor1OfCourse1.googleId); ______TS("Get respondents for fake course"); String[] params = new String[] { Const.ParamsNames.COURSE_ID, "fake-course", }; assertNull(logic.getCourse("fake-course")); GetHasResponsesAction getHasResponsesAction = getAction(params); JsonResult jsonResult = getJsonResult(getHasResponsesAction); MessageOutput messageOutput = (MessageOutput) jsonResult.getOutput(); assertEquals(jsonResult.getStatusCode(), HttpStatus.SC_NOT_FOUND); assertEquals(messageOutput.getMessage(), "No course with id: fake-course"); }

Target:
protected void testExecute_fakeCourse_shouldFail() { InstructorAttributes instructor1OfCourse1 = typicalBundle.instructors.get("instructor1OfCourse1"); loginAsInstructor(instructor1OfCourse1.googleId); ______TS("Get respondents for fake course"); String[] params = new String[] { Const.ParamsNames.COURSE_ID, "fake-course", }; assertNull(logic.getCourse("fake-course")); GetHasResponsesAction getHasResponsesAction = getAction(params); JsonResult jsonResult = getJsonResult(getHasResponsesAction); MessageOutput messageOutput = (MessageOutput) jsonResult.getOutput(); assertEquals(HttpStatus.SC_NOT_FOUND, jsonResult.getStatusCode()); assertEquals("No course with id: fake-course", messageOutput.getMessage()); }
Source:
protected void doRemoveSemanticResource(final Resource res, final ResourceSet set) { set.getResources().remove(res); EObject rootObject = tracker.getRootObjectFromResourceURI(res.getURI().toString()); if (rootObject == null) { rootObject = res.getContents() == null ? null : res.getContents().get(0); } for (final DAnalysis analysis : this.allAnalyses()) { analysis.getModels().remove(rootObject); } disableCrossReferencerResolve(res); unregisterResourceInCrossReferencer(res); if (!isFromPackageRegistry(set, res)) { disableCrossReferencerResolve(res); res.unload(); enableCrossReferencerResolve(res); } }

Target:
protected void doRemoveSemanticResource(final Resource res, final ResourceSet set) { set.getResources().remove(res); EObject rootObject = tracker.getRootObjectFromResourceURI(res.getURI().toString()); if (rootObject == null) { rootObject = findSemanticRoot(res); } for (final DAnalysis analysis : this.allAnalyses()) { analysis.getModels().remove(rootObject); } unregisterResourceInCrossReferencer(res); if (!isFromPackageRegistry(set, res)) { disableCrossReferencerResolve(res); res.unload(); enableCrossReferencerResolve(res); } }
Source:
public void testQueueOrderWhenDownloading2Items() { ItemEnqueuePositionCalculator calculator = new ItemEnqueuePositionCalculator(options); DownloadStateProvider stubDownloadStateProvider = mock(DownloadStateProvider.class); stub(stubDownloadStateProvider.isDownloadingFile(any(FeedMedia.class))).toReturn(false); calculator.downloadStateProvider = stubDownloadStateProvider; List<FeedItem> queue = new ArrayList<>(queueInitial); Playable currentlyPlaying = getCurrentlyPlaying(idCurrentlyPlaying); FeedItem tFI101 = setAsDownloading(101, stubDownloadStateProvider); doAddToQueueAndAssertResult(message + " (1st download)", calculator, tFI101, queue, currentlyPlaying, idsExpectedAfter101); FeedItem tFI102 = setAsDownloading(102, stubDownloadStateProvider); doAddToQueueAndAssertResult(message + " (2nd download, it should preserve order of download)", calculator, tFI102, queue, currentlyPlaying, idsExpectedAfter102); }

Target:
public void testQueueOrderWhenDownloading2Items() { ItemEnqueuePositionCalculator calculator = new ItemEnqueuePositionCalculator(options); DownloadStateProvider stubDownloadStateProvider = mock(DownloadStateProvider.class); stub(stubDownloadStateProvider.isDownloadingFile(any(FeedMedia.class))).toReturn(false); calculator.downloadStateProvider = stubDownloadStateProvider; List<FeedItem> queue = new ArrayList<>(queueInitial); Playable currentlyPlaying = getCurrentlyPlaying(idCurrentlyPlaying); FeedItem tFI101 = setAsDownloading(101, stubDownloadStateProvider, true); doAddToQueueAndAssertResult(message + " (1st download)", calculator, tFI101, queue, currentlyPlaying, idsExpectedAfter101); FeedItem tFI102 = setAsDownloading(102, stubDownloadStateProvider, true); doAddToQueueAndAssertResult(message + " (2nd download, it should preserve order of download)", calculator, tFI102, queue, currentlyPlaying, idsExpectedAfter102); setAsDownloading(tFI102, stubDownloadStateProvider, false); FeedItem tFI103 = setAsDownloading(103, stubDownloadStateProvider, true); doAddToQueueAndAssertResult(message + " (3rd download, with 2nd download failed; " + "it should be behind 1st download (unless enqueueLocation is BACK)", calculator, tFI103, queue, currentlyPlaying, idsExpectedAfter103); }
Source:
private void installPnpm(List<String> installCommand) { List<String> command = new ArrayList<>(); command.addAll(installCommand); command.add("install"); command.add("pnpm@" + DEFAULT_PNPM_VERSION); FrontendUtils.console(YELLOW, FrontendUtils.commandToString(baseDir, command)); ProcessBuilder builder = FrontendUtils.createProcessBuilder(command); builder.environment().put("ADBLOCK", "1"); builder.directory(new File(baseDir)); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); builder.redirectError(ProcessBuilder.Redirect.INHERIT); Process process = null; try { process = builder.start(); getLogger().debug("Output of `{}`:", command.stream().collect(Collectors.joining(" "))); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String stdoutLine; while ((stdoutLine = reader.readLine()) != null) { getLogger().debug(stdoutLine); } } int errorCode = process.waitFor(); if (errorCode != 0) { getLogger().error("Couldn't install 'pnpm'"); } else { getLogger().debug("Pnpm is successfully installed"); } } catch (InterruptedException | IOException e) { getLogger().error("Error when running `npm install`", e); } finally { if (process != null) { process.destroyForcibly(); } } }

Target:
private void installPnpm(List<String> installCommand) { List<String> command = new ArrayList<>(); command.addAll(installCommand); command.add("install"); command.add("pnpm@" + DEFAULT_PNPM_VERSION); FrontendUtils.console(FrontendUtils.YELLOW, FrontendUtils.commandToString(baseDir, command)); ProcessBuilder builder = FrontendUtils.createProcessBuilder(command); builder.environment().put("ADBLOCK", "1"); builder.directory(new File(baseDir)); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); builder.redirectError(ProcessBuilder.Redirect.INHERIT); Process process = null; try { process = builder.start(); getLogger().debug("Output of `{}`:", command.stream().collect(Collectors.joining(" "))); try (BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) { String stdoutLine; while ((stdoutLine = reader.readLine()) != null) { getLogger().debug(stdoutLine); } } int errorCode = process.waitFor(); if (errorCode != 0) { getLogger().error("Couldn't install 'pnpm'"); } else { getLogger().debug("Pnpm is successfully installed"); } } catch (InterruptedException | IOException e) { getLogger().error("Error when running `npm install`", e); } finally { if (process != null) { process.destroyForcibly(); } } }
Source:
public HypervisorResource(ConsumerResource consumerResource, ConsumerCurator consumerCurator, ConsumerTypeCurator consumerTypeCurator, I18n i18n, OwnerCurator ownerCurator, Provider<GuestMigration> migrationProvider, ModelTranslator translator, GuestIdResource guestIdResource) { this.consumerResource = consumerResource; this.consumerCurator = consumerCurator; this.consumerTypeCurator = consumerTypeCurator; this.i18n = i18n; this.ownerCurator = ownerCurator; this.migrationProvider = migrationProvider; this.translator = translator; this.guestIdResource = guestIdResource; this.hypervisorType = consumerTypeCurator.lookupByLabel(ConsumerTypeEnum.HYPERVISOR.getLabel()); if (this.hypervisorType == null) { this.hypervisorType = consumerTypeCurator.create(new ConsumerType(ConsumerTypeEnum.HYPERVISOR)); } }

Target:
public HypervisorResource(ConsumerResource consumerResource, ConsumerCurator consumerCurator, ConsumerTypeCurator consumerTypeCurator, I18n i18n, OwnerCurator ownerCurator, Provider<GuestMigration> migrationProvider, ModelTranslator translator, GuestIdResource guestIdResource) { this.consumerResource = consumerResource; this.consumerCurator = consumerCurator; this.consumerTypeCurator = consumerTypeCurator; this.i18n = i18n; this.ownerCurator = ownerCurator; this.migrationProvider = migrationProvider; this.translator = translator; this.guestIdResource = guestIdResource; this.hypervisorType = consumerTypeCurator.lookupByLabel(ConsumerTypeEnum.HYPERVISOR.getLabel(), true); }
Source:
public QueryRunner<Row> preMergeQueryDecoration(final QueryRunner<Row> runner) { return new SubqueryQueryRunner<>( intervalChunkingQueryRunnerDecorator.decorate( new QueryRunner<Row>() { @Override public Sequence<Row> run(Query<Row> query, Map<String, Object> responseContext) { if (!(query instanceof GroupByQuery)) { return runner.run(query, responseContext); } GroupByQuery groupByQuery = (GroupByQuery) query; ArrayList<DimensionSpec> dimensionSpecs = new ArrayList<>(); Set<String> optimizedDimensions = optimizedExtractionDims(groupByQuery, true); for (DimensionSpec dimensionSpec : groupByQuery.getDimensions()) { if (optimizedDimensions.contains(dimensionSpec.getDimension())) { dimensionSpecs.add( new DefaultDimensionSpec(dimensionSpec.getDimension(), dimensionSpec.getOutputName()) ); } else { dimensionSpecs.add(dimensionSpec); } } return runner.run( new GroupByQuery( groupByQuery.getDataSource(), groupByQuery.getQuerySegmentSpec(), groupByQuery.getDimFilter(), groupByQuery.getGranularity(), dimensionSpecs, groupByQuery.getAggregatorSpecs(), groupByQuery.getPostAggregatorSpecs(), groupByQuery.getHavingSpec(), groupByQuery.getLimitSpec(), groupByQuery.getContext() ), responseContext ); } }, this ) ); }

Target:
public QueryRunner<Row> preMergeQueryDecoration(final QueryRunner<Row> runner) { return new SubqueryQueryRunner<>( intervalChunkingQueryRunnerDecorator.decorate( new QueryRunner<Row>() { @Override public Sequence<Row> run(Query<Row> query, Map<String, Object> responseContext) { if (!(query instanceof GroupByQuery)) { return runner.run(query, responseContext); } GroupByQuery groupByQuery = (GroupByQuery) query; ArrayList<DimensionSpec> dimensionSpecs = new ArrayList<>(); Set<String> optimizedDimensions = ImmutableSet.copyOf( Iterables.transform( extractionsToRewrite(groupByQuery), new Function<DimensionSpec, String>() { @Override public String apply(DimensionSpec input) { return input.getDimension(); } } ) ); for (DimensionSpec dimensionSpec : groupByQuery.getDimensions()) { if (optimizedDimensions.contains(dimensionSpec.getDimension())) { dimensionSpecs.add( new DefaultDimensionSpec(dimensionSpec.getDimension(), dimensionSpec.getOutputName()) ); } else { dimensionSpecs.add(dimensionSpec); } } return runner.run( groupByQuery.withDimensionSpecs(dimensionSpecs), responseContext ); } }, this ) ); }
Source:
private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { AsyncTasks task = DbFacade.getInstance().getAsyncTaskDao().get(asyncTaskId); if (task.getTaskId().equals(NGuid.Empty)) { AsyncTaskManager.failTaskWithoutVdsmId(task); } } }

Target:
private void clearAsyncTasksWithOutVdsmId() { for (Guid asyncTaskId : getReturnValue().getAsyncTaskIdList()) { AsyncTasks task = DbFacade.getInstance().getAsyncTaskDao().get(asyncTaskId); if (task.getVdsmTaskId().equals(NGuid.Empty)) { AsyncTaskManager.failTaskWithoutVdsmId(task); } } }
Source:
public String removeDotDot(String s) { while (true) { int i = s.indexOf("/../"); if (i < 1) return s; int j = s.lastIndexOf("/", i-1); if (j < 0) j = 0; else j = j + 1; s = s.substring(0, j) + s.substring(i+4); } }

Target:
public String removeDotDot(String s) { int loopCount = 0; while (true) { int i = s.indexOf("/../"); if (i < 1 || ++loopCount > 999) return s; int j = s.lastIndexOf("/", i-1); if (j < 0) j = 0; else j = j + 1; s = s.substring(0, j) + s.substring(i+4); } }
Source:
public static List<Certificate> parseChain(final String chain) throws IOException, CertificateException { final List<Certificate> certs = new ArrayList<Certificate>(); try(final PemReader pemReader = new PemReader(new StringReader(chain));) { final PemObject pemObject = pemReader.readPemObject(); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent()); for (final Certificate cert : certificateFactory.generateCertificates(bais)) { if (cert instanceof X509Certificate) { certs.add(cert); } } if (certs.isEmpty()) { throw new IllegalArgumentException("Unable to decode certificate chain"); } } return certs; }

Target:
public static List<Certificate> parseChain(final String chain) throws IOException, CertificateException { Preconditions.checkNotNull(chain); final List<Certificate> certs = new ArrayList<Certificate>(); try(final PemReader pemReader = new PemReader(new StringReader(chain));) { final PemObject pemObject = pemReader.readPemObject(); final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509"); final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent()); for (final Certificate cert : certificateFactory.generateCertificates(bais)) { if (cert instanceof X509Certificate) { certs.add(cert); } } if (certs.isEmpty()) { throw new IllegalStateException("Unable to decode certificate chain"); } } return certs; }