auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void initialize(URL location, ResourceBundle resources) { treeViewWrapper = new TreeViewWrapper<>(astTreeView); astTreeView.setCellFactory(treeView -> new ASTTreeCell(parent)); languageVersionProperty().values() .filterMap(Objects::nonNull, LanguageVersion::getLanguage) .distinct() .subscribe(this::updateSyntaxHighlighter); EventStreams.valuesOf(astTreeView.getSelectionModel().selectedItemProperty()) .filterMap(Objects::nonNull, TreeItem::getValue) .subscribe(parent::onNodeItemSelected); codeEditorArea.richChanges() .filter(t -> !t.getInserted().equals(t.getRemoved())) .successionEnds(Duration.ofMillis(100)) .subscribe(richChange -> parent.onRefreshASTClicked()); codeEditorArea.setParagraphGraphicFactory(LineNumberFactory.get(codeEditorArea)); }

Target:
public void initialize(URL location, ResourceBundle resources) { treeViewWrapper = new TreeViewWrapper<>(astTreeView); astTreeView.setCellFactory(treeView -> new ASTTreeCell(parent)); languageVersionProperty().values() .filterMap(Objects::nonNull, LanguageVersion::getLanguage) .distinct() .subscribe(this::updateSyntaxHighlighter); EventStreams.valuesOf(astTreeView.getSelectionModel().selectedItemProperty()) .filterMap(Objects::nonNull, TreeItem::getValue) .subscribe(parent::onNodeItemSelected); codeEditorArea.richChanges() .filter(t -> !t.getInserted().equals(t.getRemoved())) .successionEnds(CODE_EDITOR_REFRESH) .subscribe(richChange -> parent.refreshAST()); codeEditorArea.setParagraphGraphicFactory(LineNumberFactory.get(codeEditorArea)); }
Source:
public ViewerActionContext<? extends Viewer> getActionContext() { return actionContext; }

Target:
protected ViewerActionContext<? extends Viewer> getActionContext() { return actionContext; }
Source:
public void addIndexerToCorfuTableStream(String streamName, IndexRegistry indexRegistry) { UUID streamId = CorfuRuntime.getStreamID(streamName); SMRObject.Builder ob = SMRObject.builder() .runtime(runtime) .setType(CorfuTable.class) .setArguments(indexRegistry) .setStreamID(streamId); addCustomTypeStream(streamId, ob); }

Target:
public void addIndexerToCorfuTableStream(String streamName, IndexRegistry indexRegistry) { UUID streamId = CorfuRuntime.getStreamID(streamName); Builder ob = SMRObject.builder() .runtime(runtime) .setType(CorfuTable.class) .setArguments(indexRegistry) .setStreamID(streamId); addCustomTypeStream(streamId, ob); }
Source:
private void init() { fields = new ArrayList<Field>(); List<String> headers = new ArrayList<String>(); List<Integer> fieldWidth = new ArrayList<Integer>(); for (String tmp : fieldDescription.split(",")) { String[] fieldTuple = tmp.split(":(?=([^\"]*\"[^\"]*\")*[^\"]*$)", -1); Field field = new Field(); field.setName(fieldTuple[0]); field.setType(fieldTuple[1]); headers.add(fieldTuple[0]); fieldWidth.add(Integer.parseInt(fieldTuple[2])); if (field.getType() == FIELD_TYPE.DATE) { if (fieldTuple.length > 3) { fieldDateFormat.put(field.getName(), fieldTuple[3].replace("\"", "")); } else { logger.error("Date format is missing for the field {}", field.getName()); throw new RuntimeException("Missing date format"); } } fields.add(field); } header = headers.toArray(new String[headers.size()]); width = Ints.toArray(fieldWidth); FixedWidthFieldLengths lengths = new FixedWidthFieldLengths(header, width); FixedWidthParserSettings settings = new FixedWidthParserSettings(lengths); settings.getFormat().setPadding(this.padding); fixedWidthParser = new FixedWidthParser(settings); }

Target:
private void init() { fields = new ArrayList<FixedWidthField>(); List<String> headers = new ArrayList<String>(); List<Integer> fieldWidth = new ArrayList<Integer>(); for (String tmp : fieldDescription.split(",")) { String[] fieldTuple = tmp.split(":(?=([^\"]*\"[^\"]*\")*[^\"]*$)", -1); FixedWidthField field = new FixedWidthField(); field.setName(fieldTuple[0]); field.setType(fieldTuple[1]); field.setWidth(Integer.parseInt(fieldTuple[2])); headers.add(fieldTuple[0]); fieldWidth.add(Integer.parseInt(fieldTuple[2])); if (field.getType() == FIELD_TYPE.DATE) { if (fieldTuple.length > 3) { field.setDateFormat(fieldTuple[3].replace("\"", "")); } else { logger.error("Date format is missing for the field {}", field.getName()); throw new RuntimeException("Missing date format"); } } fields.add(field); } header = headers.toArray(new String[headers.size()]); int[] width = Ints.toArray(fieldWidth); FixedWidthFields lengths = new FixedWidthFields(header, width); FixedWidthParserSettings settings = new FixedWidthParserSettings(lengths); settings.getFormat().setPadding(this.padding); fixedWidthParser = new FixedWidthParser(settings); }
Source:
public static Predicate<Object> isStringStartingWith(final String prefix) { return Predicates.<Object>and(Predicates.instanceOf(CharSequence.class), Predicates.compose(new StartsWith<String>(prefix), StringFunctions.toStringFunction())); }

Target:
public static Predicate<Object> isStringStartingWith(final String prefix) { return Predicates.<Object>and(Predicates.instanceOf(CharSequence.class), Predicates.compose(startsWith(prefix), StringFunctions.toStringFunction())); }
Source:
public Response processStats(BatchedOperatorStats stats) { Response response = new Response(); response.repartitionRequired = false; if (!partitionedInstanceStatus.containsKey(stats.getOperatorId())) { return response; } partitionedInstanceStatus.put(stats.getOperatorId(), stats); if (getLoad(stats) != 0) { logger.debug("repartition{}, currentTimeMillis {}, nextMillis {}, diff{}", repartition, System.currentTimeMillis(), nextMillis, nextMillis - System.currentTimeMillis()); if (repartition && System.currentTimeMillis() > nextMillis) { repartition = false; logger.debug("AAAAAAAAAAAAA"); response.repartitionRequired = true; logger.debug("setting repartition to true"); } else if (!repartition) { repartition = true; logger.debug("BBBBBBBBBB"); nextMillis = System.currentTimeMillis() + cooldownMillis; } } else { repartition = false; } return response; }

Target:
public Response processStats(BatchedOperatorStats stats) { Response response = new Response(); response.repartitionRequired = false; if (!partitionedInstanceStatus.containsKey(stats.getOperatorId())) { return response; } partitionedInstanceStatus.put(stats.getOperatorId(), stats); if (getLoad(stats) != 0) { if (repartition && System.currentTimeMillis() > nextMillis) { repartition = false; response.repartitionRequired = true; logger.debug("setting repartition to true"); } else if (!repartition) { repartition = true; nextMillis = System.currentTimeMillis() + cooldownMillis; } } else { repartition = false; } return response; }
Source:
public void testEnableTetheringPermission() throws Exception { if (!mTM.isTetheringSupported()) return; final TestTetheringEventCallback tetherEventCallback = new TestTetheringEventCallback(); mTM.registerTetheringEventCallback(c -> c.run(), tetherEventCallback); tetherEventCallback.expectCallbackStarted(); final TestSoftApCallback softApCallback = new TestSoftApCallback(); mWm.registerSoftApCallback(c -> c.run(), softApCallback); final StartTetheringCallback wifiCallback = new StartTetheringCallback(); mTM.startTethering(new TetheringRequest.Builder(TETHERING_WIFI).build(), c -> c.run(), wifiCallback); wifiCallback.verifyTetheringStarted(); PollingCheck.check( "No WIFI_AP_STATE_ENABLED state change", 5_000, () -> { return softApCallback.expectSoftApState(WifiManager.WIFI_AP_STATE_ENABLED); }); mTM.stopAllTethering(); PollingCheck.check( "No WIFI_AP_STATE_DISABLED state change", 5_000, () -> { return softApCallback.expectSoftApState(WifiManager.WIFI_AP_STATE_DISABLED); }); mTM.unregisterTetheringEventCallback(tetherEventCallback); mUiAutomation.dropShellPermissionIdentity(); mTM.startTethering(new TetheringRequest.Builder(TETHERING_WIFI).build(), c -> c.run(), wifiCallback); wifiCallback.expectTetheringFailed(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION); }

Target:
public void testEnableTetheringPermission() throws Exception { if (!mTM.isTetheringSupported()) return; final TestTetheringEventCallback tetherEventCallback = new TestTetheringEventCallback(); mTM.registerTetheringEventCallback(c -> c.run(), tetherEventCallback); tetherEventCallback.expectCallbackStarted(); final TestSoftApCallback softApCallback = new TestSoftApCallback(); mWm.registerSoftApCallback(c -> c.run(), softApCallback); final StartTetheringCallback wifiCallback = new StartTetheringCallback(); mTM.startTethering(new TetheringRequest.Builder(TETHERING_WIFI).build(), c -> c.run(), wifiCallback); wifiCallback.verifyTetheringStarted(); softApCallback.expectSoftApState(WifiManager.WIFI_AP_STATE_ENABLED, DEFAULT_TIMEOUT_MS); mTM.stopAllTethering(); softApCallback.expectSoftApState(WifiManager.WIFI_AP_STATE_DISABLED, DEFAULT_TIMEOUT_MS); mTM.unregisterTetheringEventCallback(tetherEventCallback); mUiAutomation.dropShellPermissionIdentity(); mTM.startTethering(new TetheringRequest.Builder(TETHERING_WIFI).build(), c -> c.run(), wifiCallback); wifiCallback.expectTetheringFailed(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION); }
Source:
private void merge(Map<String, StageState> files, boolean showPrompt, String toolNamePrompt) throws Exception { List<String> fileNames = new ArrayList<>(files.keySet()); Collections.sort(fileNames); outw.println("Merging:"); for (String fileName : fileNames) { outw.println(fileName); } for (String fileName : fileNames) { StageState fileState = files.get(fileName); if (fileState == StageState.BOTH_MODIFIED) { outw.println("\nNormal merge conflict for '" + fileName + "':"); outw.println(" {local}: modified file"); outw.println(" {remote}: modified file"); boolean launch = true; if (showPrompt) { launch = isLaunch(toolNamePrompt); } if (launch) { outw.println("TODO: Launch mergetool '" + toolNamePrompt + "' for path '" + fileName + "'..."); } else { break; } } else if ((fileState == StageState.DELETED_BY_US) || (fileState == StageState.DELETED_BY_THEM)) { outw.println("\nDeleted merge conflict for '" + fileName + "':"); } else { outw.println( "\nUnknown merge conflict for '" + fileName + "':"); break; } } }

Target:
private void merge(Map<String, StageState> files, boolean showPrompt, String toolNamePrompt) throws Exception { List<String> fileNames = new ArrayList<>(files.keySet()); Collections.sort(fileNames); outw.println("Merging:"); for (String fileName : fileNames) { outw.println(fileName); } outw.flush(); for (String fileName : fileNames) { StageState fileState = files.get(fileName); if (fileState == StageState.BOTH_MODIFIED) { outw.println("\nNormal merge conflict for '" + fileName + "':"); outw.println(" {local}: modified file"); outw.println(" {remote}: modified file"); boolean launch = true; if (showPrompt) { launch = isLaunch(toolNamePrompt); } if (launch) { outw.println("TODO: Launch mergetool '" + toolNamePrompt + "' for path '" + fileName + "'..."); } else { break; } } else if ((fileState == StageState.DELETED_BY_US) || (fileState == StageState.DELETED_BY_THEM)) { outw.println("\nDeleted merge conflict for '" + fileName + "':"); } else { outw.println( "\nUnknown merge conflict for '" + fileName + "':"); break; } } }
Source:
protected String appendHash(String name, String toBeHashed) { return Joiner.on("").join(name, DELIMITER, DigestUtils.md5DigestAsHex(toBeHashed.getBytes()).substring(0, DATE_FORMAT.length())); }

Target:
protected String appendHash(String name, String toBeHashed) { return appendHash(name, toBeHashed, getDefaultHashLength()); }
Source:
public void revertFile() throws IOException { OutputStream fileOutputStream = Files.newOutputStream(Paths.get(pathOfOldMetaFormat)); fileOutputStream.write(testMetaOldFormat); fileOutputStream.close(); fileOutputStream = Files.newOutputStream( Paths.get("src/test/resources/testmetaUnsupportedFormat.xml")); fileOutputStream.write(testmetaUnsupportedFormat); fileOutputStream.close(); }

Target:
public void revertFile() throws IOException { IOUtils.write( testMetaOldFormat, Files.newOutputStream(Paths.get(pathOfOldMetaFormat))); IOUtils.write( testmetaUnsupportedFormat, Files.newOutputStream(Paths.get("src/test/resources/testmetaUnsupportedFormat.xml"))); }
Source:
public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format("Can not return data for a " + "message which is of type %s.", getBodyType().toString()))); } return new IterableStream<>(Collections.singletonList(data)); }

Target:
public IterableStream<byte[]> getData() { if (bodyType != AmqpMessageBodyType.DATA) { throw logger.logExceptionAsError(new IllegalArgumentException( "This method can only be called for AMQP Data body type at present. Track this issue, " + "<LINK_0> for other body type support in " + "future.")); } if (dataList == null) { dataList = Collections.singletonList(data); } return new IterableStream<>(dataList); }
Source:
public SecureBoot(SystemService systemService) { this.systemService = systemService; try { ddfHome = getDdfHome(); userHome = getUserHome(); } catch (IOException e) { String message = "Unable to determine if your installation [" + ddfHome + "] is located in an insecure directory. See log for details. Shutting down..."; System.err.println("\n" + message + "\n"); LOGGER.error(message, e); shutdown(); } }

Target:
public SecureBoot(SystemService systemService) { this.systemService = systemService; ddfHome = getDdfHome(); userHome = getUserHome(); }
Source:
public Page<TaskInfo> getTasks(final long from, final long to, final String tag, final int offset, final int limit, final String user, final boolean pending, final boolean running, final boolean finished) { DBTaskDataParameters parameters = new DBTaskDataParameters(tag, from, to, offset, limit, user, pending, running, finished, new SortSpecifierContainer()); int totalNbTasks = getTotalNumberOfTasks(parameters); List<TaskInfo> lTaskInfo = runWithoutTransaction(TaskDBUtils.taskInfoSessionWork(parameters)); return new Page<TaskInfo>(lTaskInfo, totalNbTasks); }

Target:
public Page<TaskInfo> getTasks(final long from, final long to, final String tag, final int offset, final int limit, final String user, final boolean pending, final boolean running, final boolean finished) { DBTaskDataParameters parameters = new DBTaskDataParameters(tag, from, to, offset, limit, user, pending, running, finished, SortSpecifierContainer.EMPTY_CONTAINER); int totalNbTasks = getTotalNumberOfTasks(parameters); List<TaskInfo> lTaskInfo = runWithoutTransaction(TaskDBUtils.taskInfoSessionWork(parameters)); return new Page<TaskInfo>(lTaskInfo, totalNbTasks); }
Source:
public void init(TransactionManager transactionManager) { successfullyInvoked = transactionManager.getKeyValueServiceStatus() == KeyValueServiceStatus.HEALTHY_ALL_OPERATIONS; while (block) { try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } } }

Target:
public void init(TransactionManager transactionManager) { successfullyInvoked = transactionManager.getKeyValueServiceStatus() == KeyValueServiceStatus.HEALTHY_ALL_OPERATIONS; while (block) { try { Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } }
Source:
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION: if (PermissionUtil.isPermitted(grantResults)) { WikipediaApp.getInstance().getBus().post(new GrantStoragePermissionEvent()); searchOfflineCompilations(true); } else { L.i("Write permission was denied by user"); onOfflineCompilationsError(new RuntimeException(getString(R.string.offline_read_permission_error))); if (PermissionUtil.shouldShowWritePermissionRationale(this)) { showStoragePermissionSnackbar(); } else { showAppSettingSnackbar(); } } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }

Target:
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case Constants.ACTIVITY_REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION: if (PermissionUtil.isPermitted(grantResults)) { searchOfflineCompilations(true); } else { L.i("Write permission was denied by user"); onOfflineCompilationsError(new RuntimeException(getString(R.string.offline_read_permission_error))); if (PermissionUtil.shouldShowWritePermissionRationale(this)) { showStoragePermissionSnackbar(); } else { showAppSettingSnackbar(); } } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
Source:
private Transaction registerTransaction(int txId, int status, String name, long logId, RollbackListener listener) { int transactionId; long sequenceNo; boolean success; do { VersionedBitSet original = openTransactions.get(); if (txId == 0) { transactionId = original.nextClearBit(1); } else { transactionId = txId; assert !original.get(transactionId); } if (transactionId > maxTransactionId) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_TOO_MANY_OPEN_TRANSACTIONS, "There are {0} open transactions", transactionId - 1); } VersionedBitSet clone = original.cloneIt(); clone.set(transactionId); sequenceNo = clone.getVersion() + 1; clone.setVersion(sequenceNo); success = openTransactions.compareAndSet(original, clone); } while(!success); Transaction transaction = new Transaction(this, transactionId, sequenceNo, status, name, logId, listener); success = transactions.compareAndSet(transactionId, null, transaction); assert success; return transaction; }

Target:
private Transaction registerTransaction(int txId, int status, String name, long logId, RollbackListener listener) { int transactionId; long sequenceNo; boolean success; do { VersionedBitSet original = openTransactions.get(); if (txId == 0) { transactionId = original.nextClearBit(1); } else { transactionId = txId; assert !original.get(transactionId); } if (transactionId > maxTransactionId) { throw DataUtils.newIllegalStateException( DataUtils.ERROR_TOO_MANY_OPEN_TRANSACTIONS, "There are {0} open transactions", transactionId - 1); } VersionedBitSet clone = original.clone(); clone.set(transactionId); sequenceNo = clone.getVersion() + 1; clone.setVersion(sequenceNo); success = openTransactions.compareAndSet(original, clone); } while(!success); Transaction transaction = new Transaction(this, transactionId, sequenceNo, status, name, logId, listener); assert transactions.get(transactionId) == null; transactions.set(transactionId, transaction); return transaction; }
Source:
public String xpath() { XStreamDOM child = node.children.get(pos - 1); int count =0; for (int i=0; i<pos-1; i++) if (node.children.get(i).tagName.equals(child.tagName)) count++; boolean more = false; for (int i=pos; !more && i<node.children.size(); i++) if (node.children.get(i).tagName.equals(child.tagName)) { more = true; break; } if (count==0 && !more) return child.tagName; return child.tagName+'['+count+']'; }

Target:
public String xpath() { XStreamDOM child = node.children.get(pos - 1); int count =0; for (int i=0; i<pos-1; i++) if (node.children.get(i).tagName.equals(child.tagName)) count++; boolean more = false; for (int i=pos; !more && i<node.children.size(); i++) if (node.children.get(i).tagName.equals(child.tagName)) more = true; if (count==0 && !more) return child.tagName; return child.tagName+'['+count+']'; }
Source:
public OAuth20Profile extractUserProfile(final String body) { final OAuth20Profile profile = new OAuth20Profile(); final JsonNode json = JsonHelper.getFirstNode(body, getFirstNodePath()); if (json != null) { if (profileId != null) profile.setId(ProfileHelper.sanitizeIdentifier(profile, JsonHelper.getElement(json, profileId))); for (final String attribute : getPrimaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final String attribute : getSecondaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final Map.Entry<String, String> entry : getProfileAttributes().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); convertAndAdd(profile, key, JsonHelper.getElement(json, value)); } } return profile; }

Target:
public OAuth20Profile extractUserProfile(final String body) { final OAuth20Profile profile = new OAuth20Profile(); final JsonNode json = JsonHelper.getFirstNode(body, getFirstNodePath()); if (json != null) { if (profileId != null) { profile.setId(ProfileHelper.sanitizeIdentifier(profile, JsonHelper.getElement(json, profileId))); } for (final String attribute : getPrimaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final String attribute : getSecondaryAttributes()) { convertAndAdd(profile, attribute, JsonHelper.getElement(json, attribute)); } for (final Map.Entry<String, String> entry : getProfileAttributes().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); convertAndAdd(profile, key, JsonHelper.getElement(json, value)); } } return profile; }
Source:
public void enableStats(boolean statsEnabled) { if (statsEnabled) { this.countsEnabled = true; } this.statsEnabled = statsEnabled; if (this.channelMetrics != null) { this.channelMetrics.setFullStatsEnabled(statsEnabled); } }

Target:
public void enableStats(boolean statsEnabled) { if (statsEnabled) { this.countsEnabled = true; } this.statsEnabled = statsEnabled; this.channelMetrics.setFullStatsEnabled(statsEnabled); }
Source:
private void increaseWriteIndex() { if (curWriteIndex == maxSlotNum - 1) { final long startLoopAt = System.currentTimeMillis(); while ((nextReadIndex == -1 || nextReadIndex == 0) && !Thread.interrupted()) { if (System.currentTimeMillis() - startLoopAt > timeoutMs) { throw new RuntimeException(new TimeoutException()); } } curWriteIndex = 0; } else { final int nextWriteIndex = curWriteIndex + 1; final long startLoopAt = System.currentTimeMillis(); while ((nextWriteIndex == nextReadIndex) && !Thread.interrupted()) { if (System.currentTimeMillis() - startLoopAt > timeoutMs) { throw new RuntimeException(new TimeoutException()); } } curWriteIndex = nextWriteIndex; } }

Target:
private void increaseWriteIndex() { final long startAtNs = System.nanoTime(); final long queryTimeoutAtNs = getQueryTimeoutAtNs(startAtNs); final long spinTimeoutAtNs = startAtNs + SPIN_FOR_TIMEOUT_THRESHOLD_NS; long timeoutNs = queryTimeoutAtNs - startAtNs; long spinTimeoutNs = SPIN_FOR_TIMEOUT_THRESHOLD_NS; if (curWriteIndex == maxNumSlots - 1) { while ((nextReadIndex == -1 || nextReadIndex == 0) && !Thread.currentThread().isInterrupted()) { if (timeoutNs <= 0L) { throw new RuntimeException(new TimeoutException()); } if (spinTimeoutNs <= 0L) { Thread.yield(); } long now = System.nanoTime(); timeoutNs = queryTimeoutAtNs - now; spinTimeoutNs = spinTimeoutAtNs - now; } curWriteIndex = 0; } else { final int nextWriteIndex = curWriteIndex + 1; while ((nextWriteIndex == nextReadIndex) && !Thread.currentThread().isInterrupted()) { if (timeoutNs <= 0L) { throw new RuntimeException(new TimeoutException()); } if (spinTimeoutNs <= 0L) { Thread.yield(); } long now = System.nanoTime(); timeoutNs = queryTimeoutAtNs - now; spinTimeoutNs = spinTimeoutAtNs - now; } curWriteIndex = nextWriteIndex; } }
Source:
public void setBossBar(ServerBossBar bossBar) { this.shadow$bossInfo = (ServerBossInfo) bossBar; }

Target:
public void setBossBar(ServerBossBar bossBar) { checkNotNull(bossBar, "BossBar cannot be null."); this.bossInfo = (ServerBossInfo) bossBar; }
Source:
public static String primitiveToString(Object x) throws IOException { if (x != null) { if (x instanceof String) return (String)x; else if (x instanceof Boolean) return String.valueOf(x); else if (x instanceof Integer) return String.valueOf(x); else if (x instanceof Long) return String.valueOf(x); else if (x instanceof Float) return String.valueOf(x); else if (x instanceof Byte) return Byte.toString((Byte)x); else if (x instanceof Short) return Short.toString((Short)x); else if (x instanceof Double) return String.valueOf(x); else if (x instanceof BigDecimal) return ((BigDecimal)x).toString(); else if (x instanceof byte[]) return new String((byte[])x, StandardCharsets.UTF_8); else if (x instanceof Time) return ((Time)x).toString(); else if (x instanceof java.sql.Date) return ((java.sql.Date)x).toString(); else if (x instanceof Timestamp) return ((Timestamp)x).toString(); else if (x instanceof InputStream) { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = ((InputStream)x).read(buffer)) != -1) { result.write(buffer, 0, length); } return result.toString("UTF-8"); } else return (String)x; } else return null; }

Target:
public static String primitiveToString(Object x) throws IOException { if (x != null) { if (x instanceof String) return (String)x; else if (x instanceof Boolean) return String.valueOf(x); else if (x instanceof Integer) return String.valueOf(x); else if (x instanceof Long) return String.valueOf(x); else if (x instanceof Float) return String.valueOf(x); else if (x instanceof Byte) return Byte.toString((Byte)x); else if (x instanceof Short) return Short.toString((Short)x); else if (x instanceof Double) return String.valueOf(x); else if (x instanceof BigDecimal) return ((BigDecimal)x).toString(); else if (x instanceof byte[]) return new String((byte[])x, StandardCharsets.UTF_8); else if (x instanceof Time) return ((Time)x).toString(); else if (x instanceof java.sql.Date) return ((java.sql.Date)x).toString(); else if (x instanceof Timestamp) return ((Timestamp)x).toString(); else if (x instanceof InputStream) { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = ((InputStream)x).read(buffer)) != -1) { result.write(buffer, 0, length); if (length < buffer.length) break; } return result.toString("UTF-8"); } else return (String)x; } else return null; }
Source:
private int getMaxQueryComplexity(JSONObject policyDefinition) { Object complexityObject = policyDefinition.get(APIConstants.QUERY_ANALYSIS_COMPLEXITY); boolean complexityCheckEnabled = Boolean.parseBoolean(((JSONObject) complexityObject).get("enabled").toString()); if (complexityCheckEnabled) { Object maxQueryComplexity = ((JSONObject) complexityObject).get("max_query_complexity"); if (maxQueryComplexity != null) { return ((Long) maxQueryComplexity).intValue(); } else { log.error("Maximum query complexity was not allocated"); return -1; } } else { return -1; } }

Target:
private int getMaxQueryComplexity(JSONObject policyDefinition) { Object complexityObject = policyDefinition.get(APIConstants.QUERY_ANALYSIS_COMPLEXITY); boolean complexityCheckEnabled = Boolean.parseBoolean(((JSONObject) complexityObject) .get(APIConstants.CHECK_ENABLED).toString()); if (complexityCheckEnabled) { Object maxQueryComplexity = ((JSONObject) complexityObject).get(APIConstants.MAXIMUM_QUERY_COMPLEXITY); if (maxQueryComplexity != null) { return ((Long) maxQueryComplexity).intValue(); } else { log.error("Maximum query complexity was not allocated"); return -1; } } else { return -1; } }
Source:
public void test_DnDClassFromContainer2ContainerBlank5() throws Exception { test_DnDClassFromMC2ContainerBlank5(); try { openErrorLogViewByAPI(); SWTBot errorLogBot = bot.viewByTitle("Error Log").bot(); int rowCount = errorLogBot.tree().rowCount(); DndUtil util = new DndUtil(bot.getDisplay()); SWTBotGefEditPart p1Bot = editor.getEditPart(CONTAINER_TO_DRAG_P1).parent(); Point targetLocation = editor.getBounds(p1Bot).getLeft().getTranslated(-200, 0); final SWTBotTreeItem ecoreTreeItem = semanticResourceNode.expandNode(ROOTPACKAGE_NAME) .getNode(CONTAINER_TO_DRAG_P2); System.out.println("Cas2 --> \"P2\" = " + ecoreTreeItem.getText()); util.dragAndDrop(ecoreTreeItem, editor.getCanvas(), new org.eclipse.swt.graphics.Point(targetLocation.x, targetLocation.y)); bot.waitUntil(new DiagramWithChildrensCondition(editor, 2)); assertEquals("An error message was generated !", rowCount, errorLogBot.tree().rowCount()); SWTBotGefEditPart c1Bot = editor.getEditPart(CLASS_TO_DRAG_C1).parent(); Point c1Location = editor.getBounds(c1Bot).getLocation(); SWTBotGefEditPart targetSwtBotPart = editor.getEditPart(CONTAINER_TO_DRAG_P2, AbstractDiagramContainerEditPart.class); final IGraphicalEditPart targetPart = (IGraphicalEditPart) targetSwtBotPart.part(); Point targetCenter = targetPart.getFigure().getBounds().getCenter(); editor.drag(c1Location, targetCenter); assertEquals("An error message was generated !", rowCount, errorLogBot.tree().rowCount()); } finally { closeErrorLogView(); } }

Target:
public void test_DnDClassFromContainer2ContainerBlank5() throws Exception { test_DnDClassFromMC2ContainerBlank5(); try { openErrorLogViewByAPI(); SWTBot errorLogBot = bot.viewByTitle("Error Log").bot(); int rowCount = errorLogBot.tree().rowCount(); DndUtil util = new DndUtil(bot.getDisplay()); SWTBotGefEditPart p1Bot = editor.getEditPart(CONTAINER_TO_DRAG_P1).parent(); Point targetLocation = editor.getBounds(p1Bot).getLeft().getTranslated(-200, 0); final SWTBotTreeItem ecoreTreeItem = semanticResourceNode.expandNode(ROOTPACKAGE_NAME) .getNode(CONTAINER_TO_DRAG_P2); util.dragAndDrop(ecoreTreeItem, editor.getCanvas(), new org.eclipse.swt.graphics.Point(targetLocation.x, targetLocation.y)); bot.waitUntil(new DiagramWithChildrensCondition(editor, 2)); assertEquals("An error message was generated !", rowCount, errorLogBot.tree().rowCount()); SWTBotGefEditPart c1Bot = editor.getEditPart(CLASS_TO_DRAG_C1).parent(); Point c1Location = editor.getBounds(c1Bot).getLocation(); SWTBotGefEditPart targetSwtBotPart = editor.getEditPart(CONTAINER_TO_DRAG_P2, AbstractDiagramContainerEditPart.class); final IGraphicalEditPart targetPart = (IGraphicalEditPart) targetSwtBotPart.part(); Point targetCenter = targetPart.getFigure().getBounds().getCenter(); editor.drag(c1Location, targetCenter); assertEquals("An error message was generated !", rowCount, errorLogBot.tree().rowCount()); } finally { closeErrorLogView(); } }
Source:
void testPreCanUnlockResearchEvent() throws InterruptedException { SlimefunPlugin.getRegistry().setResearchingEnabled(true); NamespacedKey key = new NamespacedKey(plugin, "simple_research"); Research research = new Research(key, 250, "Test", 10); research.register(); SlimefunGuideImplementation guide = Mockito.mock(SlimefunGuideImplementation.class); Player player = server.addPlayer(); PlayerProfile profile = TestUtilities.awaitProfile(player); SlimefunItem sfItem = TestUtilities.mockSlimefunItem(plugin, "RESEARCH_TEST", new CustomItem(Material.TORCH, "&bResearch Test")); research.guideClickInteraction(guide,player,profile,sfItem,sfItem.getCategory(),0); server.getPluginManager().assertEventFired(PreCanUnlockResearchEvent.class, event -> { Assertions.assertEquals(player, event.getPlayer()); Assertions.assertEquals(research, event.getResearch()); Assertions.assertEquals(sfItem,event.getSlimefunItem()); Assertions.assertFalse(event.isCancelled()); return true; }); }

Target:
void testPreCanUnlockResearchEvent() throws InterruptedException { SlimefunPlugin.getRegistry().setResearchingEnabled(true); NamespacedKey key = new NamespacedKey(plugin, "simple_research"); Research research = new Research(key, 250, "Test", 10); research.register(); SlimefunGuideImplementation guide = Mockito.mock(SlimefunGuideImplementation.class); Player player = server.addPlayer(); PlayerProfile profile = TestUtilities.awaitProfile(player); SlimefunItem sfItem = TestUtilities.mockSlimefunItem(plugin, "RESEARCH_TEST", new CustomItem(Material.TORCH, "&bResearch Test")); research.unlockFromGuide(guide, player, profile, sfItem, sfItem.getCategory(), 0); server.getPluginManager().assertEventFired(PlayerPreResearchEvent.class, event -> { Assertions.assertEquals(player, event.getPlayer()); Assertions.assertEquals(research, event.getResearch()); Assertions.assertEquals(sfItem, event.getSlimefunItem()); Assertions.assertFalse(event.isCancelled()); return true; }); }
Source:
public void testCreateSecret() throws Exception { requireDockerApiVersionAtLeast("1.25", "swarm support"); final String secretData = Base64.encodeAsString("testdata".getBytes()); final SecretSpec secret = SecretSpec.builder().name("asecret").data(secretData).build(); final SecretCreateResponse response = sut.createSecret(secret); assertThat(response.id(), is(notNullValue())); }

Target:
public void testCreateSecret() throws Exception { requireDockerApiVersionAtLeast("1.25", "swarm support"); final String secretData = Base64.encodeAsString("testdata".getBytes()); HashMap<String, String> labels = new HashMap<>(); labels.put("foo", "bar"); labels.put("1", "a"); final SecretSpec secret1 = SecretSpec.builder().name("asecret").data(secretData) .labels(labels).build(); final SecretCreateResponse response1 = sut.createSecret(secret1); assertThat(response1.id(), is(notNullValue())); final SecretSpec secret2Conflict = SecretSpec.builder().name("asecret").data(secretData) .labels(labels).build(); try { sut.createSecret(secret2Conflict); fail("Should fail due to secret name conflict"); } catch (ConflictException de) final SecretSpec secret3PlainData = SecretSpec.builder().name("asecret2").data("plainData") .labels(labels).build(); try { sut.createSecret(secret3PlainData); fail("Should fail due to plain data"); } catch (DockerException de) }
Source:
public void validate() throws Exception { final Environment.Mock mock = new Environment.Mock(); final String name = String.format("src/main/java/foo/%s", this.file); final Environment env = mock.withFile( name, IOUtils.toString( this.getClass().getResourceAsStream(this.file), Charset.defaultCharset() ) ); final Collection<Violation> violations = new PmdValidator(env).validate( Collections.singletonList(new File(env.basedir(), name)) ); MatcherAssert.assertThat(violations.isEmpty(), this.result); final StringBuilder builder = new StringBuilder(); for (final Violation violation : violations) { builder.append( String.format( "PMD: %s[%s]: %s (%s)\n", this.file, violation.lines(), violation.message(), violation.name() ) ); } MatcherAssert.assertThat(builder.toString(), this.matcher); }

Target:
public void validate() throws Exception { final Environment.Mock mock = new Environment.Mock(); final String name = String.format("src/main/java/foo/%s", this.file); final Environment env = mock.withFile( name, IOUtils.toString( this.getClass().getResourceAsStream(this.file), StandardCharsets.UTF_8 ) ); final Collection<Violation> violations = new PmdValidator(env).validate( Collections.singletonList(new File(env.basedir(), name)) ); MatcherAssert.assertThat(violations.isEmpty(), this.result); final StringBuilder builder = new StringBuilder(); for (final Violation violation : violations) { builder.append( String.format( "PMD: %s[%s]: %s (%s)\n", this.file, violation.lines(), violation.message(), violation.name() ) ); } MatcherAssert.assertThat(builder.toString(), this.matcher); }
Source:
protected Blob convertBlobToMimeType(Blob blob, String destinationMimeType) { BlobHolder bh = new SimpleBlobHolder(blob); bh = convertToMimeType(destinationMimeType, bh, new HashMap<String, Serializable>()); if (bh == null) { return null; } Blob result = bh.getBlob(); return result; }

Target:
protected Blob convertBlobToMimeType(Blob blob, String destinationMimeType) { BlobHolder bh = new SimpleBlobHolder(blob); bh = convertToMimeType(destinationMimeType, bh, null); return bh == null ? null : bh.getBlob(); }
Source:
public void testCookieForStateLessClient() throws HttpException, IOException { TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; Header header = new Header("User-Agent", "Java/1.6" ); HttpClient httpClient = new HttpClient(); httpClient.getState().setCredentials( AuthScope.ANY, new UsernamePasswordCredentials( username, password ) ); GetMethod getMethod = new GetMethod( url ); getMethod.addRequestHeader( header ); getMethod.releaseConnection(); Assert.assertEquals( httpClient.executeMethod( getMethod ), 200 ); Cookie sessionCookie = this.getSessionCookie( httpClient.getState().getCookies() ); Assert.assertNull( sessionCookie, "Session Cookie is set" ); }

Target:
public void testCookieForStateLessClient() throws HttpException, IOException { TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; Header header = new Header("User-Agent", "Java/1.6" ); HttpClient httpClient = new HttpClient(); httpClient.getState().setCredentials( AuthScope.ANY, new UsernamePasswordCredentials( username, password ) ); GetMethod getMethod = new GetMethod( url ); getMethod.addRequestHeader( header ); Assert.assertEquals( executeAndRelease( httpClient, getMethod ), 200 ); Cookie sessionCookie = this.getSessionCookie( httpClient.getState().getCookies() ); Assert.assertNull( sessionCookie, "Session Cookie is set" ); }
Source:
private synchronized void startNextProjectNegotiation() { ISarosSession currentSession = session; if (currentSession == null) { log.warn("could not add resources because there is no active session"); return; } if (!currentSession.hasWriteAccess()) { log.error( "current local user has not enough privileges to add resources to the current session"); return; } ProjectSharingData projectsToShare = new ProjectSharingData(); Map<IReferencePoint, List<IResource>> mapping = nextProjectNegotiation.get(); for (Entry<IReferencePoint, List<IResource>> mapEntry : mapping.entrySet()) { final IReferencePoint referencePoint = mapEntry.getKey(); final List<IResource> resourcesList = mapEntry.getValue(); String referencePointID = currentSession.getReferencePointID(referencePoint); if (referencePointID == null) { referencePointID = String.valueOf(SESSION_ID_GENERATOR.nextInt(Integer.MAX_VALUE)); } projectsToShare.addReferencePoint(referencePoint, referencePointID, resourcesList); if (currentSession.isHost() && !currentSession.isCompletelyShared(referencePoint)) { currentSession.addSharedResources(referencePoint, referencePointID, resourcesList); } } if (projectsToShare.isEmpty()) { log.warn( "skipping project negotiation because no new projects were added to the current session"); return; } executeOutgoingProjectNegotiation(projectsToShare, session.getLocalUser()); }

Target:
private synchronized void startNextProjectNegotiation() { ISarosSession currentSession = session; if (currentSession == null) { log.warn("could not add resources because there is no active session"); return; } if (!currentSession.hasWriteAccess()) { log.error( "current local user has not enough privileges to add resources to the current session"); return; } ProjectSharingData referencePointsToShare = new ProjectSharingData(); Map<IReferencePoint, List<IResource>> mapping = nextProjectNegotiation.get(); for (Entry<IReferencePoint, List<IResource>> mapEntry : mapping.entrySet()) { final IReferencePoint referencePoint = mapEntry.getKey(); final List<IResource> resourcesList = mapEntry.getValue(); String referencePointID = currentSession.getReferencePointID(referencePoint); if (referencePointID == null) { referencePointID = String.valueOf(SESSION_ID_GENERATOR.nextInt(Integer.MAX_VALUE)); } referencePointsToShare.addReferencePoint(referencePoint, referencePointID, resourcesList); if (currentSession.isHost() && !currentSession.isCompletelyShared(referencePoint)) { currentSession.addSharedResources(referencePoint, referencePointID, resourcesList); } } if (referencePointsToShare.isEmpty()) { log.warn( "skipping project negotiation because no new projects were added to the current session"); return; } executeOutgoingProjectNegotiation(referencePointsToShare, session.getLocalUser()); }
Source:
public void testDisableCompactionForBlobStore() { compactionManager.enable(); assertFalse("Disable compaction on BlobStore is not allowed when compaction executor is not instantiated", compactionManager.disableCompactionForBlobStore(blobStore)); compactionManager.disable(); compactionManager.awaitTermination(); properties.setProperty("store.compaction.triggers", ALL_COMPACTION_TRIGGERS); config = new StoreConfig(new VerifiableProperties(properties)); StorageManagerMetrics metrics = new StorageManagerMetrics(new MetricRegistry()); compactionManager = new CompactionManager(MOUNT_PATH, config, Collections.singleton(blobStore), metrics, time); compactionManager.enable(); assertTrue("Disable compaction on given BlobStore should succeed", compactionManager.disableCompactionForBlobStore(blobStore)); compactionManager.disable(); compactionManager.awaitTermination(); }

Target:
public void testDisableCompactionForBlobStore() throws Exception { compactionManager.enable(); assertTrue("Disable compaction on BlobStore should be true when compaction executor is not instantiated", compactionManager.disableCompactionForBlobStore(blobStore)); compactionManager.disable(); compactionManager.awaitTermination(); properties.setProperty("store.compaction.triggers", ALL_COMPACTION_TRIGGERS); config = new StoreConfig(new VerifiableProperties(properties)); StorageManagerMetrics metrics = new StorageManagerMetrics(new MetricRegistry()); compactionManager = new CompactionManager(MOUNT_PATH, config, Collections.singleton(blobStore), metrics, time); compactionManager.enable(); assertTrue("Disable compaction on given BlobStore should succeed", compactionManager.disableCompactionForBlobStore(blobStore)); assertFalse("BlobStore should not be scheduled after compaction is disabled on it", compactionManager.scheduleNextForCompaction(blobStore)); compactionManager.disable(); compactionManager.awaitTermination(); }
Source:
public HaxeClassResolveResult resolveHaxeClass() { Throwable t = new Throwable(); StackTraceElement[] stack = t.getStackTrace(); if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Called from " + stack[1].toString())); if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Begin resolving Haxe class:" + this.getText())); HaxeClassResolveResult result = resolveHaxeClassInternal(); if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Finished resolving Haxe class " + this.getText() + " as " + result.debugDump())); return result; }

Target:
public HaxeClassResolveResult resolveHaxeClass() { if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Begin resolving Haxe class:" + this.getText())); HaxeClassResolveResult result = resolveHaxeClassInternal(); if (LOG.isTraceEnabled()) LOG.trace(traceMsg("Finished resolving Haxe class " + this.getText() + " as " + result.debugDump())); return result; }
Source:
public void loadAd(@Nullable MediationAdRequest request, @Nullable Bundle bundle, @Nullable Bundle bundle1) { Log.d(TAG, "Load Ad"); if (interstitial != null) { interstitial.load(); } }

Target:
public void loadAd(@Nullable MediationAdRequest request, @Nullable Bundle bundle, @Nullable Bundle bundle1) { Log.d(TAG, "Load Ad"); if (interstitial != null) { interstitial.load(); } else { Log.d(TAG, "Ad failed to load: interstitial is null"); if (listener != null) { listener.onAdFailedToLoad(MyTargetRewardedAdapter.this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } } }
Source:
private boolean menuIsRelevant(Menu m) throws XPathSyntaxException { XPathExpression relevance = m.getMenuRelevance(); if (m.getMenuRelevance() != null) { errorXpathException = m.getMenuRelevanceRaw(); EvaluationContext ec = asw.getEvaluationContext(m.getId()); if (!XPathFuncExpr.toBoolean(relevance.eval(ec))) { return false; } } return true; }

Target:
private boolean menuIsRelevant(Menu m) throws XPathSyntaxException { XPathExpression relevance = m.getMenuRelevance(); if (m.getMenuRelevance() != null) { errorXpathException = m.getMenuRelevanceRaw(); EvaluationContext ec = asw.getEvaluationContext(m.getId()); return XPathFuncExpr.toBoolean(relevance.eval(ec)); } return true; }
Source:
public void testRequiredTypeAdapterNonNull() { RequiredTypeAdapterModel expected = new RequiredTypeAdapterModel(); expected.uri = Uri.parse(Constants.WIKIPEDIA_URL); RequiredTypeAdapterModel result = unmarshal(RequiredTypeAdapterModel.class, marshal(expected)); assertThat(result, is(expected)); }

Target:
public void testRequiredTypeAdapterNonNull() { RequiredTypeAdapterModel expected = new RequiredTypeAdapterModel(); expected.uri = Uri.parse(Constants.WIKIPEDIA_URL); RequiredTypeAdapterModel result = unmarshal(gson, RequiredTypeAdapterModel.class, marshal(gson, expected)); assertThat(result, is(expected)); }
Source:
public void addComponent(MultiblockComponent component) { if(getComponentForLocation(component.relPos.posX, component.relPos.posY, component.relPos.posZ)!=null) { throw new IllegalArgumentException("Location in multiblock already occupied"); } components.add(component); changeAxisForNewComponent(component.relPos.posX, component.relPos.posY, component.relPos.posZ); calculateCostForNewComponent(component); addComponentToLocationCache(component); }

Target:
public void addComponent(MultiblockComponent component) { if(getComponentForLocation(component.relPos.posX, component.relPos.posY, component.relPos.posZ) != null) throw new IllegalArgumentException("Location in multiblock already occupied"); components.add(component); changeAxisForNewComponent(component.relPos.posX, component.relPos.posY, component.relPos.posZ); calculateCostForNewComponent(component); addComponentToLocationCache(component); }
Source:
public boolean isValid() { return coordinates != null && coordinates.size() == 2 && coordinates.get(0) >= -180.0 && coordinates.get(0) <= 180.0 && coordinates.get(1) >= -90.0 && coordinates.get(1) <= 90.0 && (coordinateSystem == null || coordinateSystem.isValid()); }

Target:
public boolean isValid() { return coordinates != null && coordinates.size() == 2 && coordinates.get(0) != null && coordinates.get(1) != null && coordinates.get(0) >= -180.0 && coordinates.get(0) <= 180.0 && coordinates.get(1) >= -90.0 && coordinates.get(1) <= 90.0 && (coordinateSystem == null || coordinateSystem.isValid()); }
Source:
public void launch() { MongoDBServer server = MongoDBServer.class.cast(entity); Integer port = server.getAttribute(MongoDBServer.PORT); ImmutableList.Builder<String> argsBuilder = ImmutableList.<String>builder() .add("--config", getConfFile()) .add("--pidfilepath", getPidFile()) .add("--dbpath", getDataDirectory()) .add("--logpath", getLogFile()) .add("--port", port.toString()) .add("--fork"); String replicaSetName = server.getReplicaSet().getName(); if (!Strings.isNullOrEmpty(replicaSetName)) argsBuilder.add("--replSet", replicaSetName); if (Boolean.TRUE.equals(server.getConfig(MongoDBServer.ENABLE_REST_INTERFACE))) argsBuilder.add("--rest"); String args = Joiner.on(" ").join(argsBuilder.build()); String command = String.format("%s/bin/mongod %s > out.log 2> err.log < /dev/null", getExpandedInstallDir(), args); log.info(command); newScript(LAUNCHING) .updateTaskAndFailOnNonZeroResultCode() .body.append(command).execute(); }

Target:
public void launch() { MongoDBServer server = getEntity(); Integer port = server.getAttribute(MongoDBServer.PORT); ImmutableList.Builder<String> argsBuilder = ImmutableList.<String>builder() .add("--config", getConfFile()) .add("--pidfilepath", getPidFile()) .add("--dbpath", getDataDirectory()) .add("--logpath", getLogFile()) .add("--port", port.toString()) .add("--fork"); if (server.isReplicaSetMember()) { String replicaSetName = server.getReplicaSet().getName(); checkState(!Strings.isNullOrEmpty(replicaSetName), "Replica set name must not be null or empty"); argsBuilder.add("--replSet", replicaSetName); } if (Boolean.TRUE.equals(server.getConfig(MongoDBServer.ENABLE_REST_INTERFACE))) argsBuilder.add("--rest"); String args = Joiner.on(" ").join(argsBuilder.build()); String command = String.format("%s/bin/mongod %s > out.log 2> err.log < /dev/null", getExpandedInstallDir(), args); LOG.info(command); newScript(LAUNCHING) .updateTaskAndFailOnNonZeroResultCode() .body.append(command).execute(); }
Source:
public void emitTuples() { if (!readThread.isAlive() && resultQueue.isEmpty()) { startReadThread(); } try { Result result = resultQueue.poll(); if (result == null) { Thread.sleep(sleepMillis); return; } T tuple = getTuple(result); if (tuple != null) { outputPort.emit(tuple); tuplesRead++; } } catch (Exception e) { e.printStackTrace(); } }

Target:
public void emitTuples() { if (!readThread.isAlive() && threadFailed) { throw new RuntimeException("Exception in scan thread"); } try { Result result = resultQueue.poll(); if (result == null) { return; } T tuple = getTuple(result); if (tuple != null) { outputPort.emit(tuple); tuplesRead++; } } catch (Exception e) { throw new RuntimeException(e); } }