auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void handleStartingPodStatus(CompletableFuture<Void> podRunningFuture, Pod pod) { if (POD_STATUS_PHASE_RUNNING.equals(pod.getStatus().getPhase())) { podRunningFuture.complete(null); } if (POD_STATUS_PHASE_SUCCEEDED.equals(pod.getStatus().getPhase())) { podRunningFuture.completeExceptionally( new InfrastructureException( "Pod container has been terminated. Container must be configured to use a non-terminating command.")); } if (POD_STATUS_PHASE_FAILED.equals(pod.getStatus().getPhase())) { String exceptionMessage = "Pod '" + pod.getMetadata().getName() + "' failed to start."; String reason = pod.getStatus().getReason(); if (Strings.isNullOrEmpty(reason)) { try { String podLog = clientFactory .create() .pods() .inNamespace(namespace) .withName(pod.getMetadata().getName()) .getLog(); exceptionMessage = exceptionMessage.concat(" Pod logs: ").concat(podLog); } catch (InfrastructureException e) { exceptionMessage = exceptionMessage.concat(" Error occurred while fetching pod logs."); } } else { exceptionMessage = exceptionMessage.concat(" Reason: ").concat(reason); } podRunningFuture.completeExceptionally(new InfrastructureException(exceptionMessage)); LOG.warn(exceptionMessage); } }

Target:
private void handleStartingPodStatus(CompletableFuture<Void> podRunningFuture, Pod pod) { if (POD_STATUS_PHASE_RUNNING.equals(pod.getStatus().getPhase())) { podRunningFuture.complete(null); return; } if (POD_STATUS_PHASE_SUCCEEDED.equals(pod.getStatus().getPhase())) { podRunningFuture.completeExceptionally( new InfrastructureException( "Pod container has been terminated. Container must be configured to use a non-terminating command.")); return; } if (POD_STATUS_PHASE_FAILED.equals(pod.getStatus().getPhase())) { String exceptionMessage = "Pod '" + pod.getMetadata().getName() + "' failed to start."; String reason = pod.getStatus().getReason(); if (Strings.isNullOrEmpty(reason)) { try { String podLog = clientFactory .create() .pods() .inNamespace(namespace) .withName(pod.getMetadata().getName()) .getLog(); exceptionMessage = exceptionMessage.concat(" Pod logs: ").concat(podLog); } catch (InfrastructureException e) { exceptionMessage = exceptionMessage.concat(" Error occurred while fetching pod logs."); } } else { exceptionMessage = exceptionMessage.concat(" Reason: ").concat(reason); } podRunningFuture.completeExceptionally(new InfrastructureException(exceptionMessage)); LOG.warn(exceptionMessage); } }
Source:
public boolean batchFetch(List<RowLocation> locations, List<ExecRow> destRows,FormatableBitSet validColumns,boolean waitForLock) throws StandardException{ if (locations.size() == 0) return false; Partition htable = getTable(); KeyHashDecoder rowDecoder = null; try{ DataGet baseGet=opFactory.newDataGet(trans.getTxnInformation(),locations.get(0).getBytes(),null); baseGet.returnAllVersions(); DataGet get = createGet(baseGet,destRows.get(0).getRowArray(),validColumns); Iterator<DataResult> results = htable.batchGet(get, Lists.transform(locations, ROWLOCATION_TO_BYTES)); assert results != null:"Results Returned are Null"; int i = 0; DescriptorSerializer[] serializers = null; int[] cols=FormatableBitSetUtils.toIntArray(validColumns); while (results.hasNext()) { DataResult result = results.next(); DataValueDescriptor[] destRow = destRows.get(i).getRowArray(); if (serializers ==null) { serializers = VersionedSerializers.forVersion(tableVersion, true).getSerializers(destRow); rowDecoder=new EntryDataDecoder(cols,null,serializers); } ExecRow row=new ValueRow(destRow.length); row.setRowArray(destRow); row.resetRowArray(); DataCell keyValue=result.userData(); rowDecoder.set(keyValue.valueArray(),keyValue.valueOffset(),keyValue.valueLength()); rowDecoder.decode(row); i++; } return true; }catch(Exception e){ e.printStackTrace(); throw Exceptions.parseException(e); } finally { if (rowDecoder !=null) Closeables.closeAndSwallowIOExceptions(rowDecoder); } }

Target:
public boolean batchFetch(List<RowLocation> locations, List<ExecRow> destRows,FormatableBitSet validColumns,boolean waitForLock) throws StandardException{ if (locations.size() == 0) return false; Partition htable = getTable(); KeyHashDecoder rowDecoder = null; try{ DataGet baseGet=opFactory.newDataGet(trans.getTxnInformation(),locations.get(0).getBytes(),null); baseGet.returnAllVersions(); DataGet get = createGet(baseGet,destRows.get(0).getRowArray(),validColumns); Iterator<DataResult> results = htable.batchGet(get, Lists.transform(locations, ROWLOCATION_TO_BYTES)); assert results != null:"Results Returned are Null"; int i = 0; DescriptorSerializer[] serializers = null; int[] cols=FormatableBitSetUtils.toIntArray(validColumns); while (results.hasNext()) { DataResult result = results.next(); DataValueDescriptor[] destRow = destRows.get(i).getRowArray(); if (serializers ==null) { serializers = VersionedSerializers.forVersion(tableVersion, true).getSerializers(destRow); rowDecoder=new EntryDataDecoder(cols,null,serializers); } ExecRow row=new ValueRow(destRow.length); row.setRowArray(destRow); row.resetRowArray(); DataCell keyValue=result.userData(); rowDecoder.set(keyValue.valueArray(),keyValue.valueOffset(),keyValue.valueLength()); rowDecoder.decode(row); i++; } return true; }catch(Exception e){ throw Exceptions.parseException(e); } finally { if (rowDecoder !=null) Closeables.closeAndSwallowIOExceptions(rowDecoder); } }
Source:
public StringListType(StringType... rows) { typeDetails = new ArrayList<>(rows.length); for (StringType row : rows) { typeDetails.add(row.toString()); } }

Target:
public StringListType(StringType... rows) { typeDetails = Arrays.stream(rows) .map(StringType::toString) .collect(Collectors.toList()); }
Source:
public static ReplicationPeerManager create(ZKWatcher zk, Configuration conf, String clusterId) throws ReplicationException { ReplicationPeerStorage peerStorage = ReplicationStorageFactory.getReplicationPeerStorage(zk, conf); ConcurrentMap<String, ReplicationPeerDescription> peers = new ConcurrentHashMap<>(); for (String peerId : peerStorage.listPeerIds()) { ReplicationPeerConfig peerConfig = peerStorage.getPeerConfig(peerId); ReplicationPeerConfig updatedPeerConfig = ReplicationPeerConfigUtil. addBasePeerConfigsIfNotPresent(conf,peerConfig); peerStorage.updatePeerConfig(peerId,updatedPeerConfig); boolean enabled = peerStorage.isPeerEnabled(peerId); SyncReplicationState state = peerStorage.getPeerSyncReplicationState(peerId); peers.put(peerId, new ReplicationPeerDescription(peerId, enabled, updatedPeerConfig, state)); } return new ReplicationPeerManager(peerStorage, ReplicationStorageFactory.getReplicationQueueStorage(zk, conf), peers, conf, clusterId); }

Target:
public static ReplicationPeerManager create(ZKWatcher zk, Configuration conf, String clusterId) throws ReplicationException { ReplicationPeerStorage peerStorage = ReplicationStorageFactory.getReplicationPeerStorage(zk, conf); ConcurrentMap<String, ReplicationPeerDescription> peers = new ConcurrentHashMap<>(); for (String peerId : peerStorage.listPeerIds()) { ReplicationPeerConfig peerConfig = peerStorage.getPeerConfig(peerId); peerConfig = ReplicationPeerConfigUtil.addBasePeerConfigsIfNotPresent(conf, peerConfig); peerStorage.updatePeerConfig(peerId, peerConfig); boolean enabled = peerStorage.isPeerEnabled(peerId); SyncReplicationState state = peerStorage.getPeerSyncReplicationState(peerId); peers.put(peerId, new ReplicationPeerDescription(peerId, enabled, peerConfig, state)); } return new ReplicationPeerManager(peerStorage, ReplicationStorageFactory.getReplicationQueueStorage(zk, conf), peers, conf, clusterId); }
Source:
public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); Context.clearCacheForCurrentUser(); }

Target:
public void setUserProperty(String prop, String value) { getUserProperties().put(prop, value); }
Source:
public boolean remove(String lookupName) { final LookupExtractorFactory lookupExtractorFactory = lookupMap.remove(lookupName); if (lookupExtractorFactory != null) { LOGGER.debug("Removing lookup [%s]", lookupName); if (!isClosed() && lookupSnapshotTaker != null) { lookupSnapshotTaker.takeSnapshot(getAllAsList()); } return lookupExtractorFactory.close(); } return false; }

Target:
public boolean remove(String lookupName) { synchronized (lock) { final LookupExtractorFactory lookupExtractorFactory = lookupMap.remove(lookupName); if (lookupExtractorFactory != null) { LOGGER.debug("Removed lookup [%s]", lookupName); if (lookupSnapshotTaker != null) { lookupSnapshotTaker.takeSnapshot(getAllAsList()); } return lookupExtractorFactory.close(); } } return false; }
Source:
@CheckReturnValue public final @Nullable T fromJson(String string) throws IOException { JsonReader reader = JsonReader.of(new Buffer().writeUtf8(string)); T result = fromJson(reader); if (reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; }

Target:
@CheckReturnValue public final @Nullable T fromJson(String string) throws IOException { JsonReader reader = JsonReader.of(new Buffer().writeUtf8(string)); T result = fromJson(reader); if (!isLenient() && reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; }
Source:
public SecurityEventVisitor<?, String> build() { return new SimpleSecurityEventFormatter(this); }

Target:
public SecurityEventVisitor<Void, String> build() { return new SimpleSecurityEventFormatter(this); }
Source:
public MessageProperties toMessageProperties(AMQP.BasicProperties source, Envelope envelope, String charset) { final MessageProperties messageProperties = super.toMessageProperties(source, envelope, charset); final String header = String.valueOf(messageProperties.getHeaders().get(TraceeConstants.HTTP_HEADER_NAME)); if (header != null && !header.isEmpty()) { final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile); if (filterConfiguration.shouldProcessContext(IncomingResponse)) { final Map<String, String> parsedContext = transportSerialization.parse(Arrays.asList(header)); backend.putAll(filterConfiguration.filterDeniedParams(parsedContext, IncomingResponse)); } } return messageProperties; }

Target:
public MessageProperties toMessageProperties(AMQP.BasicProperties source, Envelope envelope, String charset) { final MessageProperties messageProperties = super.toMessageProperties(source, envelope, charset); final Object headerObject = messageProperties.getHeaders().get(TraceeConstants.JMS_HEADER_NAME); if (headerObject != null) { final String headerString = String.valueOf(headerObject); if (!headerString.isEmpty()) { final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile); if (filterConfiguration.shouldProcessContext(TraceeFilterConfiguration.Channel.AsyncProcess)) { final Map<String, String> parsedContext = transportSerialization.parse(Arrays.asList(headerString)); backend.putAll(filterConfiguration.filterDeniedParams(parsedContext, TraceeFilterConfiguration.Channel.AsyncProcess)); } } } return messageProperties; }
Source:
protected String getPath(String query) throws URISyntaxException { URIBuilder uri; uri = new URIBuilder(query); log.debug("Retrieving path from query"); return uri.getPath(); }

Target:
protected String getPath(String query) throws URISyntaxException { URIBuilder uri; uri = new URIBuilder(query); return uri.getPath(); }
Source:
public boolean doAction(View view, ViewActionTrigger actionDetail, ViewDetail viewDetail) { FragmentManager fragmentManager = oldFragment.getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction().replace(fragmentContainer, fragment).addToBackStack(null).commit(); return false; }

Target:
public boolean doAction(View view, ViewActionTrigger actionDetail, ViewDetail viewDetail) { FragmentManager fragmentManager = oldFragment.getActivity().getSupportFragmentManager(); if(addToBackStack){ fragmentManager.beginTransaction().replace(fragmentContainer, fragment).addToBackStack(null).commit(); } else{ fragmentManager.beginTransaction().replace(fragmentContainer, fragment).commit(); } return false; }
Source:
public PasswordTextInput(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); inflate(context, R.layout.password_edit_text, this); editText = (EditText) findViewById(R.id.password_edit_text_input); passwordShowButton = findViewById(R.id.password_edit_text_show); passwordShowButton.setOnClickListener(this); updateButtonOpacity(); }

Target:
public PasswordTextInput(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); }
Source:
protected void setWorldSpawn(CommandSender sender) { if (sender instanceof Player) { Player p = (Player) sender; Location l = p.getLocation(); World w = p.getWorld(); setWorldSpawn(sender, w, l); } else { sender.sendMessage("You cannot use this command from the console."); } }

Target:
protected void setWorldSpawn(CommandSender sender) { if (sender instanceof Player) { Player p = (Player) sender; Location l = p.getLocation(); World w = p.getWorld(); setWorldSpawn(sender, w, l); } else { sender.sendMessage("You need to give coordinates to use this command from the console!"); } }
Source:
public void testErrornousHandlerWithStrategyRethrow() throws Exception { KieBase kbase = createKnowledgeBaseWithoutDumper("handler/BPMN2-UserTaskWithBooleanOutput.bpmn2", "handler/BPMN2-ScriptTask.bpmn2"); KieSession ksession = createKnowledgeSession(kbase); ErrornousWorkItemHandler workItemHandler = new ErrornousWorkItemHandler("ScriptTask", HandlingStrategy.RETHROW); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); try { Map<String, Object> params = new HashMap<>(); params.put("isChecked", false); ProcessInstance processInstance = ksession.startProcess("com.sample.boolean", params); assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); assertProcessVarValue(processInstance, "isChecked", "false"); } catch (WorkflowRuntimeException e) { assertEquals("On purpose", e.getCause().getMessage()); } }

Target:
public void testErrornousHandlerWithStrategyRethrow() throws Exception { KieBase kbase = createKnowledgeBaseWithoutDumper("handler/BPMN2-UserTaskWithBooleanOutput.bpmn2", "handler/BPMN2-ScriptTask.bpmn2"); KieSession ksession = createKnowledgeSession(kbase); ErrornousWorkItemHandler workItemHandler = new ErrornousWorkItemHandler("ScriptTask", HandlingStrategy.RETHROW); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler); try { Map<String, Object> params = new HashMap<>(); params.put("isChecked", false); ksession.startProcess("com.sample.boolean", params); fail("Should fail since strategy is rethrow"); } catch (WorkflowRuntimeException e) { assertEquals("On purpose", e.getCause().getMessage()); } }
Source:
protected A param(String key, String val) { if(params.get(key) == null) { params.put(key, new ArrayList<String>()); } params.get(key).add(val); @SuppressWarnings("unchecked") A result = (A) this; return result; }

Target:
protected A param(String key, String val) { params.put(key, new ArrayList<String>()); return paramAddToList(key, val); }
Source:
private JSONObject getConfiguration() throws JSONException { JSONObject configuration = new JSONObject(); configuration.put("port", config.getPort()); configuration.put("register", true); if (config.getProxy() != null) { configuration.put("proxy", config.getProxy()); } else { configuration.put("proxy", "org.openqa.grid.selenium.proxy.DefaultRemoteProxy"); } configuration.put("role", "node"); configuration.put("registerCycle", config.getRegisterCycle()); configuration.put("maxSession", config.getMaxSession()); URL registrationUrl; try { registrationUrl = new URL(config.getRegistrationUrl()); } catch (MalformedURLException e) { log.log(Level.SEVERE, "Grid hub url cannot be parsed", e); throw new SelendroidException("Grid hub url cannot be parsed: " + e.getMessage()); } configuration.put("hubHost", registrationUrl.getHost()); configuration.put("hubPort", registrationUrl.getPort()); configuration.put("seleniumProtocol", "WebDriver"); configuration.put("host", config.getServerHost()); configuration.put("remoteHost", "http://" + config.getServerHost() + ":" + config.getPort()); return configuration; }

Target:
private JSONObject getConfiguration() throws JSONException { JSONObject configuration = new JSONObject(); configuration.put("port", config.getPort()); configuration.put("register", true); if (config.getProxy() != null) { configuration.put("proxy", config.getProxy()); } else { configuration.put("proxy", "org.openqa.grid.selenium.proxy.DefaultRemoteProxy"); } configuration.put("role", "node"); configuration.put("registerCycle", config.getRegisterCycle()); configuration.put("maxSession", config.getMaxSession()); configuration.put("hubHost", hub.getHost()); configuration.put("hubPort", hub.getPort()); configuration.put("seleniumProtocol", "WebDriver"); configuration.put("host", config.getServerHost()); configuration.put("remoteHost", "http://" + config.getServerHost() + ":" + config.getPort()); return configuration; }
Source:
protected void initializeScopingHint() { String working_sets = settings.get(STORE_WORKING_SETS); if (working_sets == null || working_sets.isEmpty()) { participantScope.setSelection(true); updateParticipantScope(); } else { StringTokenizer st = new StringTokenizer(working_sets, " ,"); ArrayList<IWorkingSet> ws = new ArrayList<>(); while (st.hasMoreTokens()) { String workingSetName = st.nextToken(); if (workingSetName != null && workingSetName.isEmpty() == false) { IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager(); IWorkingSet workingSet = workingSetManager.getWorkingSet(workingSetName); if (workingSet != null) { ws.add(workingSet); } } } if(! ws.isEmpty()) { this.workingSets = ws.toArray(new IWorkingSet[ws.size()]); updateWorkingSetScope(); updateWorkingSetLabel(); participantScope.setSelection(false); selectedResourcesScope.setSelection(false); workingSetScope.setSelection(true); } } }

Target:
protected void initializeScopingHint() { String working_sets = settings.get(STORE_WORKING_SETS); if (working_sets == null || working_sets.isEmpty()) { participantScope.setSelection(true); updateParticipantScope(); } else { StringTokenizer st = new StringTokenizer(working_sets, " ,"); ArrayList<IWorkingSet> ws = new ArrayList<>(); while (st.hasMoreTokens()) { String workingSetName = st.nextToken(); if (workingSetName != null && !workingSetName.isEmpty()) { IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager(); IWorkingSet workingSet = workingSetManager.getWorkingSet(workingSetName); if (workingSet != null) { ws.add(workingSet); } } } if(! ws.isEmpty()) { this.workingSets = ws.toArray(new IWorkingSet[ws.size()]); updateWorkingSetScope(); updateWorkingSetLabel(); participantScope.setSelection(false); selectedResourcesScope.setSelection(false); workingSetScope.setSelection(true); } } }
Source:
public final FieldData clone() { FieldData clone = new FieldData(); try { clone.cachedExtension = cachedExtension; if (unknownFieldData == null) { clone.unknownFieldData = null; } else { clone.unknownFieldData.addAll(unknownFieldData); } if (value instanceof MessageNano) { clone.value = ((MessageNano) value).clone(); } else if (value instanceof byte[]) { clone.value = ((byte[]) value).clone(); } else if (value instanceof byte[][]) { clone.value = ((byte[][]) value).clone(); } else if (value instanceof boolean[]) { clone.value = ((boolean[]) value).clone(); } else if (value instanceof int[]) { clone.value = ((int[]) value).clone(); } else if (value instanceof long[]) { clone.value = ((long[]) value).clone(); } else if (value instanceof float[]) { clone.value = ((float[]) value).clone(); } else if (value instanceof double[]) { clone.value = ((double[]) value).clone(); } else if (value instanceof MessageNano[]) { MessageNano[] valueArray = (MessageNano[]) value; MessageNano[] cloneArray = new MessageNano[valueArray.length]; clone.value = cloneArray; for (int i = 0; i < valueArray.length; i++) { cloneArray[i] = valueArray[i].clone(); } } return clone; } catch (CloneNotSupportedException e) { throw new AssertionError(e); } }

Target:
public final FieldData clone() { FieldData clone = new FieldData(); try { clone.cachedExtension = cachedExtension; if (unknownFieldData == null) { clone.unknownFieldData = null; } else { clone.unknownFieldData.addAll(unknownFieldData); } if (value == null) { } else if (value instanceof MessageNano) { clone.value = ((MessageNano) value).clone(); } else if (value instanceof byte[]) { clone.value = ((byte[]) value).clone(); } else if (value instanceof byte[][]) { byte[][] valueArray = (byte[][]) value; byte[][] cloneArray = new byte[valueArray.length][]; clone.value = cloneArray; for (int i = 0; i < valueArray.length; i++) { cloneArray[i] = valueArray[i].clone(); } } else if (value instanceof boolean[]) { clone.value = ((boolean[]) value).clone(); } else if (value instanceof int[]) { clone.value = ((int[]) value).clone(); } else if (value instanceof long[]) { clone.value = ((long[]) value).clone(); } else if (value instanceof float[]) { clone.value = ((float[]) value).clone(); } else if (value instanceof double[]) { clone.value = ((double[]) value).clone(); } else if (value instanceof MessageNano[]) { MessageNano[] valueArray = (MessageNano[]) value; MessageNano[] cloneArray = new MessageNano[valueArray.length]; clone.value = cloneArray; for (int i = 0; i < valueArray.length; i++) { cloneArray[i] = valueArray[i].clone(); } } return clone; } catch (CloneNotSupportedException e) { throw new AssertionError(e); } }
Source:
public Configuration getConfiguration(GraphContext context) { AbstractIterationOperation<FileModel> commitPeriodically = new AbstractIterationOperation<FileModel>() { private int uncommittedIterations = 0; @Override public void perform(GraphRewrite event, EvaluationContext context, FileModel payload) { uncommittedIterations++; if (uncommittedIterations > 10) { event.getGraphContext().getGraph().getBaseGraph().commit(); uncommittedIterations = 0; } } @Override public String toString() { return "CommitPeriodically"; } }; return ConfigurationBuilder.begin() .addRule() .when(Query.find(FileModel.class) .withProperty(FileModel.IS_DIRECTORY, false) .withProperty(FileModel.FILE_PATH, QueryPropertyComparisonType.REGEX, ".*\\.class") ) .perform(new AddClassFileMetadata().and(commitPeriodically).and(MonitorIterationProgress.monitor("Indexed class file: ", 1000))); }

Target:
public Configuration getConfiguration(GraphContext context) { AbstractIterationOperation<FileModel> commitPeriodically = new AbstractIterationOperation<FileModel>() { private int uncommittedIterations = 0; @Override public void perform(GraphRewrite event, EvaluationContext context, FileModel payload) { uncommittedIterations++; if (uncommittedIterations > 10) { event.getGraphContext().getGraph().getBaseGraph().commit(); uncommittedIterations = 0; } } @Override public String toString() { return "CommitPeriodically"; } }; return ConfigurationBuilder.begin() .addRule() .when(Query.find(FileModel.class) .withProperty(FileModel.IS_DIRECTORY, false) .withProperty(FileModel.FILE_PATH, QueryPropertyComparisonType.REGEX, ".*\\.class") ) .perform(new AddClassFileMetadata().and(commitPeriodically).and(IterationProgress.monitoring("Indexed class file: ", 1000))); }
Source:
void genCode() throws IOException { if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IOException("unable to create output directory " + outputDirectory); } } FileWriter c = null, h = null; try { c = new FileWriter(new File(outputDirectory, mName + ".c")); h = new FileWriter(new File(outputDirectory, mName + ".h")); h.write(" \n"); h.write("\n"); c.write(" \n"); c.write("\n"); h.write("#ifndef __" + mName.toUpperCase().replace('.', '_') + "__\n"); h.write("#define __" + mName.toUpperCase().replace('.', '_') + "__\n"); h.write("#include \"recordio.h\"\n"); for (Iterator<JFile> i = mInclFiles.iterator(); i.hasNext(); ) { JFile f = i.next(); h.write("#include \"" + f.getName() + ".h\"\n"); } h.write("\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"); c.write("#include <stdlib.h>\n"); c.write("#include \"" + mName + ".h\"\n\n"); for (Iterator<JRecord> i = mRecList.iterator(); i.hasNext(); ) { JRecord jr = i.next(); jr.genCCode(h, c); } h.write("\n#ifdef __cplusplus\n}\n#endif\n\n"); h.write("#endif } catch (IOException e) { throw e; } finally { if (h != null) { try { h.close(); } catch (IOException ex) { throw ex; } finally { if (c != null) { c.close(); } } } if (c != null) { c.close(); } } }

Target:
void genCode() throws IOException { if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IOException("unable to create output directory " + outputDirectory); } } try (FileWriter c = new FileWriter(new File(outputDirectory, mName + ".c")); FileWriter h = new FileWriter(new File(outputDirectory, mName + ".h")); ) { h.write(" \n"); h.write("\n"); c.write(" \n"); c.write("\n"); h.write("#ifndef __" + mName.toUpperCase().replace('.', '_') + "__\n"); h.write("#define __" + mName.toUpperCase().replace('.', '_') + "__\n"); h.write("#include \"recordio.h\"\n"); for (Iterator<JFile> i = mInclFiles.iterator(); i.hasNext(); ) { JFile f = i.next(); h.write("#include \"" + f.getName() + ".h\"\n"); } h.write("\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"); c.write("#include <stdlib.h>\n"); c.write("#include \"" + mName + ".h\"\n\n"); for (Iterator<JRecord> i = mRecList.iterator(); i.hasNext(); ) { JRecord jr = i.next(); jr.genCCode(h, c); } h.write("\n#ifdef __cplusplus\n}\n#endif\n\n"); h.write("#endif } }
Source:
public boolean isSamePost(ReaderPost post) { return post != null && post.blogId == this.blogId && post.postId == this.postId && post.feedId == this.feedId && post.feedItemId == this.feedItemId && post.numLikes == this.numLikes && post.numReplies == this.numReplies && post.isFollowedByCurrentUser == this.isFollowedByCurrentUser && post.isLikedByCurrentUser == this.isLikedByCurrentUser && post.isCommentsOpen == this.isCommentsOpen && post.useExcerpt == this.useExcerpt && post.isBookmarked == this.isBookmarked && post.getTitle().equals(this.getTitle()) && post.getExcerpt().equals(this.getExcerpt()) && post.getText().equals(this.getText()); }

Target:
public boolean isSamePost(ReaderPost post) { return post != null && post.blogId == this.blogId && post.postId == this.postId && post.feedId == this.feedId && post.feedItemId == this.feedItemId && post.numLikes == this.numLikes && post.numReplies == this.numReplies && post.isFollowedByCurrentUser == this.isFollowedByCurrentUser && post.isLikedByCurrentUser == this.isLikedByCurrentUser && post.isCommentsOpen == this.isCommentsOpen && post.useExcerpt == this.useExcerpt && post.getTitle().equals(this.getTitle()) && post.getExcerpt().equals(this.getExcerpt()) && post.getText().equals(this.getText()); }
Source:
protected void testAccessControl_instructorAccessOwnResponse_accessible() { ______TS("Instructor intends to access own response, should be accessible"); loginAsInstructor(instructor1OfCourse1.getGoogleId()); assertEquals(instructor1OfCourse1.getEmail(), typicalResponse3.getGiver()); FeedbackResponseUpdateRequest updateRequest = new FeedbackResponseUpdateRequest(); updateRequest.setQuestionType(FeedbackQuestionType.MCQ); updateRequest.setRecipientIdentifier(typicalResponse3.getRecipient()); FeedbackMcqResponseDetails newDetails = new FeedbackMcqResponseDetails(); newDetails.setAnswer("TEAM_NOT_EXIST"); updateRequest.setResponseDetails(newDetails); String[] instructorAccessOwnPersonParams = new String[] { Const.ParamsNames.INTENT, Intent.INSTRUCTOR_SUBMISSION.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_ID, typicalResponse3.getId(), }; UpdateFeedbackResponseAction a = getAction(updateRequest, instructorAccessOwnPersonParams); a.checkSpecificAccessControl(); }

Target:
protected void testAccessControl_instructorAccessOwnResponse_accessible() { ______TS("Instructor intends to access own response, should be accessible"); loginAsInstructor(instructor1OfCourse1.getGoogleId()); assertEquals(instructor1OfCourse1.getEmail(), instructor1ResponseToAll.getGiver()); FeedbackResponseUpdateRequest updateRequest = getUpdateRequest(instructor1ResponseToAll.getRecipient()); String[] instructorAccessOwnPersonParams = new String[] { Const.ParamsNames.INTENT, Intent.INSTRUCTOR_SUBMISSION.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_ID, instructor1ResponseToAll.getId(), }; verifyCanAccess(updateRequest, instructorAccessOwnPersonParams); }
Source:
private int findLastPosition(final DetailNode detailNode) { if (detailNode.getChildren().length == 0) { return lines2position.get(detailNode.getLineNumber()) + detailNode.getColumnNumber() + detailNode.getText().length(); } else { return findLastPosition(detailNode.getChildren()[detailNode.getChildren().length - 1]); } }

Target:
private int findLastPosition(final DetailNode detailNode) { final int lastPosition; if (detailNode.getChildren().length == 0) { lastPosition = lines2position.get(detailNode.getLineNumber()) + detailNode.getColumnNumber() + detailNode.getText().length(); } else { final DetailNode lastChild = detailNode.getChildren()[detailNode.getChildren().length - 1]; lastPosition = findLastPosition(lastChild); } return lastPosition; }
Source:
public List<String> validationErrors() { List<String> errors = new ArrayList<>(); Base64Value base64Value; try { String safeValue = this.value.replace('-', '+').replace('_', '/'); base64Value = new Base64Value(safeValue); if ((this.value.contains("-") || this.value.contains("_")) && (this.value.contains("+") || this.value.contains("/"))) { errors.add( "Invalid base64-value (characters from both Base and \"URL and Filename safe\" alphabets). Check RFC 4648 for details."); } } catch (IllegalArgumentException e) { errors.add(e.getMessage()); return errors; } if (base64Value.size() < 16) { errors.add("CSP specification recommends nonce-value to be at least 128 bits long (before encoding)."); } return errors; }

Target:
public List<String> validationErrors() { List<String> errors = new ArrayList<>(); Base64Value base64Value; try { String safeValue = this.value.replace('-', '+').replace('_', '/'); base64Value = new Base64Value(safeValue); if ((this.value.contains("-") || this.value.contains("_")) && (this.value.contains("+") || this.value.contains("/"))) { errors.add( "Invalid base64-value. Must use either RFC4648 \"base64\" characters (including + and /) or RFC4648 \"base64url\" characters (including - and _), but not both."); } } catch (IllegalArgumentException e) { errors.add(e.getMessage()); return errors; } if (base64Value.size() < 16) { errors.add("CSP specification recommends nonce-value to be at least 128 bits long (before encoding)."); } return errors; }
Source:
private void stopAffinityWorkerCache(){ try{ affinityWorkerCache.close(); } catch (IOException e) { } catch (NullPointerException e){ } finally{ affinityWorkerCache = null; } }

Target:
private void stopAffinityWorkerCache(){ try{ affinityWorkerCache.close(); } catch (IOException e) { log.warn("Affinity worker cache cannot be closed", e); } catch (NullPointerException e){ log.warn("Affinity worker cache in null", e); } finally{ affinityWorkerCache = null; } }
Source:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", this::setContentType); before("/*", this::setContentType); before("", mimeType, apiAuthenticationHelper::checkAdminUserAnd401); before("/*", mimeType, apiAuthenticationHelper::checkAdminUserAnd401); get("", this::index); get(Routes.ArtifactStoreConfig.NAME, this::show); post("", this::create); put(Routes.ArtifactStoreConfig.NAME, this::update); delete(Routes.ArtifactStoreConfig.NAME, this::destroy); exception(RecordNotFoundException.class, this::notFound); }); }

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", this::setContentType); before("/*", this::setContentType); before("", mimeType, apiAuthenticationHelper::checkAdminUserAnd401); before("/*", mimeType, apiAuthenticationHelper::checkAdminUserAnd401); get("", this::index); get(Routes.ArtifactStoreConfig.ID, this::show); post("", this::create); put(Routes.ArtifactStoreConfig.ID, this::update); delete(Routes.ArtifactStoreConfig.ID, this::destroy); exception(RecordNotFoundException.class, this::notFound); }); }
Source:
private void handleStart(ITmfEvent event, ITmfStateSystemBuilder ss) { String traceId = event.getContent().getFieldValue(String.class, "trace_id_low"); traceId = Long.toHexString(Long.decode(traceId)); int traceQuark = ss.getQuarkAbsoluteAndAdd(traceId); int ustSpansQuark = ss.getQuarkRelativeAndAdd(traceQuark, UST_QUARK); String spanId = event.getContent().getFieldValue(String.class, "span_id"); int spanQuark = ss.getQuarkRelativeAndAdd(ustSpansQuark, spanId); long timestamp = event.getTimestamp().toNanos(); String name = event.getContent().getFieldValue(String.class, "op_name"); ss.modifyAttribute(timestamp, name, spanQuark); }

Target:
private void handleStart(ITmfEvent event, ITmfStateSystemBuilder ss) { String traceId = event.getContent().getFieldValue(String.class, "trace_id_low"); traceId = Long.toHexString(Long.decode(traceId)); int traceQuark = ss.getQuarkAbsoluteAndAdd(traceId); int ustSpansQuark = ss.getQuarkRelativeAndAdd(traceQuark, UST_QUARK); String spanId = event.getContent().getFieldValue(String.class, "span_id"); spanId = Long.toHexString(Long.decode(spanId)); int spanQuark = ss.getQuarkRelativeAndAdd(ustSpansQuark, spanId); long timestamp = event.getTimestamp().toNanos(); String name = event.getContent().getFieldValue(String.class, "op_name"); ss.modifyAttribute(timestamp, name, spanQuark); }
Source:
public CarrierWaitingToneHelper(Context context) { mContext = context; ConfigCarrier == context.getResources().getBoolean(R.bool.config_carrier_waitting_tone); }

Target:
public CarrierWaitingToneHelper(Context context) { mContext = context; mCarrierWaitingToneSupport = context.getResources().getBoolean(R.bool.config_carrier_waiting_tone); }
Source:
public AssertionError failure(AssertionInfo info, ErrorMessageFactory messageFactory) { AssertionError error = failureIfErrorMessageIsOverridden(info); if (error != null) return error; AssertionError assertionError = new AssertionFailedError(messageFactory.create(info.description(), info.representation())); removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError); printThreadDumpIfNeeded(); return assertionError; }

Target:
public AssertionError failure(AssertionInfo info, ErrorMessageFactory messageFactory) { AssertionError error = failureIfErrorMessageIsOverridden(info); if (error != null) return error; String assertionErrorMessage = assertionErrorMessage(info, messageFactory); AssertionError assertionError = assertionErrorCreator.assertionError(assertionErrorMessage); removeAssertJRelatedElementsFromStackTraceIfNeeded(assertionError); printThreadDumpIfNeeded(); return assertionError; }
Source:
public static void beforeClass() throws Exception { KieModuleModel module = services.newKieModuleModel(); KieBaseModel base = module.newKieBaseModel(KIE_BASE_NAME); base.setEventProcessingMode(EventProcessingOption.STREAM); KieFileSystem fs = services.newKieFileSystem(); fs.generateAndWritePomXML(releaseId); fs.write(services.getResources() .newClassPathResource(DRL_FILE_NAME, DroolsGcCausesNPETest.class)); fs.writeKModuleXML(module.toXML()); KieBuilder builder = services.newKieBuilder(fs); List<Message> errors = builder.buildAll().getResults() .getMessages(Message.Level.ERROR); if (errors.size() > 0) { Assertions.fail("unexpected errors building drl: " + errors); } services.getRepository().addKieModule(builder.getKieModule()); }

Target:
public static void beforeClass() throws Exception { final KieModuleModel module = SERVICES.newKieModuleModel(); final KieBaseModel base = module.newKieBaseModel(KIE_BASE_NAME); base.setEventProcessingMode(EventProcessingOption.STREAM); final KieFileSystem fs = SERVICES.newKieFileSystem(); fs.generateAndWritePomXML(RELEASE_ID); fs.write(SERVICES.getResources() .newClassPathResource(DRL_FILE_NAME, DroolsGcCausesNPETest.class)); fs.writeKModuleXML(module.toXML()); final KieBuilder builder = SERVICES.newKieBuilder(fs); final List<Message> errors = builder.buildAll().getResults() .getMessages(Message.Level.ERROR); Assertions.assertThat(errors).as("Unexpected errors building drl: " + errors).isEmpty(); SERVICES.getRepository().addKieModule(builder.getKieModule()); }
Source:
private String createMessage(String invalidAttribute, Set<String> sourceIds) { return String.format( "The field \"%s\" is not supported by the %s Content Store(s)", invalidAttribute, prettyPrintSources(sourceIds)); }

Target:
private String createMessage(String invalidAttribute, Set<String> sourceIds) { String messageFormat = messageFormatSupplier.get(); return messageFormat .replace("{attribute}", invalidAttribute) .replace("{sources}", prettyPrintSources(sourceIds)); }
Source:
protected Address getAddress() { if (isLocalOnly) { return cache.getCacheManager().getAddress(); } else { return cache.getRpcManager().getAddress(); } }

Target:
protected Address getAddress() { return clusteringDependentLogic.getAddress(); }
Source:
protected Set<Object> extractFromAttribute(Object attributeValue) { final String value = attributeValue != null ? attributeValue.toString() : null; if (value == null) { return new HashSet<>(); } else { final String[] valueSplit = value.split(separator); return Stream.of(valueSplit) .map(StringUtils::trim) .filter(StringUtils::isNotEmpty) .collect(Collectors.toSet()); } }

Target:
protected Set<Object> extractFromAttribute(Object attributeValue) { if (attributeValue == null) { return Collections.emptySet(); } else { final String[] valueSplit = attributeValue.toString().split(separator); return Stream.of(valueSplit) .map(StringUtils::trim) .filter(StringUtils::isNotEmpty) .collect(Collectors.toSet()); } }
Source:
private static Config loadNeo4jConfig( Path homeDir, Path configDir, String databaseName ) { return Config.fromFile( configDir.resolve( "neo4j.conf" ) ) .withHome( homeDir ) .withSetting( DatabaseManagementSystemSettings.active_database, databaseName ) .withConnectorsDisabled().build(); }

Target:
private static Config loadNeo4jConfig( Path homeDir, Path configDir, String databaseName ) { return Config.fromFile( configDir.resolve( Config.DEFAULT_CONFIG_FILE_NAME ) ) .withHome( homeDir ) .withSetting( DatabaseManagementSystemSettings.active_database, databaseName ) .withConnectorsDisabled().build(); }
Source:
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); sendMessage(message); final IterableStream<ServiceBusReceivedMessage> messageIte = receiver.receive(1, TIMEOUT); Assertions.assertNotNull(messageIte); final List<ServiceBusReceivedMessage> asList = messageIte.stream().collect(Collectors.toList()); ServiceBusReceivedMessage receivedMessage = asList.get(0); assertNotNull(receivedMessage); ServiceBusReceivedMessage receivedPeekMessage = receiver.peekAt(receivedMessage.getSequenceNumber()); assertMessageEquals(receivedPeekMessage, messageId, isSessionEnabled); }

Target:
void peekFromSequenceNumberMessage(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = getMessage(messageId, isSessionEnabled); final int maxMessages = 1; sendMessage(message); final IterableStream<ServiceBusReceivedMessage> messages = receiver.receive(maxMessages, TIMEOUT); Assertions.assertNotNull(messages); final List<ServiceBusReceivedMessage> asList = messages.stream().collect(Collectors.toList()); assertEquals(maxMessages, asList.size()); final ServiceBusReceivedMessage receivedMessage = asList.get(0); assertNotNull(receivedMessage); ServiceBusReceivedMessage receivedPeekMessage = receiver.peekAt(receivedMessage.getSequenceNumber()); assertEquals(receivedMessage.getSequenceNumber(), receivedPeekMessage.getSequenceNumber()); assertMessageEquals(receivedPeekMessage, messageId, isSessionEnabled); }
Source:
public void createTwiceDifferentMetadata() { Map<String, String> metadata = new HashMap<>(); metadata.put("metadata1", "value1"); metadata.put("metadata2", "value2"); TestHelpers.assertResponseStatusCode(client.create(), 201); try { client.create(metadata); fail("Creating a queue twice with different metadata values should throw an exception."); } catch (Exception exception) { TestHelpers.assertExceptionStatusCode(exception, 409); } }

Target:
public void createTwiceDifferentMetadata() { Map<String, String> metadata = new HashMap<>(); metadata.put("metadata1", "value1"); metadata.put("metadata2", "value2"); helper.assertResponseStatusCode(client.create(), 201); try { client.create(metadata); fail("Creating a queue twice with different metadata values should throw an exception."); } catch (Exception exception) { helper.assertExceptionStatusCode(exception, 409); } }
Source:
public void test() { final Object[][] parameters = (Object[][]) data().toArray(); try { startKillStartScheduler(); long recovered = numberOfJobsRecovered(); final long timeSpent = timeSpentToRecoverJobs(); LOGGER.info(BaseRecoveryTest.makeCSVString("JobRecoveryTest", jobsNumber, timeLimit, recovered, timeSpent, ((timeSpent < timeLimit) ? SUCCESS : "FAILURE"))); final Integer numberOfJobsOfLastTestCase = (Integer) parameters[parameters.length - 1][0]; if (jobsNumber == numberOfJobsOfLastTestCase) { LOGGER.info(BaseRecoveryTest.makeCSVString("JobRecoveryTestWithNodes", jobsNumber, timeLimit, jobsNumber, timeSpentToRecoverNodesAndJobs(), SUCCESS)); } assertEquals(jobsNumber, recovered); assertThat("Jobs recovery time for " + jobsNumber + " jobs", (int) timeSpent, lessThan(timeLimit)); } catch (Exception e) { e.printStackTrace(); LOGGER.info(BaseRecoveryTest.makeCSVString("JobRecoveryTest", jobsNumber, timeLimit, -1, -1, "ERROR")); } }

Target:
public void test() { final Object[][] parameters = (Object[][]) data().toArray(); try { startKillStartScheduler(); long recovered = numberOfJobsRecovered(); final long timeSpent = timeSpentToRecoverJobs(); LOGGER.info(BaseRecoveryTest.makeCSVString("JobRecoveryTest", jobsNumber, timeLimit, recovered, timeSpent, ((timeSpent < timeLimit) ? SUCCESS : FAILURE))); final Integer numberOfJobsOfLastTestCase = (Integer) parameters[parameters.length - 1][0]; if (jobsNumber == numberOfJobsOfLastTestCase) { LOGGER.info(BaseRecoveryTest.makeCSVString("JobRecoveryTestWithNodes", jobsNumber, timeLimit, jobsNumber, timeSpentToRecoverNodesAndJobs(), SUCCESS)); } assertEquals(jobsNumber, recovered); assertThat("Jobs recovery time for " + jobsNumber + " jobs", (int) timeSpent, lessThan(timeLimit)); } catch (Exception e) { e.printStackTrace(); LOGGER.info(BaseRecoveryTest.makeCSVString("JobRecoveryTest", jobsNumber, timeLimit, -1, -1, ERROR)); } }
Source:
private Stream<String> getAllBundleIds(final List<Status> statusList, final String userId, final boolean isAdmin) throws IOException { return this.getBundleIds( (Integer limit, Integer offset) -> { try { return isAdmin? this.publishAuditAPI.getBundleIdByStatus(statusList, limit, offset) : this.publishAuditAPI.getBundleIdByStatusFilterByOwner(statusList, limit, offset, userId); } catch (DotDataException e) { throw new DotRuntimeException(e); } }, (String bundleId) -> bundleId ); }

Target:
private Stream<String> getAllBundleIds(final List<Status> statusList, final String userId, final boolean isAdmin) throws IOException { return this.getBundleIds( (Integer limit, Integer offset) -> { try { return isAdmin? this.publishAuditAPI.getBundleIdByStatus(statusList, limit, offset) : this.publishAuditAPI.getBundleIdByStatusFilterByOwner(statusList, limit, offset, userId); } catch (DotDataException e) { Logger.error(this, "Error getting all bundles with statuses: " + statusList.toString() + "by the user: " + userId,e); throw new DotRuntimeException(e); } }, (String bundleId) -> bundleId ); }
Source:
public Response listJournalEntryComments(@PathParam("WORKSPACEID") Long workspaceEntityId, @PathParam("JOURNALENTRYID") Long journalEntryId) { WorkspaceEntity workspaceEntity = workspaceController.findWorkspaceEntityById(workspaceEntityId); if (workspaceEntity == null) { return Response.status(Status.NOT_FOUND).build(); } WorkspaceJournalEntry journalEntry = workspaceJournalController.findJournalEntry(journalEntryId); if (journalEntry == null) { return Response.status(Status.NOT_FOUND).build(); } if (!sessionController.hasWorkspacePermission(MuikkuPermissions.ACCESS_WORKSPACE_JOURNAL, workspaceEntity)) { return Response.status(Status.FORBIDDEN).build(); } List<WorkspaceJournalComment> comments = orderCommentTree(workspaceJournalController.listCommentsByJournalEntry(journalEntry)); List<WorkspaceJournalCommentRESTModel> result = new ArrayList<>(); for (WorkspaceJournalComment comment : comments) { result.add(toRestModel(workspaceEntity, comment)); } return Response.ok(result).build(); }

Target:
public Response listJournalEntryComments(@PathParam("WORKSPACEID") Long workspaceEntityId, @PathParam("JOURNALENTRYID") Long journalEntryId) { WorkspaceEntity workspaceEntity = workspaceController.findWorkspaceEntityById(workspaceEntityId); if (workspaceEntity == null) { return Response.status(Status.NOT_FOUND).build(); } WorkspaceJournalEntry journalEntry = workspaceJournalController.findJournalEntry(journalEntryId); if (journalEntry == null) { return Response.status(Status.NOT_FOUND).build(); } if (!sessionController.hasWorkspacePermission(MuikkuPermissions.LIST_WORKSPACE_JOURNAL_COMMENTS, workspaceEntity)) { if (!journalEntry.getUserEntityId().equals(sessionController.getLoggedUserEntity().getId())) { return Response.status(Status.FORBIDDEN).build(); } } List<WorkspaceJournalComment> comments = orderCommentTree(workspaceJournalController.listCommentsByJournalEntry(journalEntry)); List<WorkspaceJournalCommentRESTModel> result = new ArrayList<>(); for (WorkspaceJournalComment comment : comments) { result.add(toRestModel(workspaceEntity, comment)); } return Response.ok(result).build(); }
Source:
private static void execute(File f) { if (!f.exists()) { fail("Config file " + f.getPath() + " doesn't exist"); } final String jbossDist = TestSuiteEnvironment.getSystemProperty("jboss.dist"); if (jbossDist == null) { fail("jboss.dist system property is not set"); } final CliCommandBuilder commandBuilder = CliCommandBuilder.of(jbossDist); commandBuilder.addJavaOptions("-Djboss.cli.config=" + f.toPath()); commandBuilder.addCliArgument("--command=help"); Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .setRedirectErrorStream(true) .launch(); cliProc.waitFor(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException | IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } if (cliProc.exitValue() != 0) { fail("Cli process failed with exit code " + cliProc.exitValue()); } }

Target:
private static void execute(File f) { if (!f.exists()) { fail("Config file " + f.getPath() + " doesn't exist"); } final String jbossDist = TestSuiteEnvironment.getSystemProperty("jboss.dist"); if (jbossDist == null) { fail("jboss.dist system property is not set"); } final CliCommandBuilder commandBuilder = CliCommandBuilder.of(jbossDist); commandBuilder.addJavaOptions("-Djboss.cli.config=" + f.toPath()); commandBuilder.addCliArgument("--command=help"); Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .setRedirectErrorStream(true) .launch(); flushInStream(cliProc.getInputStream()); cliProc.waitFor(TimeoutUtil.adjust(10000), TimeUnit.MILLISECONDS); } catch (InterruptedException | IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } if (cliProc.exitValue() != 0) { fail("Cli process failed with exit code " + cliProc.exitValue()); } }