auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void createActions() { Action resolveAllAsRemote = new Action(Messages.SyncMergeFileTableViewer_Resolve_all_as_remote, IAction.AS_PUSH_BUTTON) { @Override public void run() { String currentSyncServiceId = SyncConfigManager.getActive(project).getSyncProviderId(); ISynchronizeService syncService = SyncManager.getSyncService(currentSyncServiceId); ArrayList<IPath> paths = new ArrayList<IPath>(); for (IResource resource : getAllResources()) { paths.add(resource.getProjectRelativePath()); } try { syncService.checkoutRemoteCopy(project, paths.toArray(new IPath[paths.size()])); syncService.setMergeAsResolved(project, paths.toArray(new IPath[paths.size()])); } catch (CoreException e) { RDTSyncUIPlugin.getDefault().logErrorMessage(Messages.SyncMenuOperation_1); } activeViewerInstance.update(null); } }; resolveAllAsRemote.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin( RDTSyncUIPlugin.PLUGIN_ID, "icons/mergeview/resolve_as_remote.gif")); IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager(); toolbar.add(resolveAllAsRemote); }

Target:
private void createActions() { Action resolveAllAsRemote = new Action(Messages.SyncMergeFileTableViewer_Resolve_all_as_remote, IAction.AS_PUSH_BUTTON) { @Override public void run() { if (project == null) { return; } String currentSyncServiceId = SyncConfigManager.getActive(project).getSyncProviderId(); ISynchronizeService syncService = SyncManager.getSyncService(currentSyncServiceId); Set<IPath> paths = getAllPaths(); try { syncService.checkoutRemoteCopy(project, paths.toArray(new IPath[paths.size()])); syncService.setMergeAsResolved(project, paths.toArray(new IPath[paths.size()])); } catch (CoreException e) { MessageDialog.openError(null, Messages.SyncMergeFileTableViewer_Error, Messages.SyncMergeFileTableViewer_Error_resolving_all + Messages.SyncMergeFileTableViewer_Error_description + e.getMessage()); } activeViewerInstance.update(null); } }; resolveAllAsRemote.setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin( RDTSyncUIPlugin.PLUGIN_ID, "icons/mergeview/resolve_as_remote.gif")); IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager(); toolbar.add(resolveAllAsRemote); }
Source:
public void shouldEmitNoRecordIfTransformReturnsNull() { final ProcessorContext context = mock(ProcessorContext.class); final ValueTransformerWithKey<Integer, Integer, Integer> valueTransformer = mock(ValueTransformerWithKey.class); final KStreamTransformValues.KStreamTransformValuesProcessor<Integer, Integer, Integer> processor = new KStreamTransformValues.KStreamTransformValuesProcessor<>(valueTransformer); processor.init(context); EasyMock.reset(context, valueTransformer); final Integer inputKey = 1; final Integer inputValue = 10; EasyMock.expect(valueTransformer.transform(inputKey, inputValue)).andReturn(null); EasyMock.replay(context, valueTransformer); processor.process(inputKey, inputValue); EasyMock.verify(context, valueTransformer); }

Target:
public void shouldEmitNoRecordIfTransformReturnsNull() { final ProcessorContext context = mock(ProcessorContext.class); final ValueTransformerWithKey<Integer, Integer, Integer> valueTransformer = mock(ValueTransformerWithKey.class); final KStreamTransformValues.KStreamTransformValuesProcessor<Integer, Integer, Integer> processor = new KStreamTransformValues.KStreamTransformValuesProcessor<>(valueTransformer); processor.init(context); final Integer inputKey = 1; final Integer inputValue = 10; EasyMock.expect(valueTransformer.transform(inputKey, inputValue)).andStubReturn(null); EasyMock.replay(context); processor.process(inputKey, inputValue); EasyMock.verify(context); }
Source:
public void setPrecision(final TimeUnit precision) { this.precision = precision; }

Target:
void setPrecision(final TimeUnit precision) { this.precision = precision; }
Source:
public void loginExistingAccount(String userName, String password) { waitForElementByElement(existingUsernameField); existingUsernameField.sendKeys(userName); PageObjectLogging.log("loginExistingAccount", "username " + userName + " typed into the field", true); waitForElementByElement(existingPasswordField); existingPasswordField.sendKeys(password); PageObjectLogging.log("loginExistingAccount", "password " + password + " typed into the field", true); loginExistingButton.click(); PageObjectLogging.log("loginExistingAccount", "login button clicked", true); }

Target:
public void loginExistingAccount(String userName, String password) { waitForElementByElement(existingUsernameField); existingUsernameField.sendKeys(userName); PageObjectLogging.log("loginExistingAccount", "username " + userName + " typed into the field", true); waitForElementByElement(existingPasswordField); existingPasswordField.sendKeys(password); PageObjectLogging.log("loginExistingAccount", "password " + password + " typed into the field", true); loginExistingButton.click(); }
Source:
static Configuration getConfiguration(String modid, String name) { if(name == null || name.isEmpty()) name = modid; File configDir = Loader.instance().getConfigDir(); File configFile = new File(configDir, name + ".cfg"); return CONFIGS.get(configFile.getAbsolutePath()); }

Target:
static Configuration getConfiguration(String modid, String name) { if (Strings.isNullOrEmpty(name)) name = modid; File configDir = Loader.instance().getConfigDir(); File configFile = new File(configDir, name + ".cfg"); return CONFIGS.get(configFile.getAbsolutePath()); }
Source:
private void InitializeItems(List<SanTargetModel> newItems) { if (getItems() == null) { setItems(new ObservableCollection<SanTargetModel>()); } ArrayList<SanTargetModel> items = new ArrayList<SanTargetModel>(); items.addAll((List<SanTargetModel>) getItems()); if (newItems != null) { for (SanTargetModel newItem : newItems) { if (Linq.FirstOrDefault(items, new Linq.TargetPredicate(newItem)) == null) { items.add(newItem); } } } setItems(items); UpdateLoginAllAvailability(); }

Target:
private void InitializeItems(List<SanTargetModel> newItems) { if (getItems() == null) { setItems(new ObservableCollection<SanTargetModel>()); } if (newItems != null) { ArrayList<SanTargetModel> items = new ArrayList<SanTargetModel>(); items.addAll((List<SanTargetModel>) getItems()); for (SanTargetModel newItem : newItems) { if (Linq.FirstOrDefault(items, new Linq.TargetPredicate(newItem)) == null) { items.add(newItem); } } setItems(items); } UpdateLoginAllAvailability(); }
Source:
public RowBatch nextBatch(RowBatch previous) throws IOException { MessageType requestedSchema = readContext.getRequestedSchema(); List<ColumnDescriptor> columns = requestedSchema.getColumns(); int nColumns = columns.size(); ColumnVector[] columnVectors; RowBatch rowBatch = previous; if (rowBatch == null) { rowBatch = new RowBatch(); } if (rowBatch.getColumns() == null) { columnVectors = new ColumnVector[nColumns]; rowBatch.setColumns(columnVectors); } else { columnVectors = rowBatch.getColumns(); } MessageType[] columnSchemas = new MessageType[nColumns]; for (int i = 0; i < nColumns; i++) { ColumnVector columnVector = columnVectors[i]; columnSchemas[i] = new MessageType(requestedSchema.getFieldName(i), requestedSchema.getType(i)); if (columnVector == null) { columnVector = ColumnVector.from(columns.get(i)); } rowBatch.getColumns()[i] = columnVector; } return readVectors(rowBatch.getColumns(), columnSchemas) ? rowBatch : null; }

Target:
public RowBatch nextBatch(RowBatch previous) throws IOException { MessageType requestedSchema = readContext.getRequestedSchema(); List<ColumnDescriptor> columns = requestedSchema.getColumns(); int nColumns = columns.size(); ColumnVector[] columnVectors; RowBatch rowBatch = previous; if (rowBatch == null) { rowBatch = new RowBatch(new ColumnVector[nColumns]); } columnVectors = rowBatch.getColumns(); checkArgument(columns.size() == columnVectors.length, "Number of columns in the requested schema and the previous row batch don't match."); MessageType[] columnSchemas = new MessageType[nColumns]; for (int i = 0; i < nColumns; i++) { ColumnVector columnVector = columnVectors[i]; columnSchemas[i] = new MessageType(requestedSchema.getFieldName(i), requestedSchema.getType(i)); if (columnVector == null) { columnVector = ColumnVector.from(columns.get(i)); } rowBatch.getColumns()[i] = columnVector; } return readVectors(rowBatch.getColumns(), columnSchemas) ? rowBatch : null; }
Source:
private String startPasswordDialog(String user) throws IOException { log.debug("starting password dialog."); System.out.println(String.format("Please enter a password for %s:",user)); return new String(System.console().readPassword()); }

Target:
private String startPasswordDialog(String user) throws IOException { log.debug("starting password dialog."); System.out.printf("Please enter a password for %s:",user); return new String(System.console().readPassword()); }
Source:
public List<StoredQuery> listStoredQueries() { final List<StoredQuery> queries = new ArrayList<>(); queries.add(StoredQuery.DEFAULT); final Resource dir = storedQueryDir(); final List<StoredQuery> globalQueries = getStoredQueryByResource(dir); final List<StoredQuery> localQueries = getLocalWorkspaceStoredQueries(); if (shouldProcessGlobalQueries()) { globalQueries .stream() .filter( q -> localQueries .stream() .noneMatch( local -> Objects.equals( q.getName(), local.getName()))) .forEach(q -> queries.add(q)); } queries.addAll(localQueries); return queries; }

Target:
public List<StoredQuery> listStoredQueries() { final List<StoredQuery> queries = new ArrayList<>(); queries.add(StoredQuery.DEFAULT); final Resource dir = storedQueryDir(); final List<StoredQuery> globalQueries = getStoredQueryByResource(dir); final List<StoredQuery> localQueries = getLocalWorkspaceStoredQueries(); if (shouldProcessGlobalQueries()) { globalQueries .stream() .filter(q -> checkQueryNotExists(q, localQueries)) .forEach(q -> queries.add(q)); } queries.addAll(localQueries); return queries; }
Source:
public void testCrossJoinBroadcastRightNoHint() throws Exception { if (useSpark.equalsIgnoreCase("false")) return; String sqlText = "sparkexplain select count(*) from\n" + " t1 --splice-properties useSpark=true\n" + " inner join big on 1=1"; testQueryContains(sqlText, "BroadcastNestedLoopJoin BuildRight, Cross", methodWatcher, true); }

Target:
public void testCrossJoinBroadcastRightNoHint() throws Exception { if (useSpark.equalsIgnoreCase("false")) return; String sqlText = "explain select count(*) from\n" + " t1 --splice-properties useSpark=true\n" + " inner join big on 1=1"; String[] expectedList = {"CrossJoin", "TableScan[T1(", "TableScan[BIG("}; rowContainsQuery(new int[]{6, 7, 9}, sqlText, methodWatcher, expectedList); sqlText = "sparkexplain select count(*) from\n" + " t1 --splice-properties useSpark=true\n" + " inner join big on 1=1"; String expected = "BroadcastNestedLoopJoin BuildRight, Cross |\n" + " :- Scan ExistingRDD[] |\n" + "-> TableScan[BIG("; testQueryContains(sqlText, expected, methodWatcher, true); }
Source:
public Mono<Void> deleteAllById(Iterable<? extends ID> ids) { Assert.notNull(ids, "The given Iterable of entities must not be null"); return Flux.fromIterable(ids).flatMap(this::deleteById).then(); }

Target:
public Mono<Void> deleteAllById(Iterable<? extends ID> ids) { Assert.notNull(ids, "The given Iterable of entities must not be null"); if (FindByIdQuery.hasCompositeKeys(ids)) { return deleteById(Flux.fromIterable(ids)); } if (!ids.iterator().hasNext()) { return Mono.empty(); } return this.operations.delete(createIdsInCollectionQuery(ids), this.entityInformation.getJavaType()).then(); }
Source:
protected void executeCommand() { VDSGroup cluster = getVdsGroupDAO().get(getParameters().getClusterId()); try { getSyncJobInstance().refreshHooksInCluster(cluster, true); setSucceeded(true); } catch (VdcBLLException e) { setSucceeded(false); } }

Target:
protected void executeCommand() { getSyncJobInstance().refreshHooksInCluster(getVdsGroup(), true); setSucceeded(true); }
Source:
private void resetVisibleLimits() { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { Timber.e("Unable to reset visible limits", e); } }

Target:
private void resetVisibleLimits() { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { Timber.e(e, "Unable to reset visible limits"); } }
Source:
public int[] getRequiredTokens() { return new int[] { TokenTypes.SEMI, }; }

Target:
public int[] getRequiredTokens() { return CommonUtil.EMPTY_INT_ARRAY; }
Source:
public JobExecutionInfoResource getJobExecutionInfo(@PathVariable long executionId) { final JobExecution jobExecution; try { jobExecution = jobService.getJobExecution(executionId); } catch (org.springframework.batch.core.launch.NoSuchJobExecutionException e) { throw new NoSuchJobExecutionException(executionId); } final Set<String> restartableJobs = new HashSet<String>(jobLocator.getAllRestartableJobs()); final Set<String> deployedJobs = new HashSet<String>(jobLocator.getJobNames()); final Set<String> jobDefinitionNames = new HashSet<String>(getJobDefinitionNames()); final JobExecutionInfoResource jobExecutionInfoResource = getJobExecutionInfoResource(jobExecution, restartableJobs, deployedJobs, jobDefinitionNames); for (JobExecution childJobExecution : jobService.getChildJobExecutions(jobExecution.getId())) { jobExecutionInfoResource.setComposedJob(true); stepExecutionDao.addStepExecutions(childJobExecution); final JobExecutionInfoResource childJobExecutionInfoResource = getJobExecutionInfoResource( childJobExecution, restartableJobs, deployedJobs, jobDefinitionNames); boolean isCompposed = jobService.isComposedJobExecution(childJobExecution.getId()); childJobExecutionInfoResource.setComposedJob(isCompposed); jobExecutionInfoResource.getChildJobExecutions().add(childJobExecutionInfoResource); } return jobExecutionInfoResource; }

Target:
public JobExecutionInfoResource getJobExecutionInfo(@PathVariable long executionId) { final JobExecution jobExecution; try { jobExecution = jobService.getJobExecution(executionId); } catch (org.springframework.batch.core.launch.NoSuchJobExecutionException e) { throw new NoSuchJobExecutionException(executionId); } final Set<String> restartableJobs = new HashSet<String>(jobLocator.getAllRestartableJobs()); final Set<String> deployedJobs = new HashSet<String>(jobLocator.getJobNames()); final Set<String> jobDefinitionNames = new HashSet<String>(getJobDefinitionNames()); final JobExecutionInfoResource jobExecutionInfoResource = getJobExecutionInfoResource(jobExecution, restartableJobs, deployedJobs, jobDefinitionNames); for (JobExecution childJobExecution : jobService.getChildJobExecutions(jobExecution.getId())) { jobExecutionInfoResource.setComposedJob(true); stepExecutionDao.addStepExecutions(childJobExecution); final JobExecutionInfoResource childJobExecutionInfoResource = getJobExecutionInfoResource( childJobExecution, restartableJobs, deployedJobs, jobDefinitionNames); boolean isComposed = jobService.isComposedJobExecution(childJobExecution.getId()); childJobExecutionInfoResource.setComposedJob(isComposed); jobExecutionInfoResource.getChildJobExecutions().add(childJobExecutionInfoResource); } return jobExecutionInfoResource; }
Source:
public void create_entity_with_default_values() { final int version = 100500; final String expectedState = Values.newStringValue("").getValue(); final Timestamp defaultTimestamp = Timestamp.getDefaultInstance(); final Entity entity = givenEntity().withVersion(version).build(); final String actualState = entity.getState().toString(); assertEquals(TestEntity.class, entity.getClass()); assertEquals(0L, entity.getId()); assertEquals(expectedState, actualState); assertEquals(version, entity.getVersion()); assertEquals(defaultTimestamp, entity.whenModified()); }

Target:
public void create_entity_with_default_values() { final Entity entity = givenEntity().build(); assertEquals(TestEntity.class, entity.getClass()); assertEquals(0L, entity.getId()); assertEquals(newStringValue(""), entity.getState()); assertEquals(0, entity.getVersion()); assertEquals(Timestamp.getDefaultInstance(), entity.whenModified()); }
Source:
protected void execute() { logger.debug("execute() method is called!"); }

Target:
public void execute() { if (!bindingsExist()) { logger.warn("There is no existing Girahomeserver binding configuration => refresh cycle aborted!"); return; } GiraHomeServerConnector connector = new GiraHomeServerConnector(ip, port, password); try { connector.connect(); readValuesFromGirahomeserver(connector); flushValuesToGirahomeserver(connector); } catch (UnknownHostException e) { logger.warn("the given hostname '{}' of the Gira Home Server is unknown", ip); } catch (IOException e) { logger.warn("couldn't establish network connection [host '{}']", ip); } finally { if (connector != null) { connector.disconnect(); } } }
Source:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { new Thread(() -> { if (Iterables.contains(allModules(getTrace()), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); ITmfTrace moduleTrace = module instanceof TmfAbstractAnalysisModule ? ((TmfAbstractAnalysisModule) module).getTrace() : getTrace(); getDataProvider(moduleTrace).startedAnalysisSignalHandler((ITmfAnalysisModuleWithStateSystems) module); rebuild(); } } else { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (Iterables.contains(allModules(trace), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); resetView(trace); } break; } } } }).start(); } }

Target:
public void handleAnalysisStarted(TmfStartAnalysisSignal signal) { IAnalysisModule module = signal.getAnalysisModule(); if (module instanceof ITmfAnalysisModuleWithStateSystems && !module.isAutomatic()) { final ITmfTrace viewTrace = getTrace(); if (Iterables.contains(allModules(viewTrace), module)) { new Thread(() -> { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); ITmfTrace moduleTrace = module instanceof TmfAbstractAnalysisModule ? ((TmfAbstractAnalysisModule) module).getTrace() : viewTrace; if (moduleTrace != null) { getDataProvider(moduleTrace).startedAnalysisSignalHandler((ITmfAnalysisModuleWithStateSystems) module); rebuild(); } } }).start(); } else { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (Iterables.contains(allModules(trace), module)) { synchronized (fStartedAnalysis) { fStartedAnalysis.add((ITmfAnalysisModuleWithStateSystems) module); resetView(trace); } break; } } } } }
Source:
protected SelectionListener createSelectionListener() { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final List<String> values = getValues(); Map<String, String> validValues = getAttributeMapper().getOptions(getTaskAttribute()); final InPlaceCheckBoxTreeDialog selectionDialog = new InPlaceCheckBoxTreeDialog( WorkbenchUtil.getShell(), button, values, validValues, NLS.bind(Messages.CheckboxMultiSelectAttributeEditor_Select_X, getLabel())); createEventListener(values, selectionDialog); selectionDialog.open(); } }; }

Target:
protected SelectionListener createSelectionListener() { return new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final List<String> values = getValueList(); final InPlaceCheckBoxTreeDialog selectionDialog = createInPlaceCheckBoxTreeDialog(values); addEventListener(values, selectionDialog); selectionDialog.open(); } }; }
Source:
public Object fromAvro(Schema schema, Object input) { switch (schema.getType()) { case NULL: if (input == null) { return null; } throw new NonNullValueException(); case UNION: for (Schema sub : schema.getTypes()) { try { return service.fromAvro(sub, Property.class, input); } catch (NonNullValueException e) { } } throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); case RECORD: GenericRecord record = (GenericRecord) input; List<Field> fields = schema.getFields(); Map<String, Object> data = new HashMap<>(fields.size()); for (Field field : fields) { String propertyName = service.decodeName(field.name()); Class<?> clazz = MAPPING.getOrDefault(propertyName, Property.class); Object value = service.fromAvro(field.schema(), clazz, record.get(field.name())); data.put(propertyName, value); } return data; case ARRAY: GenericData.Array<?> array = (Array<?>) input; List<Object> list = new ArrayList<>(array.size()); for (Object element : array) { list.add(service.fromAvro(schema.getElementType(), Property.class, element)); } return list; case LONG: if ("timestamp-millis".equals(getLogicalType(schema))) { return new Date(((Long) input).longValue()); } return input; case INT: case FLOAT: case STRING: case DOUBLE: case BOOLEAN: return input; case BYTES: return Blobs.createBlob(((ByteBuffer) input).array()); default: throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); } }

Target:
public Object fromAvro(Schema schema, Object input) { switch (schema.getType()) { case NULL: if (input == null) { return null; } throw new NonNullValueException(); case UNION: for (Schema sub : schema.getTypes()) { try { return service.fromAvro(sub, Property.class, input); } catch (NonNullValueException e) { } } throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); case RECORD: GenericRecord record = (GenericRecord) input; List<Field> fields = schema.getFields(); Map<String, Object> data = new HashMap<>(fields.size()); for (Field field : fields) { String propertyName = service.decodeName(field.name()); Class<?> clazz = MAPPING.getOrDefault(propertyName, Property.class); Object value = service.fromAvro(field.schema(), clazz, record.get(field.name())); data.put(propertyName, value); } return data; case ARRAY: GenericData.Array<?> array = (Array<?>) input; List<Object> list = new ArrayList<>(array.size()); for (Object element : array) { list.add(service.fromAvro(schema.getElementType(), Property.class, element)); } return list; case LONG: if (TIMESTAMP_MILLIS.equals(getLogicalType(schema))) { return new Date(((Long) input).longValue()); } return input; case INT: case FLOAT: case STRING: case DOUBLE: case BOOLEAN: return input; case BYTES: return Blobs.createBlob(((ByteBuffer) input).array()); default: throw new RuntimeServiceException(CANNOT_MAP_FROM + schema.getType()); } }
Source:
public void toServiceBusMessageTest() { final ServiceBusReceivedMessage originalMessage = new ServiceBusReceivedMessage(PAYLOAD_BYTES); originalMessage.setMessageId("mid"); originalMessage.setContentType("type"); originalMessage.setCorrelationId("cid"); originalMessage.setReplyTo("rto"); originalMessage.setViaPartitionKey("something"); originalMessage.setTimeToLive(Duration.ofSeconds(10)); originalMessage.setReplyToSessionId("rsessionid"); originalMessage.setLabel("label"); originalMessage.setTo("to"); final ServiceBusMessage messageToSend = originalMessage.toServiceBusMessage(); Assertions.assertNotNull(messageToSend); Assertions.assertNotNull(messageToSend.getBody()); Assertions.assertEquals(PAYLOAD, new String(messageToSend.getBody(), UTF_8)); Assertions.assertEquals(originalMessage.getMessageId(), messageToSend.getMessageId()); Assertions.assertEquals(originalMessage.getContentType(), messageToSend.getContentType()); Assertions.assertEquals(originalMessage.getCorrelationId(), messageToSend.getCorrelationId()); Assertions.assertEquals(originalMessage.getReplyTo(), messageToSend.getReplyTo()); Assertions.assertEquals(originalMessage.getViaPartitionKey(), messageToSend.getViaPartitionKey()); Assertions.assertTrue( originalMessage.getTimeToLive().toMillis() == messageToSend.getTimeToLive().toMillis()); Assertions.assertEquals(originalMessage.getLabel(), messageToSend.getLabel()); Assertions.assertEquals(originalMessage.getReplyToSessionId(), messageToSend.getReplyToSessionId()); Assertions.assertEquals(originalMessage.getTo(), messageToSend.getTo()); }

Target:
public void toServiceBusMessageTest() { final ServiceBusReceivedMessage originalMessage = new ServiceBusReceivedMessage(PAYLOAD_BYTES); originalMessage.setMessageId("mid"); originalMessage.setContentType("type"); originalMessage.setCorrelationId("cid"); originalMessage.setReplyTo("rto"); originalMessage.setViaPartitionKey("something"); originalMessage.setTimeToLive(Duration.ofSeconds(10)); originalMessage.setReplyToSessionId("rsessionid"); originalMessage.setLabel("label"); originalMessage.setTo("to"); final ServiceBusMessage messageToSend = originalMessage.toServiceBusMessage(); Assertions.assertNotNull(messageToSend); Assertions.assertNotNull(messageToSend.getBody()); Assertions.assertEquals(PAYLOAD, new String(messageToSend.getBody(), UTF_8)); Assertions.assertEquals(originalMessage.getMessageId(), messageToSend.getMessageId()); Assertions.assertEquals(originalMessage.getContentType(), messageToSend.getContentType()); Assertions.assertEquals(originalMessage.getCorrelationId(), messageToSend.getCorrelationId()); Assertions.assertEquals(originalMessage.getReplyTo(), messageToSend.getReplyTo()); Assertions.assertEquals(originalMessage.getViaPartitionKey(), messageToSend.getViaPartitionKey()); Assertions.assertEquals(originalMessage.getTimeToLive().toMillis(), messageToSend.getTimeToLive().toMillis()); Assertions.assertEquals(originalMessage.getLabel(), messageToSend.getLabel()); Assertions.assertEquals(originalMessage.getReplyToSessionId(), messageToSend.getReplyToSessionId()); Assertions.assertEquals(originalMessage.getTo(), messageToSend.getTo()); }
Source:
public boolean hasPatchPermission(Authentication authentication, Serializable targetId, String targetType, Patch patch) { if (!hasPermission(authentication, targetId, targetType, "WRITE")) { return false; } List<Operation> operations = patch.getOperations(); for (Operation op: operations) { if (!(op.getPath().contentEquals(EPersonPasswordReplaceOperation.OPERATION_PASSWORD_CHANGE) || (op.getPath().startsWith(DSpaceObjectMetadataPatchUtils.OPERATION_METADATA_PATH) || op.getPath().equals(DSpaceObjectMetadataPatchUtils.OPERATION_METADATA_PATH)))) { return false; } } return true; }

Target:
public boolean hasPatchPermission(Authentication authentication, Serializable targetId, String targetType, Patch patch) { if (!hasPermission(authentication, targetId, targetType, "WRITE")) { return false; } List<Operation> operations = patch.getOperations(); for (Operation op: operations) { if (!(op.getPath().contentEquals(EPersonPasswordReplaceOperation.OPERATION_PASSWORD_CHANGE) || (op.getPath().startsWith(DSpaceObjectMetadataPatchUtils.OPERATION_METADATA_PATH)))) { return false; } } return true; }
Source:
public Set<SymbolicValue> getFieldValues() { final HashSet<SymbolicValue> fieldValues = new HashSet<>(); values.forEach(new PMap.Consumer<Symbol, SymbolicValue>() { @Override public void accept(Symbol key, SymbolicValue value) { if (isField(key)) { fieldValues.add(value); } } }); return fieldValues; }

Target:
public Set<SymbolicValue> getFieldValues() { final Set<SymbolicValue> fieldValues = new HashSet<>(); values.forEach(new PMap.Consumer<Symbol, SymbolicValue>() { @Override public void accept(Symbol key, SymbolicValue value) { if (isField(key)) { fieldValues.add(value); } } }); return fieldValues; }
Source:
protected void onStreamReadyForPlayback(String entryId, final KalturaMediaServerIndex serverIndex) { logger.debug("onStreamReadyForPlayback [" + entryId + "]"); LiveEntryCache liveEntryCache = null; synchronized (entries) { if (entries.containsKey(entryId)) { liveEntryCache = entries.get(entryId); liveEntryCache.setEntryIsLive(); } else { logger.error("entry [" + entryId + "] not found in entries array"); } } }

Target:
protected void onStreamReadyForPlayback(String entryId, final KalturaMediaServerIndex serverIndex) { logger.debug("onStreamReadyForPlayback [" + entryId + "]"); synchronized (entries) { if (entries.containsKey(entryId)) { entries.get(entryId).setEntryIsLive(); } else { logger.error("entry [" + entryId + "] not found in entries array"); } } }
Source:
public String getSqlOrder() { return "SELECT ST_SetSRID(the_geom, 4326 or 'EPSG:4326') FROM table;"; }

Target:
public String getSqlOrder() { return "SELECT ST_SetSRID(the_geom, 4326 | 'EPSG:4326') FROM table;"; }
Source:
public Guid persistAsyncTaskPlaceHolder(VdcActionType parentCommand) { Guid retValue = Guid.Empty; try { AsyncTasks task = createAsyncTask(new AsyncTaskCreationInfo(), parentCommand); retValue = task.getTaskId(); AsyncTaskUtils.addOrUpdateTaskInDB(task, null, EMPTY_GUID_ARRAY); } catch (RuntimeException ex) { log.errorFormat("Error during createAsyncTask for command: {0}. Exception {1}", this.getClass().getName(), ex); } return retValue; }

Target:
public Guid persistAsyncTaskPlaceHolder(VdcActionType parentCommand) { Guid retValue = Guid.Empty; try { AsyncTasks task = createAsyncTask(new AsyncTaskCreationInfo(), parentCommand); retValue = task.getTaskId(); AsyncTaskUtils.addOrUpdateTaskInDB(task, null, EMPTY_GUID_ARRAY); } catch (RuntimeException ex) { log.errorFormat("Error during persistAsyncTaskPlaceHolder for command: {0}. Exception {1}", this.getClass().getName(), ex); } return retValue; }
Source:
public void testRoundTrip() { SigningKeyPair kp = new SigningKeyPair(SIGN_PRIVATE, HEX); String signature = kp.getSigningKey().sign(SIGN_MESSAGE, HEX); assertTrue(kp.getVerifyKey().verify(SIGN_MESSAGE, signature, HEX)); }

Target:
public void testRoundTrip() { SigningKeyPair kp = new SigningKeyPair(SIGN_KEY_SEED, HEX); String signature = kp.getSigningKey().sign(SIGN_MESSAGE, HEX); assertTrue(kp.getVerifyKey().verify(SIGN_MESSAGE, signature, HEX)); }
Source:
private ASTNode transformJavaBackendSpecificTerm(Term term) { return new org.kframework.kil.BackendTerm(Sort.of(term.sort().name()), term.toString()); }

Target:
private ASTNode transformJavaBackendSpecificTerm(Term term) { return new org.kframework.kil.BackendTerm(term.sort().toFrontEnd(), term.toString()); }
Source:
private void uploadPartitionOverride(Map<String, Map<String, String>> partitionOverrideInfos) { Properties storeProps = new Properties(); storeProps.setProperty("helix.property.store.root.path", "/" + this.clusterName); HelixPropertyStoreConfig propertyStoreConfig = new HelixPropertyStoreConfig(new VerifiableProperties(storeProps)); info("Setting partition override for all datacenters."); for (Map.Entry<String, ClusterMapUtils.DcZkInfo> entry : dataCenterToZkAddress.entrySet()) { HelixPropertyStore<ZNRecord> helixPropertyStore = ClusterMapUtils.createHelixPropertyStore(entry.getValue().getZkConnectStr(), propertyStoreConfig, null); ZNRecord znRecord = new ZNRecord(ZNRECORD_NAME); znRecord.setMapFields(partitionOverrideInfos); String path = "/" + this.clusterName + PROPERTYSTORE_PATH + "/" + ZNRECORD_NAME; if (!helixPropertyStore.set(path, znRecord, AccessOption.PERSISTENT)) { info("Failed to upload partition override for datacenter {}", entry.getKey()); } } }

Target:
private void uploadPartitionOverride(Map<String, Map<String, String>> partitionOverrideInfos) { Properties storeProps = new Properties(); storeProps.setProperty("helix.property.store.root.path", "/" + clusterName); HelixPropertyStoreConfig propertyStoreConfig = new HelixPropertyStoreConfig(new VerifiableProperties(storeProps)); info("Setting partition override for all datacenters."); for (Map.Entry<String, ClusterMapUtils.DcZkInfo> entry : dataCenterToZkAddress.entrySet()) { HelixPropertyStore<ZNRecord> helixPropertyStore = CommonUtils.createHelixPropertyStore(entry.getValue().getZkConnectStr(), propertyStoreConfig, null); ZNRecord znRecord = new ZNRecord(ClusterMapUtils.ZNODE_NAME); znRecord.setMapFields(partitionOverrideInfos); String path = ClusterMapUtils.PROPERTYSTORE_ZNODE_PATH; if (!helixPropertyStore.set(path, znRecord, AccessOption.PERSISTENT)) { info("Failed to upload partition override for datacenter {}", entry.getKey()); } } }
Source:
public void setWhitelistedValuesExpression(String expression){ this.validateWhitelistedValuesExpression(expression); this.whitelistingValueExpression = expression; }

Target:
public void setWhitelistedValuesExpression(String expression){ this.whitelistingValueExpression = expression; getConfig().setProperty(SCAN_VALUE_WHITELISTING_EXPRESSION, this.whitelistingValueExpression); whitelistingValueFilter = new ScannerParamValueFilterRule(this.whitelistingValueExpression); }
Source:
public ContentRetrieverContext(String contentRetrieverClassName, int connectionTimeout, int readTimeout, int maxPageContentLength, int numberOfEmittedFiles, int numberOfPartitionsForCrawling) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException { @SuppressWarnings("unchecked") Class<ContentRetriever> clazz = (Class<ContentRetriever>) Class.forName(contentRetrieverClassName); this.contentRetriever = clazz.getConstructor().newInstance(); this.connectionTimeout = connectionTimeout; this.readTimeout = readTimeout; this.maxPageContentLength = maxPageContentLength; this.numberOfEmittedFiles = numberOfEmittedFiles; this.numberOfPartitionsForCrawling = numberOfPartitionsForCrawling; }

Target:
public ContentRetrieverContext(String contentRetrieverClassName, int connectionTimeout, int readTimeout, int maxPageContentLength, int numberOfEmittedFiles, int numberOfPartitionsForCrawling) throws Exception { @SuppressWarnings("unchecked") Class<ContentRetriever> clazz = (Class<ContentRetriever>) Class.forName(contentRetrieverClassName); this.contentRetriever = clazz.getConstructor().newInstance(); this.connectionTimeout = connectionTimeout; this.readTimeout = readTimeout; this.maxPageContentLength = maxPageContentLength; this.numberOfEmittedFiles = numberOfEmittedFiles; this.numberOfPartitionsForCrawling = numberOfPartitionsForCrawling; }
Source:
public long getLong() throws CTFReaderException { return getLong(BIT_LONG, true); }

Target:
public long getLong() throws CTFReaderException { return get(BIT_LONG, true); }
Source:
public void toolAsWorkflow() { File cwlFile = new File(ResourceHelpers.resourceFilePath("dir6.cwl")); File cwlJSON = new File(ResourceHelpers.resourceFilePath("dir6.cwl.json")); ArrayList<String> args = new ArrayList<String>() {{ add("workflow"); add("launch"); add("--local-entry"); add(cwlFile.getAbsolutePath()); add("--json"); add(cwlJSON.getAbsolutePath()); }}; exit.expectSystemExit(); runClientCommand(args, false); assertTrue("Out should suggest to run as tool instead", systemOutRule.getLog().contains("Expected a workflow but the")); }

Target:
public void toolAsWorkflow() { File cwlFile = new File(ResourceHelpers.resourceFilePath("dir6.cwl")); File cwlJSON = new File(ResourceHelpers.resourceFilePath("dir6.cwl.json")); ArrayList<String> args = new ArrayList<String>() {{ add("workflow"); add("launch"); add("--local-entry"); add(cwlFile.getAbsolutePath()); add("--json"); add(cwlJSON.getAbsolutePath()); }}; exit.expectSystemExit(); exit.checkAssertionAfterwards( () -> assertTrue("Out should suggest to run as workflow instead", systemErrRule.getLog().contains("Expected a workflow but the"))); runClientCommand(args, false); }
Source:
public void onApplicationEvent(ApplicationPreparedEvent event) { if (this.decryptor == null) { return; } ConfigurableApplicationContext applicationContext = event .getApplicationContext(); if (!applicationContext.containsBean(DECRYPTOR_BEAN_NAME)) { applicationContext.getBeanFactory().registerSingleton (DECRYPTOR_BEAN_NAME, decryptor); } ConfigurableEnvironment environment = applicationContext.getEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); Map<String, Object> map = decrypt(propertySources); if (!map.isEmpty()) { insert(propertySources, new MapPropertySource(DECRYPTED_PROPERTY_SOURCE_NAME, map)); } }

Target:
public void onApplicationEvent(ApplicationPreparedEvent event) { if (this.decryptor == null) { return; } ConfigurableApplicationContext applicationContext = event .getApplicationContext(); if (!applicationContext.equals(this.applicationContext)){ return; } if (!applicationContext.containsBean(DECRYPTOR_BEAN_NAME)) { applicationContext.getBeanFactory().registerSingleton (DECRYPTOR_BEAN_NAME, decryptor); } ConfigurableEnvironment environment = applicationContext.getEnvironment(); MutablePropertySources propertySources = environment.getPropertySources(); Map<String, Object> map = decrypt(propertySources); if (!map.isEmpty()) { insert(propertySources, new MapPropertySource(DECRYPTED_PROPERTY_SOURCE_NAME, map)); } }
Source:
protected void migrateRealm(RealmModel realm) { for (ClientModel client : realm.getClients()) { MigrationUtils.updateProtocolMappers(client); } for (ClientScopeModel clientTemplate : realm.getClientScopes()) { MigrationUtils.updateProtocolMappers(clientTemplate); } }

Target:
protected void migrateRealm(RealmModel realm) { for (ClientModel client : realm.getClients()) { MigrationUtils.updateProtocolMappers(client); } for (ClientScopeModel clientScope : realm.getClientScopes()) { MigrationUtils.updateProtocolMappers(clientScope); } }
Source:
public int hashCode() { int result = _domainUuid != null ? _domainUuid.hashCode() : 0; result = 31 * result + (_domainName != null ? _domainName.hashCode() : 0); result = 31 * result + (_domainPath != null ? _domainPath.hashCode() : 0); result = 31 * result + (_toAdd ? 1 : 0); result = 31 * result + (_toRemove ? 1 : 0); return result; }

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (_domainUuid != null ? _domainUuid.hashCode() : 0); result = 31 * result + (_domainName != null ? _domainName.hashCode() : 0); result = 31 * result + (_domainPath != null ? _domainPath.hashCode() : 0); result = 31 * result + (_toAdd ? 1 : 0); result = 31 * result + (_toRemove ? 1 : 0); return result; }
Source:
default MergeFunction andThen(final MergeFunction that) { MergeFunction self = this; return new MergeFunction() { @Override public <C extends ValueContainer<?>> C merge(C original, C replacement) { return that.merge(self.merge(original, replacement), replacement); } }; }

Target:
default MergeFunction andThen(final MergeFunction that) { final MergeFunction self = this; return new MergeFunction() { @Override public <C extends ValueContainer<?>> C merge(C original, C replacement) { return that.merge(self.merge(original, replacement), replacement); } }; }
Source:
static void initIronSourceSDK(Activity activity, String appKey, IronSource.AD_UNIT adUnit) { if (!isIronSourceInitialized(adUnit)) { IronSource.setMediationType(MEDIATION_NAME); IronSource.initISDemandOnly(activity, appKey, adUnit); mInitialized.add(adUnit); } else { Log.d(IronSourceAdapterUtils.TAG, adUnit.toString() + " has already been initialized."); } }

Target:
static void initIronSourceSDK(Activity activity, String appKey, IronSource.AD_UNIT adUnit) { if (isIronSourceInitialized(adUnit)) { Log.d(IronSourceAdapterUtils.TAG, adUnit.toString() + " has already been initialized."); } else { IronSource.setMediationType(MEDIATION_NAME); IronSource.initISDemandOnly(activity, appKey, adUnit); mInitialized.add(adUnit); } }
Source:
public void addUserToGroup() throws NotFoundException, org.jtalks.common.service.exceptions.NotFoundException { JCUser jcUser = createUserWithGroups(4l, 5l, 6l); Group group = new Group(); when(userService.get(anyLong())).thenReturn(jcUser); when(groupService.get(anyLong())).thenReturn(group); JsonResponse jsonResponse = userController.addUserToGroup(1l, 2l); assertThat(jsonResponse.getStatus(), is(JsonResponseStatus.SUCCESS)); assertThat(group.getUsers().contains(jcUser), is(true)); assertThat(jcUser.getGroups().contains(group), is(true)); }

Target:
public void addUserToGroup() throws Exception { long userID = 1l; long groupID = 2l; Component component = createDefaultComponent(); when(componentService.getComponentOfForum()).thenReturn(component); userController.addUserToGroup(userID, groupID); verify(userService).addUserToGroup(component.getId(), userID, groupID); }
Source:
private void resolveReference(IJSONSchemaProperty node) { String reference = node.getReference(); if (reference != null) { String ref = reference.substring("#/definitions/".length()); IJSONSchemaProperty property = definitions.get(ref); if (property != null) { for (IJSONSchemaProperty p:property.getProperties().values()) { node.addProperty(p); } } Collection<IJSONSchemaProperty> props = property.getProperties().values(); for (IJSONSchemaProperty p:props) { resolveReference(p); } } Collection<IJSONSchemaProperty> props = node.getProperties().values(); for (IJSONSchemaProperty p:props) { resolveReference(p); } List<String> references = node.getReferences(); for (String ref:references) { String r = ref.substring("#/definitions/".length()); IJSONSchemaProperty property = definitions.get(r); if (property != null) { for (IJSONSchemaProperty p:property.getProperties().values()) { node.addProperty(p); } } } }

Target:
private void resolveReference(IJSONSchemaProperty node) { String reference = node.getReference(); if (reference != null) { String ref = reference.substring(DEFINITIONS.length()); IJSONSchemaProperty property = definitions.get(ref); if (property != null) { for (IJSONSchemaProperty p : property.getProperties().values()) { node.addProperty(p); } Collection<IJSONSchemaProperty> props = property.getProperties().values(); for (IJSONSchemaProperty p : props) { resolveReference(p); } } } Collection<IJSONSchemaProperty> props = node.getProperties().values(); for (IJSONSchemaProperty p:props) { resolveReference(p); } List<String> references = node.getReferences(); for (String ref:references) { String r = ref.substring(DEFINITIONS.length()); IJSONSchemaProperty property = definitions.get(r); if (property != null) { for (IJSONSchemaProperty p:property.getProperties().values()) { node.addProperty(p); } } } }
Source:
public void openingAFormToEdit_andChangingAValue_andClickingSaveAndExit_andRotating_remainsOnPrompt() { new MainMenuPage(rule) .startBlankForm("Track Changes Reason") .inputText("Nothing much...") .swipeToNextQuestion() .clickSaveAndExit() .clickEditSavedForm() .clickOnForm("Track Changes Reason") .clickGoToStart() .inputText("Nothing much!") .swipeToNextQuestion() .clickSaveAndExitWithChangesReasonPrompt() .enterReason("Something") .rotateToLandscape(new ChangesReasonPromptPage("Track Changes Reason", rule)) .assertText("Something") .rotateToPortrait(new ChangesReasonPromptPage("Track Changes Reason", rule)) .clickSave(); }

Target:
public void openingAFormToEdit_andChangingAValue_andClickingSaveAndExit_andRotating_remainsOnPrompt() { new MainMenuPage(rule) .startBlankForm("Track Changes Reason") .inputText("Nothing much...") .swipeToNextQuestion() .clickSaveAndExit() .clickEditSavedForm() .clickOnForm("Track Changes Reason") .clickGoToStart() .inputText("Nothing much!") .swipeToNextQuestion() .clickSaveAndExitWithChangesReasonPrompt() .enterReason("Something") .rotateToLandscape(new ChangesReasonPromptPage("Track Changes Reason", rule)) .assertText("Something") .closeSoftKeyboard() .clickSave(); }
Source:
public void testVmMigrationSubscription() { EventSubscriber subscriber = mock(EventSubscriber.class); when(subscriber.getSubscriptionId()).thenReturn("*|*|VM_migration_status|*"); SubscriptionHolder holder = new SubscriptionHolder(subscriber, new AtomicInteger()); EventSubscriber subscriber2 = mock(EventSubscriber.class); when(subscriber2.getSubscriptionId()).thenReturn("*|*|VM_status|*"); SubscriptionHolder holder2 = new SubscriptionHolder(subscriber2, new AtomicInteger()); SubscriptionMatcher matcher = new SubscriptionMatcher(); matcher.add(holder); matcher.add(holder2); JsonRpcEvent event = mock(JsonRpcEvent.class); when(event.getMethod()).thenReturn("10.35.18.138|virt|VM_status|d4b04c1d-c2bc-41e3-add7-bcad2ab782d4"); JsonRpcEvent event2 = mock(JsonRpcEvent.class); when(event2.getMethod()).thenReturn("10.35.0.96|virt|VM_migration_status|d4b04c1d-c2bc-41e3-add7-bcad2ab782d4"); Set<SubscriptionHolder> holders = matcher.match(event); assertEquals(1, holders.size()); Set<SubscriptionHolder> holders2 = matcher.match(event2); assertEquals(1, holders2.size()); }

Target:
public void testVmMigrationSubscription() { EventSubscriber subscriber = mock(EventSubscriber.class); when(subscriber.getSubscriptionId()).thenReturn("*|*|VM_migration_status|*"); SubscriptionHolder holder = new SubscriptionHolder(subscriber, new AtomicInteger()); EventSubscriber subscriber2 = mock(EventSubscriber.class); when(subscriber2.getSubscriptionId()).thenReturn("10.35.18.138|*|VM_status|*"); SubscriptionHolder holder2 = new SubscriptionHolder(subscriber2, new AtomicInteger()); SubscriptionMatcher matcher = new SubscriptionMatcher(); matcher.add(holder); matcher.add(holder2); JsonRpcEvent event = mock(JsonRpcEvent.class); when(event.getMethod()).thenReturn("10.35.18.138|virt|VM_status|d4b04c1d-c2bc-41e3-add7-bcad2ab782d4"); JsonRpcEvent event2 = mock(JsonRpcEvent.class); when(event2.getMethod()).thenReturn("10.35.0.96|virt|VM_migration_status|d4b04c1d-c2bc-41e3-add7-bcad2ab782d4"); Set<SubscriptionHolder> holders = matcher.match(event); assertEquals(1, holders.size()); Set<SubscriptionHolder> holders2 = matcher.match(event2); assertEquals(1, holders2.size()); }
Source:
public List<Scope> getAllSharedScopes(String tenantDomain) throws APIManagementException { if (log.isDebugEnabled()) { log.debug("Retrieving all the shared scopes for tenant: " + tenantDomain); } List<Scope> allSharedScopes = ApiMgtDAO.getInstance().getAllSharedScopes(tenantDomain); List<Scope> allScopes = scopesDAO.getScopes(APIUtil.getTenantIdFromTenantDomain(tenantDomain)); for (Scope scope : allSharedScopes) { for (Scope tempScope : allScopes) { if (scope.getKey().equals(tempScope.getKey())) { scope.setDescription(tempScope.getDescription()); scope.setRoles(tempScope.getRoles()); break; } } } return allSharedScopes; }

Target:
public List<Scope> getAllSharedScopes(String tenantDomain) throws APIManagementException { if (log.isDebugEnabled()) { log.debug("Retrieving all the shared scopes for tenant: " + tenantDomain); } List<Scope> allSharedScopes = ApiMgtDAO.getInstance().getAllSharedScopes(tenantDomain); List<Scope> allScopes = scopesDAO.getScopes(APIUtil.getTenantIdFromTenantDomain(tenantDomain)); for (Scope scope : allSharedScopes) { for (Scope tempScope : allScopes) { if (scope.getKey().equals(tempScope.getKey())) { scope.setName(tempScope.getName()); scope.setDescription(tempScope.getDescription()); scope.setRoles(tempScope.getRoles()); break; } } } return allSharedScopes; }
Source:
public static void main(String[] args) throws Exception { for (Handler h : logger.getHandlers()) { logger.removeHandler(h); } for (Handler h : LoggerJMX.getHandlers()) { LoggerJMX.removeHandler(h); } for (Handler h : Logger.getLogger("").getHandlers()) { Logger.getLogger("").removeHandler(h); } SimpleFormatter fmt = new DumbFormatter(); StreamHandler sh = new StreamHandler(System.out, fmt); Set<String> argss = new HashSet<String>(args.length); argss.addAll(Arrays.asList(args)); if (argss.contains("--time_jmx_call")) { LoggerJMX.setLevel(Level.ALL); LoggerJMX.addHandler(sh); argss.remove("--time_jmx_call"); args = argss.toArray(new String[argss.size()]); } else { logger.addHandler(sh); } List<ObjectName> objectNames = new ArrayList<ObjectName>(1); objectNames.add(null); if (args.length >= 3) { new JmxScraper(args[0], args[1], args[2], false, objectNames, new LinkedList<ObjectName>(), new JMXLogWriter()).doScrape(); } else if (args.length > 0) { new JmxScraper(args[0], "", "", false, objectNames, new LinkedList<ObjectName>(), new JMXLogWriter()).doScrape(); } else { new JmxScraper("", "", "", false, objectNames, new LinkedList<ObjectName>(), new JMXLogWriter()).doScrape(); } }

Target:
public static void main(String[] args) throws Exception { List<ObjectName> objectNames = new LinkedList<ObjectName>(); objectNames.add(null); if (args.length >= 3){ new JmxScraper(args[0], args[1], args[2], false, objectNames, new LinkedList<ObjectName>(), new StdoutWriter()).doScrape(); } else if (args.length > 0){ new JmxScraper(args[0], "", "", false, objectNames, new LinkedList<ObjectName>(), new StdoutWriter()).doScrape(); } else { new JmxScraper("", "", "", false, objectNames, new LinkedList<ObjectName>(), new StdoutWriter()).doScrape(); } }