auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { try { EventLogger.LOG.asyncFire(metadata, observer); new RunInRequest(contextId) { @Override protected void execute() { final ThreadLocalStackReference<EventMetadata> stack = currentEventMetadata.pushIfNotNull(metadata); try { Observers.notify(observer, event, metadata); } finally { stack.pop(); } } }.run(); } catch (Exception e) { String stackTrace; if (e.getCause().getMessage() != null) { stackTrace = "StackTrace: " + e.getCause().getMessage(); } else { stackTrace = "No stack trace to show, the exception's message was empty."; } EventLogger.LOG.asyncObserverFailure(observer, metadata, stackTrace); EventLogger.LOG.catchingDebug(e); } }

Target:
public void run() { try { EventLogger.LOG.asyncFire(metadata, observer); new RunInRequest(contextId) { @Override protected void execute() { final ThreadLocalStackReference<EventMetadata> stack = currentEventMetadata.pushIfNotNull(metadata); try { Observers.notify(observer, event, metadata); } finally { stack.pop(); } } }.run(); } catch (Exception e) { EventLogger.LOG.asyncObserverFailure(observer, metadata, e.getCause() != null ? e.getCause() : e); EventLogger.LOG.catchingDebug(e); } }
Source:
public void updateDataSourceListModel() { getDataSourceListModel().removeAllElements(); for (String dsName : getDataSourceArray()) { getDataSourceListModel().addElement(dsName); } setComponentsEnabled(); firePropertyChange(Bundle.DropdownListSearchPanel_selected(), null, null); }

Target:
void updateDataSourceListModel() { getDataSourceListModel().removeAllElements(); for (String dsName : getDataSourceArray()) { getDataSourceListModel().addElement(dsName); } setComponentsEnabled(); firePropertyChange(Bundle.DropdownListSearchPanel_selected(), null, null); }
Source:
public String getNetworkMode(Map<String, Object> instanceData) { Map<String, Object> labels = CollectionUtils.toMap(instanceData.get(InstanceConstants.FIELD_LABELS)); String mode = ObjectUtils.toString(labels.get(SystemLabels.LABEL_CNI_NETWORK)); if(mode == null) { String dataMode = ObjectUtils.toString(instanceData.get(DockerInstanceConstants.FIELD_NETWORK_MODE)); if (inAllowedModes(dataMode) && "true".equals(labels.get(SystemLabels.LABEL_RANCHER_NETWORK))) { mode = NetworkConstants.NETWORK_MODE_MANAGED; } else { mode = dataMode; } } return mode; }

Target:
public String getNetworkMode(Map<String, Object> instanceData) { Map<String, Object> labels = CollectionUtils.toMap(instanceData.get(InstanceConstants.FIELD_LABELS)); String mode = ObjectUtils.toString(labels.get(SystemLabels.LABEL_CNI_NETWORK)); if(mode == null) { String dataMode = ObjectUtils.toString(instanceData.get(DockerInstanceConstants.FIELD_NETWORK_MODE)); if (inAllowedModesForManaged(dataMode) && "true".equals(labels.get(SystemLabels.LABEL_RANCHER_NETWORK))) { mode = NetworkConstants.NETWORK_MODE_MANAGED; } else { mode = dataMode; } } return mode; }
Source:
public String toString() { final String from = new Throwable().getStackTrace()[1].toString(); LOGGER.warning("Use of toString() on hudson.util.Secret from "+from+". Prefer getPlainText() or getEncryptedValue() depending your needs."); return value; }

Target:
public String toString() { final String from = new Throwable().getStackTrace()[1].toString(); LOGGER.warning("Use of toString() on hudson.util.Secret from "+from+". Prefer getPlainText() or getEncryptedValue() depending your needs. see <LINK_0>"); return value; }
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { return Collections.singletonMap(getStorageDomain().getId().toString(), LockMessagesMatchUtil.STORAGE); }

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { return Collections.singletonMap(getConnection().getconnection(), LockMessagesMatchUtil.STORAGE_CONNECTION); }
Source:
public void packageApk(File apk, File manifest) { String buildRoot = System.getenv().get("ANDROID_BUILD_TOP"); String androidJarPath; if (com.google.common.base.Strings.isNullOrEmpty(buildRoot)) { androidJarPath = "prebuilts/sdk/current/android.jar"; } else { androidJarPath = buildRoot + "/prebuilts/sdk/current/android.jar"; } List<String> aapt = new ArrayList<String>(Arrays.asList("aapt", "package", "-F", apk.getPath(), "-M", manifest.getPath(), "-I", androidJarPath)); new Command(log, aapt).execute(); }

Target:
public void packageApk(File apk, File manifest) { List<String> aapt = new ArrayList<String>(Arrays.asList("aapt", "package", "-F", apk.getPath(), "-M", manifest.getPath(), "-I", androidJarPath)); new Command(log, aapt).execute(); }
Source:
public void addStateTo(StateDumpCollector dump) { PlatformConfiguration platformConfiguration = this.platformConfiguration; if (platformConfiguration != null) { Collection<Object> configurations = platformConfiguration.getExtendedConfiguration(Object.class); dump.addState("server", platformConfiguration.getServerName()); dump.addState("configurationCount", String.valueOf(configurations)); Map<String, List<Object>> pluginsByType = configurations .stream() .collect(Collectors.groupingBy(o -> o.getClass().getName())); for (Map.Entry<String, List<Object>> entry : pluginsByType.entrySet()) { StateDumpCollector typeDump = dump.subStateDumpCollector(entry.getKey()); typeDump.addState("configurationCount", String.valueOf(entry.getValue().size())); for (Object plugin : entry.getValue()) { StateDumpCollector pluginDump = typeDump.subStateDumpCollector(String.valueOf(plugin.hashCode())); pluginDump.addState("manageable", String.valueOf(plugin instanceof ManageableServerComponent)); if (plugin instanceof StateDumpable) { ((StateDumpable) plugin).addStateTo(pluginDump); } } } } TopologyService topologyService = this.topologyService; if (topologyService != null) { dump.addState("cluster", topologyService.getClusterCopy().toMap().toString()); } }

Target:
public void addStateTo(StateDumpCollector dump) { PlatformConfiguration platformConfiguration = this.platformConfiguration; if (platformConfiguration != null) { Collection<Object> configurations = platformConfiguration.getExtendedConfiguration(Object.class); dump.addState("server", platformConfiguration.getServerName()); dump.addState("configurationCount", String.valueOf(configurations.size())); Map<String, List<Object>> pluginsByType = configurations .stream() .collect(Collectors.groupingBy(o -> o.getClass().getName())); for (Map.Entry<String, List<Object>> entry : pluginsByType.entrySet()) { StateDumpCollector typeDump = dump.subStateDumpCollector(entry.getKey()); typeDump.addState("configurationCount", String.valueOf(entry.getValue().size())); int plugin_idx = 0; for (Object plugin : entry.getValue()) { StateDumpCollector pluginDump = typeDump.subStateDumpCollector(String.valueOf(plugin_idx++)); pluginDump.addState("manageable", String.valueOf(plugin instanceof ManageableServerComponent)); if (plugin instanceof StateDumpable) { ((StateDumpable) plugin).addStateTo(pluginDump); } } } } TopologyService topologyService = this.topologyService; if (topologyService != null) { dump.addState("cluster", topologyService.getClusterCopy().toMap().toString()); } }
Source:
public void showFetchingErrorCharges(String s) { if (mApiRestCounter == 1) { ll_error.setVisibility(View.VISIBLE); mNoChargesText.setText(s + "\n" + getString(R.string.click_to_refresh)); } Toaster.show(rootView, s); }

Target:
public void showFetchingErrorCharges(String s) { if (mApiRestCounter == 1) { ll_error.setVisibility(View.VISIBLE); mNoChargesText.setText(s + getString(R.string.click_to_refresh)); } Toaster.show(rootView, s); }
Source:
public void addExtraData(String variable, Object variableValue) { if (this.data == null) { this.data = new HashMap<String, Object>(); } this.data.put(variable, variableValue); }

Target:
public void addExtraData(String variable, Object variableValue) { if (this.data == null) { this.data = new HashMap<>(); } this.data.put(variable, variableValue); }
Source:
boolean canConnect(VDS vds) { boolean returnValue = true; if (vds.getVdsType() == VDSType.VDS && Config.<Boolean> GetValue(ConfigValues.InstallVds)) { SSHClient sshclient = null; try { Long timeout = TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds)); sshclient = getSSHClient(); sshclient.setHardTimeout(timeout); sshclient.setSoftTimeout(timeout); sshclient.setHost(vds.getHostName()); sshclient.setUser(USER_NAME); sshclient.setPassword(getParameters().getRootPassword()); sshclient.connect(); sshclient.authenticate(); } catch (AuthenticationException e) { log.errorFormat( "Failed to authenticate session with host {0}", vds.getName(), e ); addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_AUTHENTICATE_TO_SERVER); returnValue = false; } catch (Exception e) { log.errorFormat( "Failed to establish session with host {0}", vds.getName(), e ); addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_CONNECT_TO_SERVER); returnValue = false; } finally { if (sshclient != null) { sshclient.disconnect(); } } } return returnValue; }

Target:
protected boolean canConnect(VDS vds) { boolean returnValue = true; if (vds.getVdsType() == VDSType.VDS && Config.<Boolean> GetValue(ConfigValues.InstallVds)) { SSHClient sshclient = null; try { Long timeout = TimeUnit.SECONDS.toMillis(Config.<Integer> GetValue(ConfigValues.ConnectToServerTimeoutInSeconds)); sshclient = getSSHClient(); sshclient.setHardTimeout(timeout); sshclient.setSoftTimeout(timeout); sshclient.setHost(vds.getHostName()); sshclient.setUser(USER_NAME); sshclient.setPassword(getParameters().getRootPassword()); sshclient.connect(); sshclient.authenticate(); } catch (AuthenticationException e) { log.errorFormat( "Failed to authenticate session with host {0}", vds.getName(), e ); addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_AUTHENTICATE_TO_SERVER); returnValue = false; } catch (Exception e) { log.errorFormat( "Failed to establish session with host {0}", vds.getName(), e ); addCanDoActionMessage(VdcBllMessages.VDS_CANNOT_CONNECT_TO_SERVER); returnValue = false; } finally { if (sshclient != null) { sshclient.disconnect(); } } } return returnValue; }
Source:
public void testInitializeDatastream() throws Exception { String sourceRegex = "\\w+Event"; StringMap metadata = new StringMap(); metadata.put(DatastreamMetadataConstants.REUSE_EXISTING_DESTINATION_KEY, Boolean.FALSE.toString()); Datastream ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream", _broker, sourceRegex, metadata); KafkaMirrorMakerConnector connector = new KafkaMirrorMakerConnector("testInitializeDatastream", KafkaMirrorMakerConnectorTestUtils.getDefaultConfig(Optional.empty()), "testCluster"); connector.initializeDatastream(ds, Collections.emptyList()); sourceRegex = "SpecificTopic"; ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream2", _broker, sourceRegex, metadata); connector.initializeDatastream(ds, Collections.emptyList()); sourceRegex = "(\\w+Event)|^(Topic)"; ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream3", _broker, sourceRegex, metadata); connector.initializeDatastream(ds, Collections.emptyList()); sourceRegex = "^(?!__)\\w+"; ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream4", _broker, sourceRegex, metadata); connector.initializeDatastream(ds, Collections.emptyList()); Assert.assertTrue(DatastreamUtils.isConnectorManagedDestination(ds)); }

Target:
public void testInitializeDatastream() throws Exception { String sourceRegex = "\\w+Event"; StringMap metadata = new StringMap(); metadata.put(DatastreamMetadataConstants.REUSE_EXISTING_DESTINATION_KEY, Boolean.FALSE.toString()); Datastream ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream", _broker, sourceRegex, metadata); KafkaMirrorMakerConnector connector = new KafkaMirrorMakerConnector("testInitializeDatastream", getDefaultConfig(Optional.empty()), "testCluster"); connector.initializeDatastream(ds, Collections.emptyList()); sourceRegex = "SpecificTopic"; ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream2", _broker, sourceRegex, metadata); connector.initializeDatastream(ds, Collections.emptyList()); sourceRegex = "(\\w+Event)|^(Topic)"; ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream3", _broker, sourceRegex, metadata); connector.initializeDatastream(ds, Collections.emptyList()); sourceRegex = "^(?!__)\\w+"; ds = KafkaMirrorMakerConnectorTestUtils.createDatastream("testInitializeDatastream4", _broker, sourceRegex, metadata); connector.initializeDatastream(ds, Collections.emptyList()); Assert.assertTrue(DatastreamUtils.isConnectorManagedDestination(ds)); }
Source:
private void onYield() { if (logger.isLoggable(java.util.logging.Level.FINE)) { logger.fine("Yielding AsyncQueueHandler associated with " + "AsyncQueueHandler with ID = " + id); } synchronized (syncRoot) { cancel(false); readerFuture = executor.submit(reader); } }

Target:
private void onYield() { if (logger.isLoggable(java.util.logging.Level.FINE)) { logger.fine("Yielding AsyncQueueHandler with ID = " + id); } rescheduleReader(); }
Source:
public void close() { assertIsOpen(); LOGGER.debug().setMessage("Closing DatabaseAlertExecutionRepository").log(); assert _partitionCreator != null : "partitionCreator should be non-null when open"; try { DailyPartitionCreator.stop(_partitionCreator, Duration.ofSeconds(5)); _partitionCreator = null; } catch (final ExecutionException | InterruptedException e) { throw new RuntimeException("Failed to shutdown partition creator", e); } _isOpen.set(false); }

Target:
public void close() { assertIsOpen(); LOGGER.debug().setMessage("Closing DatabaseAlertExecutionRepository").log(); if (_partitionCreator == null) { throw new IllegalStateException("partitionCreator should be non-null when open"); } try { Patterns.gracefulStop(_partitionCreator, ACTOR_STOP_TIMEOUT) .toCompletableFuture() .get(ACTOR_STOP_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); _partitionCreator = null; } catch (final TimeoutException | ExecutionException | InterruptedException e) { throw new RuntimeException("Failed to shutdown partition creator", e); } _isOpen.set(false); }
Source:
public void processLeftWatermark(final MistWatermarkEvent input) { outputEmitter.emitWatermark(input); if (input.isCheckpoint()) { latestCheckpointTimestamp = input.getTimestamp(); final Map<String, Object> stateMap = new HashMap<>(); stateMap.put("applyStatefulFunctionState", applyStatefulFunction.getCurrentState()); checkpointMap.put(input.getTimestamp(), stateMap); } }

Target:
public void processLeftWatermark(final MistWatermarkEvent input) { if (isEarlierThanRecoveredTimestamp(input)) { return; } updateLatestEventTimestamp(input.getTimestamp()); outputEmitter.emitWatermark(input); }
Source:
private static SslContextBuilder createGrpcSslBuilder() { try { SslContextBuilder sslBuilder = GrpcSslContexts.forClient(); sslBuilder.ciphers(null); return sslBuilder; } catch (IllegalArgumentException e) { LOG.error("Could not initialize GrpcSslContexts", e); return null; } }

Target:
private static SslContextBuilder createGrpcSslBuilder() { SslContextBuilder sslBuilder = GrpcSslContexts.forClient(); sslBuilder.ciphers(null); return sslBuilder; }
Source:
public int presentAsFile(final File file, final List<CertifiedProductSearchDetails> cpList) { int numRows = 0; try { try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL);) { csvPrinter.printRecord(generateHeaderValues()); for (CertifiedProductSearchDetails currListing : cpList) { List<List<String>> rows = generateRows(currListing); if (rows != null) { for(List<String> row : rows) { csvPrinter.printRecord(row); numRows++; } } } } } catch (final IOException ex) { LOGGER.error("Could not write file " + file.getName(), ex); } return numRows; }

Target:
public int presentAsFile(final File file, final List<CertifiedProductSearchDetails> cpList) { int numRows = 0; try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8); CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL)) { csvPrinter.printRecord(generateHeaderValues()); for (CertifiedProductSearchDetails currListing : cpList) { List<List<String>> rows = generateRows(currListing); if (rows != null) { for(List<String> row : rows) { csvPrinter.printRecord(row); numRows++; } } } } catch (final IOException ex) { LOGGER.error("Could not write file " + file.getName(), ex); } return numRows; }
Source:
public void setConfiguration(String key, String value) { if (value == null) { removeConfiguration(key); } else { configuration.put(key, value); } }

Target:
public void setConfiguration(String key, String value) { configuration.put(key, Objects.requireNonNull(value)); }
Source:
public Iterator<Message> iterator() { try { final ByteArrayDataInput input = ByteStreams.newDataInput( Compression.create(messageSet.getCompression()).decompress(messageSet.getMessages())); return new Iterator<Message>() { private int messageCount = messageSet.getNumMessages(); @Override public boolean hasNext() { return messageCount > 0; } @Override public Message next() { Message m = new Message(); try { m.readFields(input); --messageCount; return m; } catch (Exception e) { log.error("Exception while iterating MessageSet:" + e.getMessage(), e); messageCount = 0; return null; } } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported"); } }; } catch (Exception e) { log.error("Exception while reading: " + e.getMessage(), e); return new Iterator<Message>() { @Override public boolean hasNext() { return false; } @Override public Message next() { return null; } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported"); } }; } }

Target:
public Iterator<Message> iterator() { try { final ByteArrayDataInput input = ByteStreams.newDataInput( Compression.create(messageSet.getCompression()).decompress(messageSet.getMessages())); return new Iterator<Message>() { private int messageCount = messageSet.getNumMessages(); @Override public boolean hasNext() { return messageCount > 0; } @Override public Message next() { Message m = new Message(); try { m.readFields(input); --messageCount; return m; } catch (Exception e) { log.error("Exception while iterating MessageSet:" + e.getMessage(), e); DynamicCounter.increment( MonitorConfig.builder(TagKey.DROPPED_COUNT) .withTag("reason", "MessageSetReaderError").build(), messageCount); messageCount = 0; return null; } } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported"); } }; } catch (Exception e) { log.error("Exception while reading: " + e.getMessage(), e); return new Iterator<Message>() { @Override public boolean hasNext() { return false; } @Override public Message next() { return null; } @Override public void remove() { throw new UnsupportedOperationException("remove is not supported"); } }; } }
Source:
private void initializeAppearColorTableColumns(Composite tableComposite) { final TableViewerColumn labelColumn= new TableViewerColumn(fAppearanceColorTableViewer, SWT.NONE, 0); final TableViewerColumn colorPreviewColumn= new TableViewerColumn(fAppearanceColorTableViewer, SWT.NONE, 1); TableColumnLayout tableColumnLayout= new TableColumnLayout(true); PixelConverter pixelConverter= new PixelConverter(tableComposite.getParent().getFont()); tableColumnLayout.setColumnData(labelColumn.getColumn(), new ColumnWeightData(1, pixelConverter.convertWidthInCharsToPixels(30))); tableColumnLayout.setColumnData(colorPreviewColumn.getColumn(), new ColumnWeightData(0, pixelConverter.convertWidthInCharsToPixels(5))); labelColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object element) { return ((String[]) element)[0]; } }); colorPreviewImages= new ArrayList<>(); colorPreviewColumn.setLabelProvider(new ColumnLabelProvider() { @Override public Image getImage(Object element) { int dimensions= 10; String key= ((String[]) element)[1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); Color color= new Color(tableComposite.getParent().getDisplay(), rgb.red, rgb.green, rgb.blue); Image image= new Image(tableComposite.getParent().getDisplay(), dimensions, dimensions); GC gc= new GC(image); gc.setBackground(color); gc.fillRectangle(0, 0, dimensions, dimensions); gc.setBackground(new Color(tableComposite.getParent().getDisplay(), 0, 0, 0)); gc.setLineWidth(2); gc.drawRectangle(0, 0, dimensions, dimensions); gc.dispose(); colorPreviewImages.add(image); return image; } @Override public String getText(Object element) { return null; } }); tableComposite.setLayout(tableColumnLayout); }

Target:
private void initializeAppearColorTableColumns(Composite tableComposite) { colorPreviewImages= new ArrayList<>(); fAppearanceColorTableViewer.setLabelProvider(new LabelProvider() { @Override public Image getImage(Object element) { int dimensions= 10; String key= ((String[]) element)[1]; RGB rgb= PreferenceConverter.getColor(fOverlayStore, key); Color color= new Color(tableComposite.getParent().getDisplay(), rgb.red, rgb.green, rgb.blue); Image image= new Image(tableComposite.getParent().getDisplay(), dimensions, dimensions); GC gc= new GC(image); gc.setBackground(color); gc.fillRectangle(0, 0, dimensions, dimensions); gc.setBackground(new Color(tableComposite.getParent().getDisplay(), 0, 0, 0)); gc.setLineWidth(2); gc.drawRectangle(0, 0, dimensions, dimensions); gc.dispose(); colorPreviewImages.add(image); return image; } @Override public String getText(Object element) { return ((String[]) element)[0]; } }); TableColumn tc= new TableColumn(fAppearanceColorTableViewer.getTable(), SWT.NONE, 0); TableColumnLayout tableColumnLayout= new TableColumnLayout(true); PixelConverter pixelConverter= new PixelConverter(tableComposite.getParent().getFont()); tableColumnLayout.setColumnData(tc, new ColumnWeightData(1, pixelConverter.convertWidthInCharsToPixels(30))); tableComposite.setLayout(tableColumnLayout); }
Source:
public Pair<List<? extends UsageVO>, Integer> getUsageRecordsPendingQuotaAggregation(final long accountId, final long domainId) { if (s_logger.isDebugEnabled()){ s_logger.debug("Getting usage records for account: " + accountId + ", domainId: " + domainId); } final short opendb = TransactionLegacy.currentTxn().getDatabaseId(); Pair<List<UsageVO>, Integer> usageRecords = new Pair<List<UsageVO>, Integer>(new ArrayList<UsageVO>(), 0); try { TransactionLegacy.open(TransactionLegacy.USAGE_DB).close(); Filter usageFilter = new Filter(UsageVO.class, "startDate", true, 0L, 10000L); SearchCriteria<UsageVO> sc = createSearchCriteria(); if (accountId != -1) { sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); } if (domainId != -1) { sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId); } sc.addAnd("quotaCalculated", SearchCriteria.Op.NULL); sc.addOr("quotaCalculated", SearchCriteria.Op.EQ, 0); if (s_logger.isDebugEnabled()){ s_logger.debug("Getting usage records" + usageFilter.getOrderBy()); } usageRecords = searchAndCountAllRecords(sc, usageFilter); } catch (Exception e) { s_logger.error("getUsageRecordsPendingQuotaAggregation failed due to: " + e.getMessage()); } finally { TransactionLegacy.open(opendb).close(); } return new Pair<List<? extends UsageVO>, Integer>(usageRecords.first(), usageRecords.second()); }

Target:
public Pair<List<? extends UsageVO>, Integer> getUsageRecordsPendingQuotaAggregation(final long accountId, final long domainId) { if (s_logger.isDebugEnabled()) { s_logger.debug("Getting usage records for account: " + accountId + ", domainId: " + domainId); } return Transaction.execute(TransactionLegacy.USAGE_DB, new TransactionCallback<Pair<List<? extends UsageVO>, Integer>>() { @Override public Pair<List<? extends UsageVO>, Integer> doInTransaction(final TransactionStatus status) { Pair<List<UsageVO>, Integer> usageRecords = new Pair<List<UsageVO>, Integer>(new ArrayList<UsageVO>(), 0); Filter usageFilter = new Filter(UsageVO.class, "startDate", true, 0L, Long.MAX_VALUE); QueryBuilder<UsageVO> qb = QueryBuilder.create(UsageVO.class); if (accountId != -1) { qb.and(qb.entity().getAccountId(), SearchCriteria.Op.EQ, accountId); } if (domainId != -1) { qb.and(qb.entity().getDomainId(), SearchCriteria.Op.EQ, domainId); } qb.and(qb.entity().getQuotaCalculated(), SearchCriteria.Op.NEQ, 1); qb.and(qb.entity().getRawUsage(), SearchCriteria.Op.GT, 0); if (s_logger.isDebugEnabled()) { s_logger.debug("Getting usage records" + usageFilter.getOrderBy()); } usageRecords = searchAndCountAllRecords(qb.create(), usageFilter); return new Pair<List<? extends UsageVO>, Integer>(usageRecords.first(), usageRecords.second()); } }); }
Source:
private void setupRestrictedNotification() { final Resources res = getResources(mContext, mActiveDataSubId); final String title = res.getString(R.string.disable_tether_notification_title); final String message = res.getString(R.string.disable_tether_notification_message); showNotification(R.drawable.stat_sys_tether_general, title, message, ""); }

Target:
void setupRestrictedNotification() { final Resources res = getResources(mContext, mActiveDataSubId); final String title = res.getString(R.string.disable_tether_notification_title); final String message = res.getString(R.string.disable_tether_notification_message); showNotification(R.drawable.stat_sys_tether_general, title, message, ""); }
Source:
private ExportPanelForm(ConfigurationPanel confPanel, FormsTable formsTable) { this.confPanel = confPanel; this.confPanelForm = confPanel.getForm(); this.formsTable = formsTable; this.formsTableForm = formsTable.getView(); $$$setupUI$$$(); exportingLabel.setMinimumSize(exportingLabel.getPreferredSize()); exportingLabel.setPreferredSize(exportingLabel.getPreferredSize()); selectAllButton.addActionListener(__ -> formsTable.selectAll()); clearAllButton.addActionListener(__ -> formsTable.clearAll()); exporting = false; }

Target:
private ExportPanelForm(ConfigurationPanel confPanel, FormsTable formsTable) { this.confPanel = confPanel; this.confPanelForm = confPanel.getForm(); this.formsTable = formsTable; this.formsTableForm = formsTable.getView(); $$$setupUI$$$(); selectAllButton.addActionListener(__ -> formsTable.selectAll()); clearAllButton.addActionListener(__ -> formsTable.clearAll()); exporting = false; }
Source:
public CompositeMessageConverter getMessageConverterForTargetType(MimeType targetMimeType) { List<MessageConverter> targetMimeTypeConverters = new ArrayList<MessageConverter>(); for (MessageConverter converter : converters) { if (converter instanceof TargetTypeMessageConverter) { TargetTypeMessageConverter targetTypeMessageConverter = (TargetTypeMessageConverter) converter; if (targetTypeMessageConverter.supportsTargetMimeType(targetMimeType)) { targetMimeTypeConverters.add(converter); } } } if (CollectionUtils.isEmpty(targetMimeTypeConverters)) { throw new ConversionException("No message converter is registered for " + targetMimeType.toString()); } return new CompositeMessageConverter(targetMimeTypeConverters); }

Target:
public CompositeMessageConverter getMessageConverterForTargetType(MimeType targetMimeType) { List<MessageConverter> targetMimeTypeConverters = new ArrayList<MessageConverter>(); for (MessageConverter converter : converters) { if (converter instanceof TargetMimeTypeMessageConverter) { TargetMimeTypeMessageConverter targetTypeMessageConverter = (TargetMimeTypeMessageConverter) converter; if (!ObjectUtils.isEmpty(targetTypeMessageConverter.getSupportedJavaTypes(targetMimeType))) { targetMimeTypeConverters.add(converter); } } } if (CollectionUtils.isEmpty(targetMimeTypeConverters)) { throw new ConversionException("No message converter is registered for " + targetMimeType.toString()); } return new CompositeMessageConverter(targetMimeTypeConverters); }
Source:
public boolean restartInErrorTask(final JobId jobId, final String taskName) throws UnknownJobException, UnknownTaskException { try { if (status.isUnusable()) { return false; } Boolean result = infrastructure.getClientOperationsThreadPool().submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { jobs.restartInErrorTask(jobId, taskName); wakeUpSchedulingThread(); return Boolean.TRUE; } }).get(); return result; } catch (ExecutionException e) { if (e.getCause() instanceof UnknownTaskException) { throw (UnknownTaskException) e.getCause(); } else if (e.getCause() instanceof UnknownJobException) { throw (UnknownJobException) e.getCause(); } else { throw launderThrowable(e.getCause()); } } catch (Exception e) { throw launderThrowable(e); } }

Target:
public boolean restartInErrorTask(final JobId jobId, final String taskName) throws UnknownJobException, UnknownTaskException { try { if (status.isUnusable()) { return false; } return infrastructure.getClientOperationsThreadPool().submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { jobs.restartInErrorTask(jobId, taskName); wakeUpSchedulingThread(); return Boolean.TRUE; } }).get(); } catch (ExecutionException e) { if (e.getCause() instanceof UnknownTaskException) { throw (UnknownTaskException) e.getCause(); } else if (e.getCause() instanceof UnknownJobException) { throw (UnknownJobException) e.getCause(); } else { throw launderThrowable(e.getCause()); } } catch (Exception e) { throw launderThrowable(e); } }
Source:
private static Observable<Integer> createSource(int numItems) { return Observable.fromPublisher(publisher -> { for (int i = 1; i <= numItems; i++) { publisher.onNext(i); } }); }

Target:
private static Observable<Integer> createSource(int numItems) { return Observable.range(1, numItems) .concatWith(Observable.never()); }
Source:
public void test_presentValue_formula_shift() { CurrencyAmount computedCaplet = PRICER.presentValue(CAPLET_LONG, RATES, SHIFTED_VOLS); CurrencyAmount computedFloorlet = PRICER.presentValue(FLOORLET_SHORT, RATES, SHIFTED_VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = SHIFTED_VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = SHIFTED_VOLS.volatility(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double shift = IborCapletFloorletDataSet.SHIFT; double expectedCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.price(forward + shift, STRIKE + shift, expiry, volatility, true); double expectedFloorlet = -NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.price(forward + shift, STRIKE + shift, expiry, volatility, false); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); }

Target:
public void test_presentValue_formula_shift() { CurrencyAmount computedCaplet = PRICER.presentValue(CAPLET_LONG, RATES, SHIFTED_VOLS); CurrencyAmount computedFloorlet = PRICER.presentValue(FLOORLET_SHORT, RATES, SHIFTED_VOLS); double forward = RATES.iborIndexRates(EUR_EURIBOR_3M).rate(RATE_COMP.getObservation()); double expiry = SHIFTED_VOLS.relativeTime(CAPLET_LONG.getFixingDateTime()); double volatility = SHIFTED_VOLS.volatility(expiry, STRIKE, forward); double df = RATES.discountFactor(EUR, CAPLET_LONG.getPaymentDate()); double shift = IborCapletFloorletDataSet.SHIFT; double expectedCaplet = NOTIONAL * df * CAPLET_LONG.getYearFraction() * BlackFormulaRepository.price(forward + shift, STRIKE + shift, expiry, volatility, true); double expectedFloorlet = -NOTIONAL * df * FLOORLET_SHORT.getYearFraction() * BlackFormulaRepository.price(forward + shift, STRIKE + shift, expiry, volatility, false); assertEquals(computedCaplet.getCurrency(), EUR); assertEquals(computedCaplet.getAmount(), expectedCaplet, NOTIONAL * TOL); assertEquals(computedFloorlet.getCurrency(), EUR); assertEquals(computedFloorlet.getAmount(), expectedFloorlet, NOTIONAL * TOL); }
Source:
public static File findIndex(final File samFile) { File indexFile; final String fileName = samFile.getName(); if (fileName.endsWith(BamFileIoUtils.BAM_FILE_EXTENSION)) { final String bai = fileName.substring(0, fileName.length() - BamFileIoUtils.BAM_FILE_EXTENSION.length()) + BAMIndex.BAMIndexSuffix; indexFile = new File(samFile.getParent(), bai); if (indexFile.isFile()) return indexFile; } else if (fileName.endsWith(CramIO.CRAM_FILE_EXTENSION)) { final String crai = fileName.substring(0, fileName.length() - CramIO.CRAM_FILE_EXTENSION.length()) + CRAIIndex.CRAIIndexSuffix; indexFile = new File(samFile.getParent(), crai); if (indexFile.isFile()) return indexFile; indexFile = new File(samFile.getParent(), samFile.getName() + CRAIIndex.CRAIIndexSuffix); if (indexFile.isFile()) return indexFile; } indexFile = new File(samFile.getParent(), samFile.getName() + BAMIndex.BAMIndexSuffix); if (indexFile.isFile()) return indexFile; return null; }

Target:
public static File findIndex(final File samFile) { File indexFile; final String fileName = samFile.getName(); if (fileName.endsWith(BamFileIoUtils.BAM_FILE_EXTENSION)) { final String bai = fileName.substring(0, fileName.length() - BamFileIoUtils.BAM_FILE_EXTENSION.length()) + BAMIndex.BAMIndexSuffix; indexFile = new File(samFile.getParent(), bai); if (indexFile.isFile()) { return indexFile; } } else if (fileName.endsWith(CramIO.CRAM_FILE_EXTENSION)) { final String crai = fileName.substring(0, fileName.length() - CramIO.CRAM_FILE_EXTENSION.length()) + CRAIIndex.CRAI_INDEX_SUFFIX; indexFile = new File(samFile.getParent(), crai); if (indexFile.isFile()) { return indexFile; } indexFile = new File(samFile.getParent(), samFile.getName() + CRAIIndex.CRAI_INDEX_SUFFIX); if (indexFile.isFile()) { return indexFile; } } indexFile = new File(samFile.getParent(), samFile.getName() + BAMIndex.BAMIndexSuffix); if (indexFile.isFile()) { return indexFile; } return null; }
Source:
protected Image getCachedImage(final String key, Rectangle clientArea, Graphics graphics) { Image result = AbstractCachedSVGFigure.SVG_IMG_CACHE.getIfPresent(key); if (result == null) { Document document = getDocument(); if (document == null) { return null; } getTranscoder().setCanvasSize(getSpecifyCanvasWidth() ? clientArea.width : -1, getSpecifyCanvasHeight() ? clientArea.height : -1); updateRenderingHints(graphics); BufferedImage awtImage = getTranscoder().getBufferedImage(); if (awtImage != null) { result = toSWT(Display.getCurrent(), awtImage); SVG_IMG_CACHE.put(key, result); } } return result; }

Target:
protected Image getCachedImage(final String key, Rectangle clientArea, Graphics graphics) { Image result = AbstractCachedSVGFigure.SVG_IMG_CACHE.getIfPresent(key); if (result == null) { Document document = getDocument(); if (document == null) { return null; } getTranscoder().setCanvasSize(getSpecifyCanvasWidth() ? clientArea.width : -1, getSpecifyCanvasHeight() ? clientArea.height : -1); updateRenderingHints(graphics); BufferedImage awtImage = getTranscoder().getBufferedImage(); if (awtImage != null) { result = toSWT(Display.getCurrent(), awtImage); AbstractCachedSVGFigure.SVG_IMG_CACHE.put(key, result); } } return result; }
Source:
private void generateActionDoc(Method method, Predicate<Parameter> predicate) { buffer.startComment(); if (method.getDoc() != null) { generateDocText(method); buffer.addLine(); } if (method.parameters().filter(predicate).findFirst().orElse(null) != null) { List<String> lines = method.parameters() .filter(predicate) .filter(p -> p.getDoc() != null) .map(p -> String.format("`%s`:: %s", pythonNames.getMemberStyleName(p.getName()), p.getDoc())) .collect(toList()); if (!lines.isEmpty()) { buffer.addLine("This method supports the following parameters:"); buffer.addLine(); lines.forEach(this::generateDocText); buffer.addLine("`headers`:: Additional HTTP headers."); buffer.addLine(); buffer.addLine("`query`:: Additional URL query parameters."); buffer.addLine(); buffer.addLine("`wait`:: If true wait for the response."); } } buffer.endComment(); }

Target:
private void generateActionDoc(Method method, Predicate<Parameter> predicate) { buffer.startComment(); if (method.getDoc() != null) { generateDocText(method); buffer.addLine(); } if (method.parameters().filter(predicate).findFirst().orElse(null) != null) { List<String> lines = method.parameters() .filter(predicate) .filter(p -> p.getDoc() != null) .map(p -> String.format("`%s`:: %s", pythonNames.getMemberStyleName(p.getName()), p.getDoc())) .collect(toList()); if (!lines.isEmpty()) { buffer.addLine("This method supports the following parameters:"); buffer.addLine(); lines.forEach(this::generateDocText); buffer.addLine("`headers`:: Additional HTTP headers."); buffer.addLine(); buffer.addLine("`query`:: Additional URL query parameters."); buffer.addLine(); buffer.addLine("`wait`:: If `True` wait for the response."); } } buffer.endComment(); }
Source:
private void handleWsStart(WorkspaceDto workspace) { initialLoadingInfo.setOperationStatus(WORKSPACE_BOOTING.getValue(), SUCCESS); setCurrentWorkspace(workspace); EnvironmentDto currentEnvironment = null; for (EnvironmentDto environment : workspace.getConfig().getEnvironments()) { if (environment.getName().equals(workspace.getConfig().getDefaultEnv())) { currentEnvironment = environment; break; } } List<MachineConfigDto> machineConfigs = currentEnvironment != null ? currentEnvironment.getMachineConfigs() : new ArrayList<MachineConfigDto>(); for (MachineConfigDto machineConfig : machineConfigs) { if (machineConfig.isDev()) { MachineManager machineManager = machineManagerProvider.get(); machineManager.onDevMachineCreating(machineConfig); } } }

Target:
private void handleWsStart(WorkspaceDto workspace) { initialLoadingInfo.setOperationStatus(WORKSPACE_BOOTING.getValue(), SUCCESS); setCurrentWorkspace(workspace); EnvironmentDto currentEnvironment = null; for (EnvironmentDto environment : workspace.getConfig().getEnvironments()) { if (environment.getName().equals(workspace.getConfig().getDefaultEnv())) { currentEnvironment = environment; break; } } List<MachineConfigDto> machineConfigs = currentEnvironment != null ? currentEnvironment.getMachineConfigs() : Collections.<MachineConfigDto>emptyList(); for (MachineConfigDto machineConfig : machineConfigs) { if (machineConfig.isDev()) { MachineManager machineManager = machineManagerProvider.get(); machineManager.onDevMachineCreating(machineConfig); } } }
Source:
public synchronized @Nonnull String addFixedNewToken(@Nonnull String name, @Nonnull String tokenPlainValue) { if (tokenPlainValue.length() != 2 + 32) { LOGGER.log(Level.INFO, "addFixedNewToken, length received: {0}" + tokenPlainValue.length()); throw new IllegalArgumentException("The token must consist of 2 characters for the version and 32 hex-characters for the secret"); } String hashVersion = tokenPlainValue.substring(0, 2); if (!HASH_VERSION.equals(hashVersion)) { throw new IllegalArgumentException("The given version is not recognized: " + hashVersion); } String tokenPlainHexValue = tokenPlainValue.substring(2); tokenPlainHexValue = tokenPlainHexValue.toLowerCase(); if (!tokenPlainHexValue.matches("[a-f0-9]{32}")) { throw new IllegalArgumentException("The secret part of the token must consist of 32 hex-characters"); } HashedToken token = prepareAndStoreToken(name, tokenPlainHexValue); return token.uuid; }

Target:
public synchronized @Nonnull String addFixedNewToken(@Nonnull String name, @Nonnull String tokenPlainValue) { if (tokenPlainValue.length() != VERSION_LENGTH + HEX_CHAR_LENGTH) { LOGGER.log(Level.INFO, "addFixedNewToken, length received: {0}" + tokenPlainValue.length()); throw new IllegalArgumentException("The token must consist of 2 characters for the version and 32 hex-characters for the secret"); } String hashVersion = tokenPlainValue.substring(0, VERSION_LENGTH); if (!HASH_VERSION.equals(hashVersion)) { throw new IllegalArgumentException("The given version is not recognized: " + hashVersion); } String tokenPlainHexValue = tokenPlainValue.substring(VERSION_LENGTH); tokenPlainHexValue = tokenPlainHexValue.toLowerCase(); if (!CHECK_32_HEX_CHAR.matcher(tokenPlainHexValue).matches()) { throw new IllegalArgumentException("The secret part of the token must consist of 32 hex-characters"); } HashedToken token = prepareAndStoreToken(name, tokenPlainHexValue); return token.uuid; }
Source:
public PublicAccessLogRequestHandler(PublicAccessLogger publicAccessLogger) { this.publicAccessLogger = publicAccessLogger; }

Target:
public PublicAccessLogRequestHandler(PublicAccessLogger publicAccessLogger) { this.publicAccessLogger = publicAccessLogger; reset(); }
Source:
public void testToFlowElement_process() throws Exception { final BaseReusableSubprocess definition = new ReusableSubprocess(); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertFalse(CustomElement.isCase.of(propertyWriter.getFlowElement()).get()); }

Target:
public void testToFlowElement_process() { final BaseReusableSubprocess definition = new ReusableSubprocess(); final View<BaseReusableSubprocess> view = new ViewImpl<>(definition, Bounds.create()); final Node<View<BaseReusableSubprocess>, ?> node = new NodeImpl<>(java.util.UUID.randomUUID().toString()); node.setContent(view); final PropertyWriter propertyWriter = tested.toFlowElement(node); assertTrue(CallActivityPropertyWriter.class.isInstance(propertyWriter)); assertFalse(CustomElement.isCase.of(propertyWriter.getFlowElement()).get()); }
Source:
public Set<InstalledDriver> getInstalledDrivers(String profileName) { String profile = profileName != null ? profileName : "default"; return Collections.unmodifiableSet(Collections.synchronizedSet(new HashSet<InstalledDriver>(drivers.get(profile).values()))); }

Target:
public Set<InstalledDriver> getInstalledDrivers(String profileName) { String profile = profileName != null ? profileName : DEFAULT_PROFILE; if (drivers.get(profile) == null) { throw ROOT_LOGGER.noDriverDefinedInDefaultProfile(); } return Collections.unmodifiableSet(Collections.synchronizedSet(new HashSet<InstalledDriver>(drivers.get(profile).values()))); }
Source:
default Try<T> filter(Predicate<? super T> predicate, Supplier<? extends Throwable> throwableSupplier) { Objects.requireNonNull(predicate, "predicate is null"); Objects.requireNonNull(predicate, "throwableSupplier is null"); return filterTry(predicate::test, throwableSupplier); }

Target:
default Try<T> filter(Predicate<? super T> predicate, Supplier<? extends Throwable> throwableSupplier) { Objects.requireNonNull(predicate, "predicate is null"); Objects.requireNonNull(throwableSupplier, "throwableSupplier is null"); return filterTry(predicate::test, throwableSupplier); }
Source:
protected void execute() { logger.trace("Connecting to {}" + baseURL); clearState(); StringBuilder sb = new StringBuilder("<response>"); String statuses = {"status", "chem", "pumps"}; for(String status : statuses){ String response = HttpUtil.executeUrl("GET", baseURL + "/" + status + ".xml", TIMEOUT); logger.trace(baseURL + "/" + status + ".xml \n {}", response); if(response == null){ logger.error("No response from Autelis controller!"); return; } Matcher m = responsePattern.matcher(response); if (m.find()) { sb.append(m.group(1)); } } sb.append("</response>"); String xmlDoc = sb.toString(); for (AutelisBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Item item = provider.getItem(itemName); String config = provider.getAutelisBindingString(itemName); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = xpath.evaluate("response/" + config.replace('.', '/'), is); State state = toState(item.getClass(), value); State oldState = stateMap.put(itemName, state); if(!state.equals(oldState)){ logger.debug("updating item with state {}", itemName, state); eventPublisher.postUpdate(itemName, state); } } catch (XPathExpressionException e) { logger.error("could not parse xml",e); } } } }

Target:
protected void execute() { logger.trace("Connecting to {}" + baseURL); clearState(); String xmlDoc = fetchStateFromController(); if(xmlDoc == null) return; for (AutelisBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Item item = provider.getItem(itemName); String config = provider.getAutelisBindingConfigString(itemName); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = xpath.evaluate("response/" + config.replace('.', '/'), is); State state = toState(item.getClass(), value); State oldState = stateMap.put(itemName, state); if(!state.equals(oldState)){ logger.debug("updating item with state {}", itemName, state); eventPublisher.postUpdate(itemName, state); } } catch (XPathExpressionException e) { logger.warn("could not parse xml",e); } } } }
Source:
private int searchForIndex(int i) { ensureIndex(i); if (cardinality == 0 || i > indices[cardinality - 1]) { return cardinality; } int left = 0; int right = cardinality; while (left < right) { int p = (left + right) / 2; if (indices[p] > i) { right = p; } else if (indices[p] < i) { left = p + 1; } else { return p; } } return left; }

Target:
private int searchForIndex(int i) { if (cardinality == 0 || i > indices[cardinality - 1]) { return cardinality; } int left = 0; int right = cardinality; while (left < right) { int p = (left + right) / 2; if (indices[p] > i) { right = p; } else if (indices[p] < i) { left = p + 1; } else { return p; } } return left; }
Source:
private ProcessWrapper startP4dInRepo(File tempRepo) throws IOException, CheckedCommandLineException { CommandLine command = createCommandLine("p4d").withArgs("-r", tempRepo.getAbsolutePath(), "-p", String.valueOf(port)); ProcessOutputStreamConsumer outputStreamConsumer = inMemoryConsumer(); return command.execute(outputStreamConsumer, new EnvironmentVariableContext(),null); }

Target:
private ProcessWrapper startP4dInRepo(File tempRepo) throws IOException, CheckedCommandLineException { CommandLine command = createCommandLine("p4d").withArgs("-C0", "-r", tempRepo.getAbsolutePath(), "-p", String.valueOf(port)); ProcessOutputStreamConsumer outputStreamConsumer = inMemoryConsumer(); return command.execute(outputStreamConsumer, new EnvironmentVariableContext(),null); }
Source:
public Application fromDBObject(DBObject dbo) { if (dbo == null) { return null; } Long applicationId = TranslatorUtils.toLong(dbo, DEER_ID_KEY); if (DEER_ID_KEY == null) { return null; } return Application.builder() .withId(Id.valueOf(applicationId)) .withSlug(TranslatorUtils.toString(dbo, SLUG_KEY)) .withTitle(TranslatorUtils.toString(dbo, TITLE_KEY)) .withDescription(TranslatorUtils.toString(dbo, DESCRIPTION_KEY)) .withCreated(TranslatorUtils.toDateTime(dbo, CREATED_KEY)) .withCredentials(credentialsTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CREDENTIALS_KEY))) .withSources(sourcesTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CONFIG_KEY))) .build(); }

Target:
public Application fromDBObject(DBObject dbo) { if (dbo == null) { return null; } return Application.builder() .withId(Id.valueOf(TranslatorUtils.toLong(dbo, APPLICATION_ID_KEY))) .withSlug(TranslatorUtils.toString(dbo, SLUG_KEY)) .withTitle(TranslatorUtils.toString(dbo, TITLE_KEY)) .withDescription(TranslatorUtils.toString(dbo, DESCRIPTION_KEY)) .withCreated(TranslatorUtils.toDateTime(dbo, CREATED_KEY)) .withCredentials(credentialsTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CREDENTIALS_KEY))) .withSources(sourcesTranslator.fromDBObject(TranslatorUtils.toDBObject(dbo, CONFIG_KEY))) .build(); }