instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class ArrayTool
{
/**
* 二分查找
* @param branches 数组
* @param node 要查找的node
* @return 数组下标,小于0表示没找到
*/
public static int binarySearch(BaseNode[] branches, BaseNode node)
{
int high = branches.length - 1;
if (branches.length < 1)
{
return high;
}
int low = 0;
while (low <= high)
{
int mid = (low + high) >>> 1;
int cmp = branches[mid].compareTo(node);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid;
}
return -(low + 1);
}
public static int binarySearch(BaseNode[] branches, char node) | {
int high = branches.length - 1;
if (branches.length < 1)
{
return high;
}
int low = 0;
while (low <= high)
{
int mid = (low + high) >>> 1;
int cmp = branches[mid].compareTo(node);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid;
}
return -(low + 1);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\bintrie\util\ArrayTool.java | 1 |
请完成以下Java代码 | private static CostElementIdAndAcctSchemaId extractCostElementIdAndAcctSchemaId(final I_M_CostElement_Acct record)
{
return CostElementIdAndAcctSchemaId.of(
CostElementId.ofRepoId(record.getM_CostElement_ID()),
AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()));
}
private static CostElementAccounts fromRecord(final I_M_CostElement_Acct record)
{
return CostElementAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.P_CostClearing_Acct(AccountId.ofRepoId(record.getP_CostClearing_Acct()))
.build();
}
@Value(staticConstructor = "of")
private static class CostElementIdAndAcctSchemaId
{
@NonNull CostElementId costTypeId;
@NonNull AcctSchemaId acctSchemaId;
}
private static class CostElementAccountsMap
{
private final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map;
public CostElementAccountsMap( | @NonNull final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map)
{
this.map = map;
}
public CostElementAccounts getAccounts(
@NonNull final CostElementId costElementId,
@NonNull final AcctSchemaId acctSchemaId)
{
final CostElementAccounts accounts = map.get(CostElementIdAndAcctSchemaId.of(costElementId, acctSchemaId));
if (accounts == null)
{
throw new AdempiereException("No accounts found for " + costElementId + " and " + acctSchemaId);
}
return accounts;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\CostElementAccountsRepository.java | 1 |
请完成以下Java代码 | public LookupValuesPage findEntities(final Evaluatee ctx, final String filter, final int firstRow, final int pageLength)
{
return LookupValuesPage.EMPTY;
}
@Override
public LookupValuesPage findEntities(final Evaluatee ctx, final int pageLength)
{
return LookupValuesPage.EMPTY;
}
@Override
public LookupValue findById(final Object id)
{
return toUnknownLookupValue(id);
}
@Nullable
private static LookupValue toUnknownLookupValue(final Object id)
{
if (id == null)
{
return null;
}
if (id instanceof Integer)
{
return IntegerLookupValue.unknown((int)id);
}
else
{
return StringLookupValue.unknown(id.toString());
}
}
@Override
public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids)
{
if (ids.isEmpty())
{
return LookupValuesList.EMPTY;
}
return ids.stream()
.map(NullLookupDataSource::toUnknownLookupValue)
.filter(Objects::nonNull) | .collect(LookupValuesList.collect());
}
@Override
public List<CCacheStats> getCacheStats()
{
return ImmutableList.of();
}
@Override
public void cacheInvalidate()
{
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\NullLookupDataSource.java | 1 |
请完成以下Java代码 | public CmmnTaskService cmmnTaskService() {
return cmmnEngine().getCmmnTaskService();
}
@Produces
@Named
@ApplicationScoped
public CmmnRepositoryService cmmnRepositoryService() {
return cmmnEngine().getCmmnRepositoryService();
}
@Produces
@Named
@ApplicationScoped
public DynamicCmmnService dynamicCmmnService() {
return cmmnEngine().getDynamicCmmnService(); | }
@Produces
@Named
@ApplicationScoped
public CmmnHistoryService cmmnHistoryService() {
return cmmnEngine().getCmmnHistoryService();
}
@Produces
@Named
@ApplicationScoped
public CmmnManagementService cmmnManagementService() {
return cmmnEngine().getCmmnManagementService();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-cdi\src\main\java\org\flowable\cdi\impl\util\FlowableCmmnServices.java | 1 |
请完成以下Java代码 | public TbMsgBuilder partition(Integer partition) {
this.partition = partition;
return this;
}
public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds);
return this;
}
public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) {
this.ctx = ctx;
return this;
}
public TbMsgBuilder callback(TbMsgCallback callback) {
this.callback = callback;
return this;
} | public TbMsg build() {
return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback);
}
public String toString() {
return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts +
", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator +
", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType +
", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId +
", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds +
", ctx=" + this.ctx + ", callback=" + this.callback + ")";
}
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java | 1 |
请完成以下Java代码 | public UUID getOrderId() {
return orderId;
}
public void setOrderId(UUID orderId) {
this.orderId = orderId;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public LocalDate getShipBy() { | return shipBy;
}
public void setShipBy(LocalDate shipBy) {
this.shipBy = shipBy;
}
public ShipmentStatus getStatus() {
return status;
}
public void setStatus(ShipmentStatus status) {
this.status = status;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\conversion\model\entity\Shipment.java | 1 |
请完成以下Java代码 | protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
if (webhookUrl == null) {
return Mono.error(new IllegalStateException("'webhookUrl' must not be null."));
}
return Mono.fromRunnable(
() -> restTemplate.postForEntity(webhookUrl, createDiscordNotification(event, instance), Void.class));
}
protected Object createDiscordNotification(InstanceEvent event, Instance instance) {
Map<String, Object> body = new HashMap<>();
body.put("content", createContent(event, instance));
body.put("tts", tts);
if (avatarUrl != null) {
body.put("avatar_url", avatarUrl);
}
if (username != null) {
body.put("username", username);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add(HttpHeaders.USER_AGENT, "RestTemplate");
return new HttpEntity<>(body, headers);
}
@Override
protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
}
@Nullable
public URI getWebhookUrl() {
return webhookUrl;
}
public void setWebhookUrl(@Nullable URI webhookUrl) {
this.webhookUrl = webhookUrl; | }
public boolean isTts() {
return tts;
}
public void setTts(boolean tts) {
this.tts = tts;
}
@Nullable
public String getUsername() {
return username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
@Nullable
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(@Nullable String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\DiscordNotifier.java | 1 |
请完成以下Java代码 | Mono<String> getBlocking() {
return Mono.fromCallable(() -> {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "foo";
});
}
@GetMapping("/non-blocking")
Mono<String> getNonBlocking() {
return Mono.just("bar")
.delayElement(Duration.ofSeconds(2));
}
@SuppressWarnings("BlockingMethodInNonBlockingContext")
@GetMapping("/warning")
Mono<String> warning() {
Mono<String> data = fetchData();
String response = "retrieved data: " + data.block();
return Mono.just(response);
} | private Mono<String> fetchData() {
return Mono.just("bar");
}
@GetMapping("/blocking-with-scheduler")
Mono<String> getBlockingWithDedicatedScheduler() {
return Mono.fromCallable(this::fetchDataBlocking)
.subscribeOn(Schedulers.boundedElastic())
.map(data -> "retrieved data: " + data);
}
private String fetchDataBlocking() {
try {
Thread.sleep(2_000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return "foo";
}
}
} | repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\threadstarvation\ThreadStarvationApp.java | 1 |
请完成以下Java代码 | public static AttachmentEntityManager getAttachmentEntityManager() {
return getAttachmentEntityManager(getCommandContext());
}
public static AttachmentEntityManager getAttachmentEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getAttachmentEntityManager();
}
public static EventLogEntryEntityManager getEventLogEntryEntityManager() {
return getEventLogEntryEntityManager(getCommandContext());
}
public static EventLogEntryEntityManager getEventLogEntryEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventLogEntryEntityManager();
}
public static FlowableEventDispatcher getEventDispatcher() {
return getEventDispatcher(getCommandContext());
}
public static FlowableEventDispatcher getEventDispatcher(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventDispatcher();
} | public static FailedJobCommandFactory getFailedJobCommandFactory() {
return getFailedJobCommandFactory(getCommandContext());
}
public static FailedJobCommandFactory getFailedJobCommandFactory(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getFailedJobCommandFactory();
}
public static ProcessInstanceHelper getProcessInstanceHelper() {
return getProcessInstanceHelper(getCommandContext());
}
public static ProcessInstanceHelper getProcessInstanceHelper(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getProcessInstanceHelper();
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CommandContextUtil.java | 1 |
请完成以下Java代码 | public java.lang.String getInvoiceWeekDay ()
{
return (java.lang.String)get_Value(COLUMNNAME_InvoiceWeekDay);
}
/**
* InvoiceWeekDayCutoff AD_Reference_ID=167
* Reference name: Weekdays
*/
public static final int INVOICEWEEKDAYCUTOFF_AD_Reference_ID=167;
/** Sunday = 7 */
public static final String INVOICEWEEKDAYCUTOFF_Sunday = "7";
/** Monday = 1 */
public static final String INVOICEWEEKDAYCUTOFF_Monday = "1";
/** Tuesday = 2 */
public static final String INVOICEWEEKDAYCUTOFF_Tuesday = "2";
/** Wednesday = 3 */
public static final String INVOICEWEEKDAYCUTOFF_Wednesday = "3";
/** Thursday = 4 */
public static final String INVOICEWEEKDAYCUTOFF_Thursday = "4";
/** Friday = 5 */
public static final String INVOICEWEEKDAYCUTOFF_Friday = "5";
/** Saturday = 6 */
public static final String INVOICEWEEKDAYCUTOFF_Saturday = "6";
/** Set Letzter Wochentag Lieferungen.
@param InvoiceWeekDayCutoff
Last day in the week for shipments to be included
*/
@Override
public void setInvoiceWeekDayCutoff (java.lang.String InvoiceWeekDayCutoff)
{
set_Value (COLUMNNAME_InvoiceWeekDayCutoff, InvoiceWeekDayCutoff);
}
/** Get Letzter Wochentag Lieferungen.
@return Last day in the week for shipments to be included
*/
@Override
public java.lang.String getInvoiceWeekDayCutoff ()
{
return (java.lang.String)get_Value(COLUMNNAME_InvoiceWeekDayCutoff);
}
/** Set Betragsgrenze.
@param IsAmount
Send invoices only if the amount exceeds the limit
IMPORTANT: currently not used;
*/
@Override
public void setIsAmount (boolean IsAmount)
{
set_Value (COLUMNNAME_IsAmount, Boolean.valueOf(IsAmount));
}
/** Get Betragsgrenze.
@return Send invoices only if the amount exceeds the limit
IMPORTANT: currently not used;
*/
@Override
public boolean isAmount ()
{
Object oo = get_Value(COLUMNNAME_IsAmount); | if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceSchedule.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price; | }
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\Book.java | 1 |
请完成以下Java代码 | public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (this.fileName.equals(fileName)) {
System.out.println("File found: " + file.toString());
return TERMINATE;
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("Failed to access file: " + file.toString());
return CONTINUE; | }
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
boolean finishedSearch = Files.isSameFile(dir, startDir);
if (finishedSearch) {
System.out.println("File:" + fileName + " not found");
return TERMINATE;
}
return CONTINUE;
}
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get("C:/Users/new/Desktop");
FileSearchExample crawler = new FileSearchExample("hibernate.txt", startingDir);
Files.walkFileTree(startingDir, crawler);
}
} | repos\tutorials-master\core-java-modules\core-java-nio-3\src\main\java\com\baeldung\filevisitor\FileSearchExample.java | 1 |
请完成以下Java代码 | protected boolean writePlanItemDefinitionCommonElements(CmmnModel model, T planItemDefinition, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception {
if (StringUtils.isNotEmpty(planItemDefinition.getDocumentation())) {
xtw.writeStartElement(ELEMENT_DOCUMENTATION);
xtw.writeCharacters(planItemDefinition.getDocumentation());
xtw.writeEndElement();
}
boolean didWriteExtensionStartElement = false;
if (options.isSaveElementNameWithNewLineInExtensionElement()) {
didWriteExtensionStartElement = CmmnXmlUtil.writeElementNameExtensionElement(planItemDefinition, didWriteExtensionStartElement, xtw);
}
return CmmnXmlUtil.writeExtensionElements(planItemDefinition, didWriteExtensionStartElement, model.getNamespaces(), xtw);
}
protected boolean writePlanItemDefinitionExtensionElements(CmmnModel model, T planItemDefinition, boolean didWriteExtensionElement, XMLStreamWriter xtw) throws Exception {
return FlowableListenerExport.writeFlowableListeners(xtw, CmmnXmlConstants.ELEMENT_PLAN_ITEM_LIFECYCLE_LISTENER,
planItemDefinition.getLifecycleListeners(), didWriteExtensionElement);
}
protected void writePlanItemDefinitionDefaultItemControl(CmmnModel model, T planItemDefinition, XMLStreamWriter xtw) throws Exception {
if (planItemDefinition.getDefaultControl() != null) {
PlanItemControlExport.writeDefaultControl(model, planItemDefinition.getDefaultControl(), xtw); | }
}
/**
* Subclasses can override this method to write the content body xml content of the plainItemDefinition
*
* @param planItemDefinition the plan item definition to write
* @param xtw the XML to write the definition to
* @throws Exception in case of write exception
*/
protected void writePlanItemDefinitionBody(CmmnModel model, T planItemDefinition, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception {
}
protected void writePlanItemDefinitionEndElement(XMLStreamWriter xtw) throws Exception {
xtw.writeEndElement();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\AbstractPlanItemDefinitionExport.java | 1 |
请完成以下Java代码 | public void setSO_TargetDocTypeReason (final @Nullable java.lang.String SO_TargetDocTypeReason)
{
set_Value (COLUMNNAME_SO_TargetDocTypeReason, SO_TargetDocTypeReason);
}
@Override
public java.lang.String getSO_TargetDocTypeReason()
{
return get_ValueAsString(COLUMNNAME_SO_TargetDocTypeReason);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public void setTitleShort (final @Nullable java.lang.String TitleShort)
{
throw new IllegalArgumentException ("TitleShort is virtual column"); }
@Override
public java.lang.String getTitleShort()
{
return get_ValueAsString(COLUMNNAME_TitleShort);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setURL2 (final @Nullable java.lang.String URL2)
{
set_Value (COLUMNNAME_URL2, URL2);
}
@Override
public java.lang.String getURL2()
{
return get_ValueAsString(COLUMNNAME_URL2);
}
@Override
public void setURL3 (final @Nullable java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3);
}
@Override
public java.lang.String getURL3()
{
return get_ValueAsString(COLUMNNAME_URL3);
}
@Override
public void setValue (final java.lang.String Value) | {
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner.java | 1 |
请完成以下Java代码 | public boolean isFocusable()
{
return findPanel.isFocusable();
}
@Override
public void requestFocus()
{
findPanel.requestFocus();
}
@Override
public boolean requestFocusInWindow()
{
return findPanel.requestFocusInWindow();
}
private final synchronized PropertyChangeSupport getPropertyChangeSupport()
{
if (_pcs == null)
{
_pcs = new PropertyChangeSupport(this);
}
return _pcs;
} | @Override
public void runOnExpandedStateChange(final Runnable runnable)
{
Check.assumeNotNull(runnable, "runnable not null");
getPropertyChangeSupport().addPropertyChangeListener(PROPERTY_Expanded, new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
runnable.run();
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelContainer_EmbeddedPanel.java | 1 |
请完成以下Java代码 | public static String rowToString(JSONArray ja) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ja.length(); i += 1) {
if (i > 0) {
sb.append(',');
}
Object o = ja.opt(i);
if (o != null) {
String s = o.toString();
if (
s.length() > 0 &&
(s.indexOf(',') >= 0 ||
s.indexOf('\n') >= 0 ||
s.indexOf('\r') >= 0 ||
s.indexOf(0) >= 0 ||
s.charAt(0) == '"')
) {
sb.append('"');
int length = s.length();
for (int j = 0; j < length; j += 1) {
char c = s.charAt(j);
if (c >= ' ' && c != '"') {
sb.append(c);
}
}
sb.append('"');
} else {
sb.append(s);
}
}
}
sb.append('\n');
return sb.toString();
}
/**
* Produce a comma delimited text from a JSONArray of JSONObjects. The first row will be a list of names obtained by inspecting the first JSONObject.
*
* @param ja
* A JSONArray of JSONObjects.
* @return A comma delimited text.
* @throws JSONException
*/
public static String toString(JSONArray ja) throws JSONException {
JSONObject jo = ja.optJSONObject(0);
if (jo != null) {
JSONArray names = jo.names();
if (names != null) {
return rowToString(names) + toString(names, ja);
}
}
return null;
} | /**
* Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names. The list of names is not included in the output.
*
* @param names
* A JSONArray of strings.
* @param ja
* A JSONArray of JSONObjects.
* @return A comma delimited text.
* @throws JSONException
*/
public static String toString(JSONArray names, JSONArray ja) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ja.length(); i += 1) {
JSONObject jo = ja.optJSONObject(i);
if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names)));
}
}
return sb.toString();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\json\CDL.java | 1 |
请完成以下Java代码 | public final PricingConditionsView createView(@NonNull final CreateViewRequest request)
{
final PricingConditionsRowData rowsData = createPricingConditionsRowData(request);
return createView(rowsData);
}
protected abstract PricingConditionsRowData createPricingConditionsRowData(CreateViewRequest request);
private PricingConditionsView createView(final PricingConditionsRowData rowsData)
{
return PricingConditionsView.builder()
.viewId(ViewId.random(windowId))
.rowsData(rowsData)
.relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_CopyRowToEditable.class))
.relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_SaveEditableRow.class))
.filterDescriptors(filtersFactory.getFilterDescriptorsProvider())
.build();
}
protected final PricingConditionsRowsLoaderBuilder preparePricingConditionsRowData()
{
return PricingConditionsRowsLoader.builder()
.lookups(lookups);
}
@Override
public PricingConditionsView filterView(
@NonNull final IView view,
@NonNull final JSONFilterViewRequest filterViewRequest,
final Supplier<IViewsRepository> viewsRepo_IGNORED)
{
return PricingConditionsView.cast(view)
.filter(filtersFactory.extractFilters(filterViewRequest));
}
private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass)
{
final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
return RelatedProcessDescriptor.builder()
.processId(adProcessDAO.retrieveProcessIdByClass(processClass)) | .anyTable()
.anyWindow()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
protected final DocumentFilterList extractFilters(final CreateViewRequest request)
{
return filtersFactory.extractFilters(request);
}
@lombok.Value(staticConstructor = "of")
private static final class ViewLayoutKey
{
WindowId windowId;
JSONViewDataType viewDataType;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java | 1 |
请完成以下Java代码 | public void setCorrelationParameter(boolean correlationParameter) {
this.correlationParameter = correlationParameter;
}
public static EventPayload correlation(String name, String type) {
EventPayload payload = new EventPayload(name, type);
payload.setCorrelationParameter(true);
return payload;
}
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public boolean isFullPayload() {
return isFullPayload;
}
public void setFullPayload(boolean isFullPayload) {
this.isFullPayload = isFullPayload;
}
public static EventPayload fullPayload(String name) {
EventPayload payload = new EventPayload();
payload.name = name;
payload.setFullPayload(true);
return payload;
}
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public boolean isMetaParameter() {
return metaParameter; | }
public void setMetaParameter(boolean metaParameter) {
this.metaParameter = metaParameter;
}
@JsonIgnore
public boolean isNotForBody() {
return header || isFullPayload || metaParameter;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EventPayload that = (EventPayload) o;
return Objects.equals(name, that.name) && Objects.equals(type, that.type) && correlationParameter == that.correlationParameter
&& header == that.header && isFullPayload == that.isFullPayload && metaParameter == that.metaParameter;
}
@Override
public int hashCode() {
return Objects.hash(name, type);
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventPayload.java | 1 |
请完成以下Java代码 | public final MovementUserNotificationsProducer notifyProcessed(@NonNull final I_M_Movement movement)
{
notifyProcessed(ImmutableList.of(movement));
return this;
}
private UserNotificationRequest createUserNotification(@NonNull final I_M_Movement movement)
{
final UserId recipientUserId = getNotificationRecipientUserId(movement);
final TableRecordReference movementRef = TableRecordReference.of(movement);
return newUserNotificationRequest()
.recipientUserId(recipientUserId)
.contentADMessage(MSG_Event_MovementGenerated)
.contentADMessageParam(movementRef)
.targetAction(TargetRecordAction.of(movementRef))
.build();
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private UserId getNotificationRecipientUserId(final I_M_Movement movement)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofCode(movement.getDocStatus());
if (docStatus.isReversedOrVoided())
{ | final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user
if (currentUserId > 0)
{
return UserId.ofRepoId(currentUserId);
}
return UserId.ofRepoId(movement.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(movement.getCreatedBy());
}
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\movement\event\MovementUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public static final ComboPopup getComboPopup(final JComboBox<?> comboBox)
{
final ComboBoxUI comboBoxUI = comboBox.getUI();
if (comboBoxUI instanceof AdempiereComboBoxUI)
{
return ((AdempiereComboBoxUI)comboBoxUI).getComboPopup();
}
//
// Fallback:
// Back door our way to finding the inner JList.
//
// it is unknown whether this functionality will work outside of Sun's
// implementation, but the code is safe and will "fail gracefully" on
// other systems
//
// see javax.swing.plaf.basic.BasicComboBoxUI.getAccessibleChild(JComponent, int)
final Accessible a = comboBoxUI.getAccessibleChild(comboBox, 0);
if (a instanceof ComboPopup)
{
return (ComboPopup)a;
}
else
{
return null;
}
}
public static class AdempiereComboPopup extends BasicComboPopup
{
private static final long serialVersionUID = 3226003169560939486L; | public AdempiereComboPopup(final JComboBox<Object> combo)
{
super(combo);
}
@Override
protected int getPopupHeightForRowCount(final int maxRowCount)
{
// ensure the combo box sized for the amount of data to be displayed
final int itemCount = comboBox.getItemCount();
int rows = itemCount < maxRowCount ? itemCount : maxRowCount;
if (rows <= 0)
rows = 1;
return super.getPopupHeightForRowCount(1) * rows;
}
@Override
protected void configureScroller()
{
super.configureScroller();
// In case user scrolls inside a combobox popup, we want to prevent closing the popup no matter if it could be scrolled or not.
scroller.putClientProperty(AdempiereScrollPaneUI.PROPERTY_DisableWheelEventForwardToParent, true);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereComboBoxUI.java | 1 |
请完成以下Java代码 | public LockChangeFailedException setParameter(@NonNull String name, Object value)
{
super.setParameter(name, value);
return this;
}
@Override
public LockChangeFailedException setRecord(final @NonNull TableRecordReference record)
{
super.setRecord(record);
return this;
}
@Override
public LockChangeFailedException setSql(String sql, Object[] sqlParams) | {
super.setSql(sql, sqlParams);
return this;
}
public LockChangeFailedException setLock(final ILock lock)
{
return setParameter("Lock", lock);
}
public LockChangeFailedException setLockCommand(final ILockCommand lockCommand)
{
setParameter("Lock command", lockCommand);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\exceptions\LockChangeFailedException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Asset prepare(EntitiesImportCtx ctx, Asset asset, Asset old, EntityExportData<Asset> exportData, IdProvider idProvider) {
asset.setAssetProfileId(idProvider.getInternalId(asset.getAssetProfileId()));
return asset;
}
@Override
protected Asset saveOrUpdate(EntitiesImportCtx ctx, Asset asset, EntityExportData<Asset> exportData, IdProvider idProvider, CompareResult compareResult) {
Asset savedAsset = assetService.saveAsset(asset);
if (ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds()) {
importCalculatedFields(ctx, savedAsset, exportData, idProvider);
}
return savedAsset;
}
@Override
protected Asset deepCopy(Asset asset) {
return new Asset(asset);
} | @Override
protected void cleanupForComparison(Asset e) {
super.cleanupForComparison(e);
if (e.getCustomerId() != null && e.getCustomerId().isNullUid()) {
e.setCustomerId(null);
}
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\AssetImportService.java | 2 |
请完成以下Java代码 | public final class EntityAlarmEntity implements ToData<EntityAlarm> {
@Column(name = TENANT_ID_COLUMN, columnDefinition = "uuid")
private UUID tenantId;
@Column(name = ENTITY_TYPE_COLUMN)
private String entityType;
@Id
@Column(name = ENTITY_ID_COLUMN, columnDefinition = "uuid")
private UUID entityId;
@Id
@Column(name = "alarm_id", columnDefinition = "uuid")
private UUID alarmId;
@Column(name = CREATED_TIME_PROPERTY)
private long createdTime;
@Column(name = "alarm_type")
private String alarmType;
@Column(name = CUSTOMER_ID_PROPERTY, columnDefinition = "uuid")
private UUID customerId;
public EntityAlarmEntity() {
super();
}
public EntityAlarmEntity(EntityAlarm entityAlarm) {
tenantId = entityAlarm.getTenantId().getId();
entityId = entityAlarm.getEntityId().getId();
entityType = entityAlarm.getEntityId().getEntityType().name();
alarmId = entityAlarm.getAlarmId().getId();
alarmType = entityAlarm.getAlarmType();
createdTime = entityAlarm.getCreatedTime(); | if (entityAlarm.getCustomerId() != null) {
customerId = entityAlarm.getCustomerId().getId();
}
}
@Override
public EntityAlarm toData() {
EntityAlarm result = new EntityAlarm();
result.setTenantId(TenantId.fromUUID(tenantId));
result.setEntityId(EntityIdFactory.getByTypeAndUuid(entityType, entityId));
result.setAlarmId(new AlarmId(alarmId));
result.setAlarmType(alarmType);
result.setCreatedTime(createdTime);
if (customerId != null) {
result.setCustomerId(new CustomerId(customerId));
}
return result;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\EntityAlarmEntity.java | 1 |
请完成以下Spring Boot application配置 | spring.docker.compose.enabled=true
spring.docker.compose.file=./connectiondetails/docker/docker-compose-kafka.yml
spring.docker.compose.skip.in-tests=false
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.mustache.check-template-location=false
spring.profiles.active=kafka
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration, org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration, org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration, org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration, | org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration | repos\tutorials-master\spring-boot-modules\spring-boot-3-2\src\main\resources\connectiondetails\application-kafka.properties | 2 |
请完成以下Java代码 | public class CacheAwareHistoryEventProducer extends DefaultHistoryEventProducer {
protected HistoricActivityInstanceEventEntity loadActivityInstanceEventEntity(ExecutionEntity execution) {
final String activityInstanceId = execution.getActivityInstanceId();
HistoricActivityInstanceEventEntity cachedEntity = findInCache(HistoricActivityInstanceEventEntity.class, activityInstanceId);
if(cachedEntity != null) {
return cachedEntity;
} else {
return newActivityInstanceEventEntity(execution);
}
}
protected HistoricProcessInstanceEventEntity loadProcessInstanceEventEntity(ExecutionEntity execution) {
final String processInstanceId = execution.getProcessInstanceId();
HistoricProcessInstanceEventEntity cachedEntity = findInCache(HistoricProcessInstanceEventEntity.class, processInstanceId);
if(cachedEntity != null) {
return cachedEntity;
} else {
return newProcessInstanceEventEntity(execution);
}
}
protected HistoricTaskInstanceEventEntity loadTaskInstanceEvent(DelegateTask task) {
final String taskId = task.getId();
HistoricTaskInstanceEventEntity cachedEntity = findInCache(HistoricTaskInstanceEventEntity.class, taskId);
if(cachedEntity != null) {
return cachedEntity;
} else {
return newTaskInstanceEventEntity(task);
}
}
protected HistoricIncidentEventEntity loadIncidentEvent(Incident incident) {
String incidentId = incident.getId();
HistoricIncidentEventEntity cachedEntity = findInCache(HistoricIncidentEventEntity.class, incidentId);
if(cachedEntity != null) {
return cachedEntity;
} else {
return newIncidentEventEntity(incident);
} | }
protected HistoricBatchEntity loadBatchEntity(BatchEntity batch) {
String batchId = batch.getId();
HistoricBatchEntity cachedEntity = findInCache(HistoricBatchEntity.class, batchId);
if(cachedEntity != null) {
return cachedEntity;
} else {
return newBatchEventEntity(batch);
}
}
/** find a cached entity by primary key */
protected <T extends HistoryEvent> T findInCache(Class<T> type, String id) {
return Context.getCommandContext()
.getDbEntityManager()
.getCachedEntity(type, id);
}
@Override
protected ProcessDefinitionEntity getProcessDefinitionEntity(String processDefinitionId) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntity entity = null;
if(commandContext != null) {
entity = commandContext
.getDbEntityManager()
.getCachedEntity(ProcessDefinitionEntity.class, processDefinitionId);
}
return (entity != null) ? entity : super.getProcessDefinitionEntity(processDefinitionId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\producer\CacheAwareHistoryEventProducer.java | 1 |
请完成以下Java代码 | public Class<?> getType(ELContext context, Object base, Object property) {
return null;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
// NO-OP
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
return false;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return null; | }
/**
* Converts an object to a specific type.
*
* <p>
* An <code>ELException</code> is thrown if an error occurs during the conversion.
* </p>
*
* @param context The context of this evaluation.
* @param obj The object to convert.
* @param targetType The target type for the conversion.
* @throws ELException thrown if errors occur.
*/
@Override
public abstract <T> T convertToType(ELContext context, Object obj, Class<T> targetType);
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\TypeConverter.java | 1 |
请完成以下Java代码 | public int getC_BP_BankAccount_DirectDebitMandate_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_DirectDebitMandate_ID);
}
@Override
public void setC_BP_BankAccount_ID (final int C_BP_BankAccount_ID)
{
if (C_BP_BankAccount_ID < 1)
set_Value (COLUMNNAME_C_BP_BankAccount_ID, null);
else
set_Value (COLUMNNAME_C_BP_BankAccount_ID, C_BP_BankAccount_ID);
}
@Override
public int getC_BP_BankAccount_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_ID);
}
@Override
public void setDateLastUsed (final @Nullable java.sql.Timestamp DateLastUsed)
{
set_Value (COLUMNNAME_DateLastUsed, DateLastUsed);
}
@Override
public java.sql.Timestamp getDateLastUsed()
{
return get_ValueAsTimestamp(COLUMNNAME_DateLastUsed);
}
@Override
public void setIsRecurring (final boolean IsRecurring)
{
set_Value (COLUMNNAME_IsRecurring, IsRecurring);
}
@Override
public boolean isRecurring()
{
return get_ValueAsBoolean(COLUMNNAME_IsRecurring);
}
@Override
public void setMandateDate (final java.sql.Timestamp MandateDate)
{
set_Value (COLUMNNAME_MandateDate, MandateDate); | }
@Override
public java.sql.Timestamp getMandateDate()
{
return get_ValueAsTimestamp(COLUMNNAME_MandateDate);
}
@Override
public void setMandateReference (final java.lang.String MandateReference)
{
set_Value (COLUMNNAME_MandateReference, MandateReference);
}
@Override
public java.lang.String getMandateReference()
{
return get_ValueAsString(COLUMNNAME_MandateReference);
}
/**
* MandateStatus AD_Reference_ID=541976
* Reference name: Mandat Status
*/
public static final int MANDATESTATUS_AD_Reference_ID=541976;
/** FirstTime = F */
public static final String MANDATESTATUS_FirstTime = "F";
/** Recurring = R */
public static final String MANDATESTATUS_Recurring = "R";
/** LastTime = L */
public static final String MANDATESTATUS_LastTime = "L";
@Override
public void setMandateStatus (final java.lang.String MandateStatus)
{
set_Value (COLUMNNAME_MandateStatus, MandateStatus);
}
@Override
public java.lang.String getMandateStatus()
{
return get_ValueAsString(COLUMNNAME_MandateStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_DirectDebitMandate.java | 1 |
请完成以下Java代码 | public QueryStringBuilder or(String str) {
return this.or(str, true);
}
public QueryStringBuilder or(String str, boolean addQuot) {
builder.append(" OR ");
this.addQuot(str, addQuot);
return this;
}
public QueryStringBuilder not(String str) {
return this.not(str, true);
}
public QueryStringBuilder not(String str, boolean addQuot) {
builder.append(" NOT ");
this.addQuot(str, addQuot);
return this;
}
/**
* 添加双引号(模糊查询,不能加双引号)
*/
private QueryStringBuilder addQuot(String str, boolean addQuot) {
return this.addQuotEffect(this.builder, str, addQuot);
}
/** | * 是否在两边加上双引号
* @param builder
* @param str
* @param addQuot
* @return
*/
private QueryStringBuilder addQuotEffect(StringBuilder builder, String str, boolean addQuot) {
if (addQuot) {
builder.append('"');
}
builder.append(str);
if (addQuot) {
builder.append('"');
}
return this;
}
@Override
public String toString() {
return builder.append(")").toString();
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\es\QueryStringBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void updateOperator(PmsOperator pmsOperator, String OperatorRoleStr) {
pmsOperatorDao.update(pmsOperator);
// 更新角色信息
saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
}
/**
* 保存用户和角色之间的关联关系
*/
private void saveOrUpdateOperatorRole(Long operatorId, String roleIdsStr) {
// 删除原来的角色与操作员关联
List<PmsOperatorRole> listPmsOperatorRoles = pmsOperatorRoleDao.listByOperatorId(operatorId);
Map<Long, PmsOperatorRole> delMap = new HashMap<Long, PmsOperatorRole>();
for (PmsOperatorRole pmsOperatorRole : listPmsOperatorRoles) {
delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
}
if (StringUtils.isNotBlank(roleIdsStr)) {
// 创建新的关联
String[] roleIds = roleIdsStr.split(",");
for (int i = 0; i < roleIds.length; i++) {
Long roleId = Long.valueOf(roleIds[i]);
if (delMap.get(roleId) == null) {
PmsOperatorRole pmsOperatorRole = new PmsOperatorRole();
pmsOperatorRole.setOperatorId(operatorId);
pmsOperatorRole.setRoleId(roleId); | pmsOperatorRoleDao.insert(pmsOperatorRole);
} else {
delMap.remove(roleId);
}
}
}
Iterator<Long> iterator = delMap.keySet().iterator();
while (iterator.hasNext()) {
Long roleId = iterator.next();
pmsOperatorRoleDao.deleteByRoleIdAndOperatorId(roleId, operatorId);
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorRoleServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isOwnerSet() {
return ownerSet;
}
public boolean isAssigneeSet() {
return assigneeSet;
}
public boolean isDelegationStateSet() {
return delegationStateSet;
}
public boolean isNameSet() {
return nameSet;
}
public boolean isDescriptionSet() {
return descriptionSet;
}
public boolean isDuedateSet() {
return duedateSet;
} | public boolean isPrioritySet() {
return prioritySet;
}
public boolean isParentTaskIdSet() {
return parentTaskIdSet;
}
public boolean isCategorySet() {
return categorySet;
}
public boolean isTenantIdSet() {
return tenantIdSet;
}
public boolean isFormKeySet() {
return formKeySet;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java | 2 |
请完成以下Java代码 | public B name(String name) {
this.name = name;
return getThis();
}
public B eventFunction(BiFunction<T, Map<String, Object>, ApplicationEvent> eventFunction) {
this.eventFunction = eventFunction;
return getThis();
}
public B normalizedProperties(Map<String, Object> normalizedProperties) {
this.normalizedProperties = normalizedProperties;
return getThis();
}
public B properties(Map<String, String> properties) {
this.properties = properties;
return getThis();
}
protected abstract void validate();
protected Map<String, Object> normalizeProperties() {
Map<String, Object> normalizedProperties = new HashMap<>();
this.properties.forEach(normalizedProperties::put);
return normalizedProperties;
}
protected abstract T doBind();
public T bind() {
validate();
Assert.hasText(this.name, "name may not be empty");
Assert.isTrue(this.properties != null || this.normalizedProperties != null,
"properties and normalizedProperties both may not be null"); | if (this.normalizedProperties == null) {
this.normalizedProperties = normalizeProperties();
}
T bound = doBind();
if (this.eventFunction != null && this.service.publisher != null) {
ApplicationEvent applicationEvent = this.eventFunction.apply(bound, this.normalizedProperties);
this.service.publisher.publishEvent(applicationEvent);
}
return bound;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ConfigurationService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WelcomeLogoApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
private static AtomicBoolean processed = new AtomicBoolean(false);
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
// Skip if processed before, prevent duplicated execution in Hierarchical ApplicationContext
if (processed.get()) {
return;
}
/**
* Gets Logger After LoggingSystem configuration ready
* @see LoggingApplicationListener
*/
final Logger logger = LoggerFactory.getLogger(getClass());
String bannerText = buildBannerText();
if (logger.isInfoEnabled()) {
logger.info(bannerText);
} else {
System.out.print(bannerText);
}
// mark processed to be true | processed.compareAndSet(false, true);
}
String buildBannerText() {
StringBuilder bannerTextBuilder = new StringBuilder();
bannerTextBuilder
.append(LINE_SEPARATOR)
.append(LINE_SEPARATOR)
.append(" :: Dubbo Spring Boot (v").append(Version.getVersion(getClass(), Version.getVersion())).append(") : ")
.append(DUBBO_SPRING_BOOT_GITHUB_URL)
.append(LINE_SEPARATOR)
.append(" :: Dubbo (v").append(Version.getVersion()).append(") : ")
.append(DUBBO_GITHUB_URL)
.append(LINE_SEPARATOR)
.append(" :: Discuss group : ")
.append(DUBBO_MAILING_LIST)
.append(LINE_SEPARATOR)
;
return bannerTextBuilder.toString();
}
} | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\context\event\WelcomeLogoApplicationListener.java | 2 |
请完成以下Java代码 | private IScriptsRegistry getScriptsRegistry()
{
return targetDatabase.getScriptsRegistry();
}
private IScriptExecutor getExecutor(final IScript script)
{
try
{
return scriptExecutorFactory.createScriptExecutor(targetDatabase, script);
}
catch (final ScriptException se)
{
throw se.addParameter("script.fileName", script.getLocalFile());
}
catch (final RuntimeException rte)
{
logger.error("Caught " + rte.getClass().getSimpleName() + " while getting executor for script " + script.getLocalFile() + "; -> logging here and rethrowing", rte);
throw rte;
}
}
private IScriptExecutor getSqlExecutor()
{
return scriptExecutorFactory.createScriptExecutor(targetDatabase);
} | @Override
public int getCountAll()
{
return countAll;
}
@Override
public int getCountApplied()
{
return countApplied;
}
@Override
public int getCountIgnored()
{
return countIgnored;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\applier\impl\ScriptsApplier.java | 1 |
请完成以下Java代码 | public String toString()
{
return stringExpression.toString();
}
@Override
public Class<V> getValueClass()
{
return valueClass;
}
@Override
public boolean isNoResult(final Object result)
{
return result == null || result == noResultValue;
}
@Override
public boolean isNullExpression()
{
return false;
}
@Override
public String getExpressionString()
{
return stringExpression.getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return stringExpression.getFormatedExpressionString();
}
@Override
public Set<String> getParameterNames()
{
return stringExpression.getParameterNames();
}
@Override
public Set<CtxName> getParameters()
{
return stringExpression.getParameters();
}
@Override
public V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException | {
final String sql = stringExpression.evaluate(ctx, onVariableNotFound);
if (Check.isEmpty(sql, true))
{
logger.warn("Expression " + stringExpression + " was evaluated to empty string. Returning no result: {}", noResultValue);
return noResultValue;
}
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
rs = pstmt.executeQuery();
if (rs.next())
{
final V value = valueRetriever.get(rs);
return value;
}
else
{
if (onVariableNotFound == OnVariableNotFound.Fail)
{
throw ExpressionEvaluationException.newWithPlainMessage("Got no result for " + this)
.setParameter("SQL", sql)
.appendParametersToMessage();
}
logger.warn("Got no result for {} (SQL: {})", this, sql);
return noResultValue;
}
}
catch (final SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlDefaultValueExpression.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MemberProductCollectionController {
@Autowired
private MemberCollectionService memberCollectionService;
@ApiOperation("添加商品收藏")
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public CommonResult add(@RequestBody MemberProductCollection productCollection) {
int count = memberCollectionService.add(productCollection);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("删除商品收藏")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(Long productId) {
int count = memberCollectionService.delete(productId);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("显示当前用户商品收藏列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<MemberProductCollection>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
Page<MemberProductCollection> page = memberCollectionService.list(pageNum,pageSize);
return CommonResult.success(CommonPage.restPage(page)); | }
@ApiOperation("显示商品收藏详情")
@RequestMapping(value = "/detail", method = RequestMethod.GET)
@ResponseBody
public CommonResult<MemberProductCollection> detail(@RequestParam Long productId) {
MemberProductCollection memberProductCollection = memberCollectionService.detail(productId);
return CommonResult.success(memberProductCollection);
}
@ApiOperation("清空当前用户商品收藏列表")
@RequestMapping(value = "/clear", method = RequestMethod.POST)
@ResponseBody
public CommonResult clear() {
memberCollectionService.clear();
return CommonResult.success(null);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\MemberProductCollectionController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CellStyle getStyles(boolean parity, ExcelExportEntity entity) {
return styles;
}
@Override
public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) {
return getStyles(true, entity);
}
@Override
public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) {
return null;
}
/**
* init --HeaderStyle
*
* @param workbook
* @return
*/
private CellStyle initHeaderStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true));
return style;
}
/**
* init-TitleStyle
*
* @param workbook
* @return
*/
private CellStyle initTitleStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false));
// ForegroundColor
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return style;
} | /**
* BaseCellStyle
*
* @return
*/
private CellStyle getBaseCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setWrapText(true);
return style;
}
/**
* Font
*
* @param size
* @param isBold
* @return
*/
private Font getFont(Workbook workbook, short size, boolean isBold) {
Font font = workbook.createFont();
font.setFontName("宋体");
font.setBold(isBold);
font.setFontHeightInPoints(size);
return font;
}
} | repos\springboot-demo-master\eaypoi\src\main\java\com\et\easypoi\service\ExcelExportStyler.java | 2 |
请完成以下Java代码 | public UserAuthToken getOrCreateNew(@NonNull final CreateUserAuthTokenRequest request)
{
return getExisting(request).orElseGet(() -> createNew(request));
}
private Optional<UserAuthToken> getExisting(@NonNull final CreateUserAuthTokenRequest request)
{
return queryBL
.createQueryBuilder(I_AD_User_AuthToken.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_User_ID, request.getUserId())
.addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_Client_ID, request.getClientId())
.addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_Org_ID, request.getOrgId())
.addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_Role_ID, request.getRoleId())
.orderByDescending(I_AD_User_AuthToken.COLUMNNAME_AD_User_AuthToken_ID)
.create()
.firstOptional(I_AD_User_AuthToken.class)
.map(UserAuthTokenRepository::fromRecord);
}
public UserAuthToken createNew(@NonNull final CreateUserAuthTokenRequest request)
{
final I_AD_User_AuthToken record = newInstanceOutOfTrx(I_AD_User_AuthToken.class);
record.setAD_User_ID(request.getUserId().getRepoId());
InterfaceWrapperHelper.setValue(record, I_AD_User_AuthToken.COLUMNNAME_AD_Client_ID, request.getClientId().getRepoId());
record.setAD_Org_ID(request.getOrgId().getRepoId());
record.setAD_Role_ID(request.getRoleId().getRepoId());
record.setDescription(request.getDescription());
record.setAuthToken(generateAuthTokenString());
InterfaceWrapperHelper.saveRecord(record);
return fromRecord(record);
}
public void deleteUserAuthTokenByUserId(@NonNull final UserId userId) | {
queryBL.createQueryBuilder(I_AD_User_AuthToken.class)
.addEqualsFilter(I_AD_User_AuthToken.COLUMN_AD_User_ID, userId)
.create()
.delete();
}
@NonNull
public UserAuthToken getById(@NonNull final UserAuthTokenId id)
{
final I_AD_User_AuthToken record = queryBL.createQueryBuilder(I_AD_User_AuthToken.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User_AuthToken.COLUMNNAME_AD_User_AuthToken_ID, id)
.create()
.firstOnlyNotNull(I_AD_User_AuthToken.class);
return fromRecord(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserAuthTokenRepository.java | 1 |
请完成以下Java代码 | public class ChildTask extends Task implements HasInParameters, HasOutParameters {
protected String businessKey;
protected boolean inheritBusinessKey;
protected List<IOParameter> inParameters = new ArrayList<>();
protected List<IOParameter> outParameters = new ArrayList<>();
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public boolean isInheritBusinessKey() {
return inheritBusinessKey;
}
public void setInheritBusinessKey(boolean inheritBusinessKey) {
this.inheritBusinessKey = inheritBusinessKey;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
inParameters.add(inParameter);
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
} | @Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void addOutParameter(IOParameter outParameter) {
outParameters.add(outParameter);
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ChildTask.java | 1 |
请完成以下Java代码 | public HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getSession(HistoricTaskInstanceEntityManager.class);
}
public HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getSession(HistoricIdentityLinkEntityManager.class);
}
public EventLogEntryEntityManager getEventLogEntryEntityManager() {
return getSession(EventLogEntryEntityManager.class);
}
public JobEntityManager getJobEntityManager() {
return getSession(JobEntityManager.class);
}
public TimerJobEntityManager getTimerJobEntityManager() {
return getSession(TimerJobEntityManager.class);
}
public SuspendedJobEntityManager getSuspendedJobEntityManager() {
return getSession(SuspendedJobEntityManager.class);
}
public DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getSession(DeadLetterJobEntityManager.class);
}
public AttachmentEntityManager getAttachmentEntityManager() {
return getSession(AttachmentEntityManager.class);
}
public TableDataManager getTableDataManager() {
return getSession(TableDataManager.class);
}
public CommentEntityManager getCommentEntityManager() {
return getSession(CommentEntityManager.class);
}
public PropertyEntityManager getPropertyEntityManager() {
return getSession(PropertyEntityManager.class);
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getSession(EventSubscriptionEntityManager.class);
} | public Map<Class<?>, SessionFactory> getSessionFactories() {
return sessionFactories;
}
public HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
// getters and setters //////////////////////////////////////////////////////
public TransactionContext getTransactionContext() {
return transactionContext;
}
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public FlowableEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java | 1 |
请完成以下Java代码 | public void setOptOutDate (java.sql.Timestamp OptOutDate)
{
set_Value (COLUMNNAME_OptOutDate, OptOutDate);
}
/** Get Datum der Abmeldung.
@return Date the contact opted out
*/
@Override
public java.sql.Timestamp getOptOutDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_OptOutDate);
}
/** Set Anmeldung.
@param SubscribeDate
Date the contact actively subscribed
*/ | @Override
public void setSubscribeDate (java.sql.Timestamp SubscribeDate)
{
set_Value (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Anmeldung.
@return Date the contact actively subscribed
*/
@Override
public java.sql.Timestamp getSubscribeDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_TopicSubscriber.java | 1 |
请完成以下Java代码 | public class LoggingSession implements Session {
protected CommandContext commandContext;
protected LoggingSessionCommandContextCloseListener commandContextCloseListener;
protected LoggingListener loggingListener;
protected ObjectMapper objectMapper;
protected List<ObjectNode> loggingData;
public LoggingSession(CommandContext commandContext, LoggingListener loggingListener, ObjectMapper objectMapper) {
this.commandContext = commandContext;
this.loggingListener = loggingListener;
this.objectMapper = objectMapper;
initCommandContextCloseListener();
}
protected void initCommandContextCloseListener() {
this.commandContextCloseListener = new LoggingSessionCommandContextCloseListener(this, loggingListener, objectMapper);
}
public void addLoggingData(String type, ObjectNode data, String engineType) {
if (loggingData == null) {
loggingData = new ArrayList<>();
commandContextCloseListener.setEngineType(engineType);
commandContext.addCloseListener(commandContextCloseListener);
}
String transactionId = null;
if (loggingData.size() > 0) {
transactionId = loggingData.get(0).get(LoggingSessionUtil.TRANSACTION_ID).asString();
} else {
transactionId = data.get(LoggingSessionUtil.ID).asString();
} | data.put(LoggingSessionUtil.TRANSACTION_ID, transactionId);
data.put(LoggingSessionUtil.LOG_NUMBER, loggingData.size() + 1);
loggingData.add(data);
}
@Override
public void flush() {
}
@Override
public void close() {
}
public List<ObjectNode> getLoggingData() {
return loggingData;
}
public void setLoggingData(List<ObjectNode> loggingData) {
this.loggingData = loggingData;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSession.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
IniRealm realm = new IniRealm();
Ini ini = Ini.fromResourcePath(Main.class.getResource("/com/baeldung/shiro/permissions/custom/shiro.ini").getPath());
realm.setIni(ini);
realm.setPermissionResolver(new PathPermissionResolver());
realm.init();
SecurityManager securityManager = new DefaultSecurityManager(realm);
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("paul.reader", "password4");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.error("Username Not Found!", uae);
} catch (IncorrectCredentialsException ice) {
log.error("Invalid Credentials!", ice);
} catch (LockedAccountException lae) {
log.error("Your Account is Locked!", lae);
} catch (AuthenticationException ae) {
log.error("Unexpected Error!", ae);
}
}
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); | if (currentUser.hasRole("admin")) {
log.info("Welcome Admin");
} else if(currentUser.hasRole("editor")) {
log.info("Welcome, Editor!");
} else if(currentUser.hasRole("author")) {
log.info("Welcome, Author");
} else {
log.info("Welcome, Guest");
}
if(currentUser.isPermitted("/articles/drafts/new-article")) {
log.info("You can access articles");
} else {
log.info("You cannot access articles!");
}
currentUser.logout();
}
} | repos\tutorials-master\security-modules\apache-shiro\src\main\java\com\baeldung\permissions\custom\Main.java | 1 |
请完成以下Java代码 | public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo)
{
throw new IllegalArgumentException ("Shipment_DocumentNo is virtual column"); }
@Override
public java.lang.String getShipment_DocumentNo()
{
return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo);
}
@Override
public void setSumDeliveredInStockingUOM (final BigDecimal SumDeliveredInStockingUOM)
{
set_Value (COLUMNNAME_SumDeliveredInStockingUOM, SumDeliveredInStockingUOM);
}
@Override
public BigDecimal getSumDeliveredInStockingUOM()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumDeliveredInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSumOrderedInStockingUOM (final BigDecimal SumOrderedInStockingUOM)
{
set_Value (COLUMNNAME_SumOrderedInStockingUOM, SumOrderedInStockingUOM);
}
@Override
public BigDecimal getSumOrderedInStockingUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SumOrderedInStockingUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_Value (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv.java | 1 |
请完成以下Java代码 | public class PatientAddressType {
@XmlElement(required = true)
protected PersonType person;
@XmlAttribute(name = "gender", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String gender;
@XmlAttribute(name = "birthdate", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar birthdate;
@XmlAttribute(name = "ssn")
protected String ssn;
/**
* Gets the value of the person property.
*
* @return
* possible object is
* {@link PersonType }
*
*/
public PersonType getPerson() {
return person;
}
/**
* Sets the value of the person property.
*
* @param value
* allowed object is
* {@link PersonType }
*
*/
public void setPerson(PersonType value) {
this.person = value;
}
/**
* Gets the value of the gender property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGender() {
return gender;
}
/**
* Sets the value of the gender property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGender(String value) {
this.gender = value;
} | /**
* Gets the value of the birthdate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getBirthdate() {
return birthdate;
}
/**
* Sets the value of the birthdate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setBirthdate(XMLGregorianCalendar value) {
this.birthdate = value;
}
/**
* Gets the value of the ssn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSsn() {
return ssn;
}
/**
* Sets the value of the ssn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSsn(String value) {
this.ssn = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\PatientAddressType.java | 1 |
请完成以下Java代码 | public ResourceOptionsDto availableOperations(UriInfo context) {
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(AuthorizationRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if(isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
public List<AuthorizationDto> queryAuthorizations(AuthorizationQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(getObjectMapper());
AuthorizationQuery query = queryDto.toQuery(getProcessEngine());
List<Authorization> resultList = QueryUtil.list(query, firstResult, maxResults);
return AuthorizationDto.fromAuthorizationList(resultList, getProcessEngine().getProcessEngineConfiguration());
}
@Override
public CountResultDto getAuthorizationCount(UriInfo uriInfo) {
AuthorizationQueryDto queryDto = new AuthorizationQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return getAuthorizationCount(queryDto);
}
protected CountResultDto getAuthorizationCount(AuthorizationQueryDto queryDto) {
AuthorizationQuery query = queryDto.toQuery(getProcessEngine());
long count = query.count();
return new CountResultDto(count); | }
@Override
public AuthorizationDto createAuthorization(UriInfo context, AuthorizationCreateDto dto) {
final AuthorizationService authorizationService = getProcessEngine().getAuthorizationService();
Authorization newAuthorization = authorizationService.createNewAuthorization(dto.getType());
AuthorizationCreateDto.update(dto, newAuthorization, getProcessEngine().getProcessEngineConfiguration());
newAuthorization = authorizationService.saveAuthorization(newAuthorization);
return getAuthorization(newAuthorization.getId()).getAuthorization(context);
}
// utility methods //////////////////////////////////////
protected IdentityService getIdentityService() {
return getProcessEngine().getIdentityService();
}
protected List<String> getUserGroups(String userId) {
List<Group> userGroups = getIdentityService().createGroupQuery()
.groupMember(userId)
.unlimitedList();
List<String> groupIds = new ArrayList<>();
for (Group group : userGroups) {
groupIds.add(group.getId());
}
return groupIds;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\AuthorizationRestServiceImpl.java | 1 |
请完成以下Java代码 | private AttributeId getAttributeId()
{
return attributeId;
}
/**
* @return attribute; never return <code>null</code>
*/
private I_M_Attribute getM_Attribute()
{
return attribute;
}
public HUAttributeQueryFilterVO assertAttributeValueType(@NonNull final String attributeValueType)
{
Check.assume(
Objects.equals(this.attributeValueType, attributeValueType),
"Invalid attributeValueType for {}. Expected: {}",
this, attributeValueType);
return this;
}
private ModelColumn<I_M_HU_Attribute, Object> getHUAttributeValueColumn()
{
return huAttributeValueColumn;
}
private Set<Object> getValues()
{
return _values;
}
private Set<Object> getValuesAndSubstitutes()
{
if (_valuesAndSubstitutes != null)
{
return _valuesAndSubstitutes;
}
final ModelColumn<I_M_HU_Attribute, Object> valueColumn = getHUAttributeValueColumn(); | final boolean isStringValueColumn = I_M_HU_Attribute.COLUMNNAME_Value.equals(valueColumn.getColumnName());
final Set<Object> valuesAndSubstitutes = new HashSet<>();
//
// Iterate current values
for (final Object value : getValues())
{
// Append current value to result
valuesAndSubstitutes.add(value);
// Search and append it's substitutes too, if found
if (isStringValueColumn && value instanceof String)
{
final String valueStr = value.toString();
final I_M_Attribute attribute = getM_Attribute();
final Set<String> valueSubstitutes = attributeDAO.retrieveAttributeValueSubstitutes(attribute, valueStr);
valuesAndSubstitutes.addAll(valueSubstitutes);
}
}
_valuesAndSubstitutes = valuesAndSubstitutes;
return _valuesAndSubstitutes;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAttributeQueryFilterVO.java | 1 |
请完成以下Java代码 | public class LieferavisAbfrageNeu {
@XmlElement(namespace = "", required = true)
protected String clientSoftwareKennung;
/**
* Gets the value of the clientSoftwareKennung property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClientSoftwareKennung() {
return clientSoftwareKennung; | }
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfrageNeu.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public FilterRegistrationBean<BaseUrlFilter> getBaseUrlFilter() {
Set<String> filterUri = new HashSet<>();
BaseUrlFilter filter = new BaseUrlFilter();
FilterRegistrationBean<BaseUrlFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setUrlPatterns(filterUri);
registrationBean.setOrder(20);
return registrationBean;
}
@Bean
public FilterRegistrationBean<UrlCheckFilter> getUrlCheckFilter() {
UrlCheckFilter filter = new UrlCheckFilter();
FilterRegistrationBean<UrlCheckFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setOrder(30);
return registrationBean;
} | @Bean
public FilterRegistrationBean<AttributeSetFilter> getWatermarkConfigFilter() {
Set<String> filterUri = new HashSet<>();
filterUri.add("/index");
filterUri.add("/");
filterUri.add("/onlinePreview");
filterUri.add("/picturesPreview");
AttributeSetFilter filter = new AttributeSetFilter();
FilterRegistrationBean<AttributeSetFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(filter);
registrationBean.setUrlPatterns(filterUri);
return registrationBean;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\config\WebConfig.java | 2 |
请完成以下Java代码 | private DeferredProcessor deferredProcessor()
{
return trxManager.getThreadInheritedTrx(OnTrxMissingPolicy.Fail) // at this point we always run in trx
.getPropertyAndProcessAfterCommit(
DeferredProcessor.class.getName(),
() -> new DeferredProcessor(huTraceEventsService),
DeferredProcessor::processNow);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void addTraceEventForDelete(@NonNull final I_M_ShipmentSchedule_QtyPicked shipmentScheduleQtyPicked)
{
huTraceEventsService.createAndAddFor(shipmentScheduleQtyPicked);
}
private static class DeferredProcessor
{
private final HUTraceEventsService huTraceEventsService;
private final AtomicBoolean processed = new AtomicBoolean(false);
private final LinkedHashMap<Integer, I_M_ShipmentSchedule_QtyPicked> records = new LinkedHashMap<>();
public DeferredProcessor(@NonNull final HUTraceEventsService huTraceEventsService)
{
this.huTraceEventsService = huTraceEventsService;
}
public void schedule(@NonNull final I_M_ShipmentSchedule_QtyPicked record)
{
if (processed.get())
{
throw new AdempiereException("already processed: " + this);
} | this.records.put(record.getM_ShipmentSchedule_QtyPicked_ID(), record);
}
public void processNow()
{
final boolean alreadyProcessed = processed.getAndSet(true);
if (alreadyProcessed)
{
throw new AdempiereException("already processed: " + this);
}
records.values().forEach(huTraceEventsService::createAndAddFor);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\interceptor\M_ShipmentSchedule_QtyPicked.java | 1 |
请完成以下Java代码 | public BigDecimal getBusinessCaseDetailQty()
{
if (businessCaseDetail == null)
{
return BigDecimal.ZERO;
}
return businessCaseDetail.getQty();
}
@Nullable
public OrderAndLineId getSalesOrderLineId()
{
final DemandDetail demandDetail = getDemandDetail();
if (demandDetail == null)
{
return null;
}
return OrderAndLineId.ofRepoIdsOrNull(demandDetail.getOrderId(), demandDetail.getOrderLineId());
}
@NonNull
public BusinessCaseDetail getBusinessCaseDetailNotNull()
{
return Check.assumeNotNull(getBusinessCaseDetail(), "businessCaseDetail is not null: {}", this);
}
public <T extends BusinessCaseDetail> Optional<T> getBusinessCaseDetail(@NonNull final Class<T> type)
{
return type.isInstance(businessCaseDetail) ? Optional.of(type.cast(businessCaseDetail)) : Optional.empty();
}
public <T extends BusinessCaseDetail> T getBusinessCaseDetailNotNull(@NonNull final Class<T> type)
{
if (type.isInstance(businessCaseDetail))
{
return type.cast(businessCaseDetail);
}
else
{
throw new AdempiereException("businessCaseDetail is not matching " + type.getSimpleName() + ": " + this);
}
}
public <T extends BusinessCaseDetail> Candidate withBusinessCaseDetail(@NonNull final Class<T> type, @NonNull final UnaryOperator<T> mapper)
{
final T businessCaseDetail = getBusinessCaseDetailNotNull(type);
final T businessCaseDetailChanged = mapper.apply(businessCaseDetail);
if (Objects.equals(businessCaseDetail, businessCaseDetailChanged))
{
return this;
} | return withBusinessCaseDetail(businessCaseDetailChanged);
}
@Nullable
public String getTraceId()
{
final DemandDetail demandDetail = getDemandDetail();
return demandDetail != null ? demandDetail.getTraceId() : null;
}
/**
* This is enabled by the current usage of {@link #parentId}
*/
public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate)
{
if (potentialStockCandidate.type != CandidateType.STOCK)
{
return false;
}
switch (type)
{
case DEMAND:
return potentialStockCandidate.getParentId().equals(id);
case SUPPLY:
return potentialStockCandidate.getId().equals(parentId);
default:
return false;
}
}
/**
* The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock.
*/
public BigDecimal getStockImpactPlannedQuantity()
{
switch (getType())
{
case DEMAND:
case UNEXPECTED_DECREASE:
case INVENTORY_DOWN:
return getQuantity().negate();
default:
return getQuantity();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java | 1 |
请完成以下Java代码 | public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class);
}
public List<I_M_PickingSlot> getByIds(@NonNull final Set<PickingSlotId> pickingSlotIds)
{
return pickingSlotDAO.getByIds(pickingSlotIds, I_M_PickingSlot.class);
}
public List<I_M_PickingSlot> list(@NonNull final PickingSlotQuery query)
{
return pickingSlotDAO.retrievePickingSlots(query);
} | public void save(final @NonNull I_M_PickingSlot pickingSlot)
{
pickingSlotDAO.save(pickingSlot);
}
public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.getPickingSlotIdAndCaption(pickingSlotId);
}
public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final Set<PickingSlotId> pickingSlotIds)
{
return pickingSlotDAO.getPickingSlotIdAndCaptions(pickingSlotIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotRepository.java | 1 |
请完成以下Java代码 | protected void deleteExceptionByteArrayByParameterMap(String key, Object value) {
EnsureUtil.ensureNotNull(key, value);
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put(key, value);
getDbEntityManager().delete(ByteArrayEntity.class, "deleteExceptionByteArraysByIds", parameterMap);
}
// fire history events ///////////////////////////////////////////////////////
public void fireJobCreatedEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_CREATE, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogCreateEvt(job);
}
});
}
}
public void fireJobFailedEvent(final Job job, final Throwable exception) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_FAIL, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogFailedEvt(job, exception);
}
@Override
public void postHandleSingleHistoryEventCreated(HistoryEvent event) {
((JobEntity) job).setLastFailureLogId(event.getId());
}
});
}
}
public void fireJobSuccessfulEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_SUCCESS, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { | return producer.createHistoricJobLogSuccessfulEvt(job);
}
});
}
}
public void fireJobDeletedEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_DELETE, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogDeleteEvt(job);
}
});
}
}
// helper /////////////////////////////////////////////////////////
protected boolean isHistoryEventProduced(HistoryEventType eventType, Job job) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
return historyLevel.isHistoryEventProduced(eventType, job);
}
protected void configureQuery(HistoricJobLogQueryImpl query) {
getAuthorizationManager().configureHistoricJobLogQuery(query);
getTenantManager().configureQuery(query);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricJobLogManager.java | 1 |
请完成以下Java代码 | public class AddRequestHeaderGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
@Override
public GatewayFilter apply(NameValueConfig config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String name = Objects.requireNonNull(config.getName(), "name must not be null");
String rawValue = Objects.requireNonNull(config.getValue(), "value must not be null");
String value = ServerWebExchangeUtils.expand(exchange, rawValue);
ServerHttpRequest request = exchange.getRequest()
.mutate()
.headers(httpHeaders -> httpHeaders.add(name, value))
.build(); | return chain.filter(exchange.mutate().request(request).build());
}
@Override
public String toString() {
String name = config.getName();
String value = config.getValue();
return filterToStringCreator(AddRequestHeaderGatewayFilterFactory.this)
.append(name != null ? name : "", value != null ? value : "")
.toString();
}
};
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\AddRequestHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public void run()
{
initReceivedDeliveredTab(m_tableReceived, true);
enableDisableButtons(m_tableReceived);
}
};
enableDisableButtons(m_tableReceived);
}
else if (tabIndex == ihTabHandler.getTabIndexEffective(TAB_RESERVED))
{
setButtonVisibility(bZoomPrimary, true);
setButtonVisibility(bZoomSecondary, false);
tabHandlerIndex = TAB_RESERVED;
initializeTabRunnable = new Runnable()
{
@Override
public void run()
{
initReservedOrderedTab(m_tableReserved, true);
enableDisableButtons(m_tableReserved);
}
};
enableDisableButtons(m_tableReserved);
}
else if (tabIndex == ihTabHandler.getTabIndexEffective(TAB_DELIVERED))
{
setButtonVisibility(bZoomPrimary, true);
setButtonVisibility(bZoomSecondary, true);
tabHandlerIndex = TAB_DELIVERED;
initializeTabRunnable = new Runnable()
{
@Override
public void run()
{
initReceivedDeliveredTab(m_tableDelivered, false);
enableDisableButtons(m_tableDelivered);
}
};
enableDisableButtons(m_tableDelivered);
}
else if (tabIndex == ihTabHandler.getTabIndexEffective(TAB_UNCONFIRMED))
{
setButtonVisibility(bZoomPrimary, false);
setButtonVisibility(bZoomSecondary, false);
tabHandlerIndex = TAB_UNCONFIRMED;
initializeTabRunnable = new Runnable()
{
@Override
public void run()
{
initUnconfirmedTab(m_tableUnconfirmed);
enableDisableButtons(m_tableUnconfirmed);
}
};
enableDisableButtons(m_tableUnconfirmed);
}
else if (tabIndex == ihTabHandler.getTabIndexEffective(TAB_ATP))
{
setButtonVisibility(bZoomPrimary, false);
setButtonVisibility(bZoomSecondary, false);
tabHandlerIndex = TAB_ATP;
initializeTabRunnable = new Runnable()
{
@Override
public void run()
{
initAtpTab(m_tableAtp);
enableDisableButtons(m_tableAtp);
}
};
enableDisableButtons(m_tableAtp);
} | else
{
return;
}
//
// Initialize tab
ihTabHandler.initializeTab(initializeTabRunnable, tabHandlerIndex);
}
private void setButtonVisibility(final CButton button, final boolean visible)
{
if (button == null)
{
return;
}
button.setVisible(visible);
}
private void enableDisableButtons(final JTable table)
{
final boolean enabled = table.getSelectedRow() >= 0;
if (bZoomPrimary != null)
{
bZoomPrimary.setEnabled(enabled);
}
if (bZoomSecondary != null)
{
bZoomSecondary.setEnabled(enabled);
}
}
@Override
public void dispose()
{
// task 09330: we reversed the order of setEnabled and dispose and that apparently solved the problem from this task
getParent().setEnabled(true);
super.dispose();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\history\impl\InvoiceHistory.java | 1 |
请完成以下Java代码 | public void setPriceList (BigDecimal PriceList)
{
set_Value (COLUMNNAME_PriceList, PriceList);
}
/** Get List Price.
@return List Price
*/
public BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Standard Price.
@param PriceStd
Standard Price | */
public void setPriceStd (BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standard Price.
@return Standard Price
*/
public BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductPriceVendorBreak.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static boolean containsIgnoreCase(String[] array, String value) {
for (String str : array) {
if (value == null && str == null) return true;
if (value != null && value.equalsIgnoreCase(str)) return true;
}
return false;
}
/**
* Join an array of strings with the given separator.
* <p>
* Note: This might be replaced by utility method from commons-lang or guava someday
* if one of those libraries is added as dependency.
* </p>
* | * @param array The array of strings
* @param separator The separator
* @return the resulting string
*/
public static String join(String[] array, String separator) {
int len = array.length;
if (len == 0) return "";
StringBuilder out = new StringBuilder();
out.append(array[0]);
for (int i = 1; i < len; i++) {
out.append(separator).append(array[i]);
}
return out.toString();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\StringUtil.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Restart getRestart() {
return this.restart;
}
public Proxy getProxy() {
return this.proxy;
}
public static class Restart {
/**
* Whether to enable remote restart.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class Proxy {
/**
* The host of the proxy to use to connect to the remote application.
*/
private @Nullable String host;
/**
* The port of the proxy to use to connect to the remote application. | */
private @Nullable Integer port;
public @Nullable String getHost() {
return this.host;
}
public void setHost(@Nullable String host) {
this.host = host;
}
public @Nullable Integer getPort() {
return this.port;
}
public void setPort(@Nullable Integer port) {
this.port = port;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\RemoteDevToolsProperties.java | 2 |
请完成以下Java代码 | public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
convertersToJsonMap.put(ThrowEvent.class, ThrowEventJsonConverter.class);
}
protected String getStencilId(BaseElement baseElement) {
ThrowEvent throwEvent = (ThrowEvent) baseElement;
List<EventDefinition> eventDefinitions = throwEvent.getEventDefinitions();
if (eventDefinitions.size() != 1) {
// return none event as default;
return STENCIL_EVENT_THROW_NONE;
}
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof SignalEventDefinition) {
return STENCIL_EVENT_THROW_SIGNAL;
} else {
return STENCIL_EVENT_THROW_NONE;
}
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
ThrowEvent throwEvent = (ThrowEvent) baseElement;
addEventProperties(throwEvent, propertiesNode); | }
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
ThrowEvent throwEvent = new ThrowEvent();
String stencilId = BpmnJsonConverterUtil.getStencilId(elementNode);
if (STENCIL_EVENT_THROW_SIGNAL.equals(stencilId)) {
convertJsonToSignalDefinition(elementNode, throwEvent);
}
return throwEvent;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\ThrowEventJsonConverter.java | 1 |
请完成以下Java代码 | public BuiltinAggregator getAggregator() {
return aggregator;
}
public void setAggregator(BuiltinAggregator aggregator) {
this.aggregator = aggregator;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
} | public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\el\ELExecutionContext.java | 1 |
请完成以下Java代码 | public class UrlEncoderUtils {
private static BitSet dontNeedEncoding;
static {
dontNeedEncoding = new BitSet(256);
int i;
for (i = 'a'; i <= 'z'; i++) {
dontNeedEncoding.set(i);
}
for (i = 'A'; i <= 'Z'; i++) {
dontNeedEncoding.set(i);
}
for (i = '0'; i <= '9'; i++) {
dontNeedEncoding.set(i);
}
dontNeedEncoding.set('+');
/**
* 这里会有误差,比如输入一个字符串 123+456,它到底是原文就是123+456还是123 456做了urlEncode后的内容呢?<br>
* 其实问题是一样的,比如遇到123%2B456,它到底是原文即使如此,还是123+456 urlEncode后的呢? <br>
* 在这里,我认为只要符合urlEncode规范的,就当作已经urlEncode过了<br>
* 毕竟这个方法的初衷就是判断string是否urlEncode过<br>
*/
dontNeedEncoding.set('-');
dontNeedEncoding.set('_');
dontNeedEncoding.set('.');
dontNeedEncoding.set('*');
}
/**
* 判断str是否urlEncoder.encode过<br>
* 经常遇到这样的情况,拿到一个URL,但是搞不清楚到底要不要encode.<Br>
* 不做encode吧,担心出错,做encode吧,又怕重复了<Br>
*
* @param str
* @return
*/
public static boolean hasUrlEncoded(String str) {
/**
* 支持JAVA的URLEncoder.encode出来的string做判断。 即: 将' '转成'+' <br>
* 0-9a-zA-Z保留 <br>
* '-','_','.','*'保留 <br>
* 其他字符转成%XX的格式,X是16进制的大写字符,范围是[0-9A-F]
*/
boolean needEncode = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i); | if (dontNeedEncoding.get((int) c)) {
continue;
}
if (c == '%' && (i + 2) < str.length()) {
// 判断是否符合urlEncode规范
char c1 = str.charAt(++i);
char c2 = str.charAt(++i);
if (isDigit16Char(c1) && isDigit16Char(c2)) {
continue;
}
}
// 其他字符,肯定需要urlEncode
needEncode = true;
break;
}
return !needEncode;
}
/**
* 判断c是否是16进制的字符
*
* @param c
* @return
*/
private static boolean isDigit16Char(char c) {
return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F');
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\utils\UrlEncoderUtils.java | 1 |
请完成以下Java代码 | public Quantity handleQuantityDecrease(final @NonNull SupplyRequiredDecreasedEvent event,
final Quantity qtyToDistribute)
{
final Collection<PPOrderCandidateId> ppOrderCandidateIds = getPpOrderCandidateIds(event);
if (ppOrderCandidateIds.isEmpty())
{
return qtyToDistribute;
}
final ImmutableList<I_PP_Order_Candidate> candidates = ppOrderCandidateDAO.getByIds(ppOrderCandidateIds);
Quantity remainingQtyToDistribute = qtyToDistribute;
for (final I_PP_Order_Candidate ppOrderCandidate : candidates)
{
remainingQtyToDistribute = doDecreaseQty(ppOrderCandidate, remainingQtyToDistribute);
if (remainingQtyToDistribute.signum() <= 0)
{
return qtyToDistribute.toZero();
}
}
return remainingQtyToDistribute;
}
private @NonNull Collection<PPOrderCandidateId> getPpOrderCandidateIds(final @NonNull SupplyRequiredDecreasedEvent event)
{
final Candidate demandCandidate = candidateRepositoryRetrieval.retrieveById(CandidateId.ofRepoId(event.getSupplyRequiredDescriptor().getDemandCandidateId()));
return candidateRepositoryWriteService.getSupplyCandidatesForDemand(demandCandidate, CandidateBusinessCase.PRODUCTION)
.stream()
.map(PPOrderCandidateAdvisedEventCreator::getPpOrderCandidateIdOrNull)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
}
@Nullable
private static PPOrderCandidateId getPpOrderCandidateIdOrNull(final Candidate candidate)
{
final ProductionDetail productionDetail = ProductionDetail.castOrNull(candidate.getBusinessCaseDetail());
return productionDetail == null ? null : productionDetail.getPpOrderCandidateId();
} | private Quantity doDecreaseQty(final I_PP_Order_Candidate ppOrderCandidate, final Quantity remainingQtyToDistribute)
{
if (isCandidateEligibleForBeingDecreased(ppOrderCandidate))
{
final Quantity quantityToProcess = Quantitys.of(ppOrderCandidate.getQtyToProcess(), UomId.ofRepoId(ppOrderCandidate.getC_UOM_ID()));
final BigDecimal qtyToDecrease = remainingQtyToDistribute.min(quantityToProcess).toBigDecimal();
ppOrderCandidate.setQtyToProcess(ppOrderCandidate.getQtyToProcess().subtract(qtyToDecrease));
ppOrderCandidate.setQtyEntered(ppOrderCandidate.getQtyEntered().subtract(qtyToDecrease));
ppOrderCandidateDAO.save(ppOrderCandidate);
return remainingQtyToDistribute.subtract(qtyToDecrease);
}
return remainingQtyToDistribute;
}
private static boolean isCandidateEligibleForBeingDecreased(final I_PP_Order_Candidate ppOrderCandidate)
{
return ppOrderCandidate.isActive() &&
!ppOrderCandidate.isClosed() &&
ppOrderCandidate.getQtyToProcess().signum() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\material\planning\PPOrderCandidateAdvisedEventCreator.java | 1 |
请完成以下Java代码 | public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set BinaryData.
@param BinaryData
Binary Data
*/
public void setBinaryData (byte[] BinaryData)
{
set_Value (COLUMNNAME_BinaryData, BinaryData);
}
/** Get BinaryData.
@return Binary Data
*/
public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
} | /** Set Image URL.
@param ImageURL
URL of image
*/
public void setImageURL (String ImageURL)
{
set_Value (COLUMNNAME_ImageURL, ImageURL);
}
/** Get Image URL.
@return URL of image
*/
public String getImageURL ()
{
return (String)get_Value(COLUMNNAME_ImageURL);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Image.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Mono<Application> toApplication(String name, Flux<Instance> instances) {
return instances.collectList().map((instanceList) -> {
Tuple2<String, Instant> status = getStatus(instanceList);
return Application.create(name)
.instances(instanceList)
.buildVersion(getBuildVersion(instanceList))
.status(status.getT1())
.statusTimestamp(status.getT2())
.build();
});
}
@Nullable
protected BuildVersion getBuildVersion(List<Instance> instances) {
List<BuildVersion> versions = instances.stream()
.map(Instance::getBuildVersion)
.filter(Objects::nonNull)
.distinct()
.sorted()
.toList();
if (versions.isEmpty()) {
return null;
}
else if (versions.size() == 1) {
return versions.get(0);
}
else {
return BuildVersion.valueOf(versions.get(0) + " ... " + versions.get(versions.size() - 1));
}
}
protected Tuple2<String, Instant> getStatus(List<Instance> instances) { | // TODO: Correct is just a second readmodel for groups
Map<String, Instant> statusWithTime = instances.stream()
.collect(toMap((instance) -> instance.getStatusInfo().getStatus(), Instance::getStatusTimestamp,
this::getMax));
if (statusWithTime.size() == 1) {
Map.Entry<String, Instant> e = statusWithTime.entrySet().iterator().next();
return Tuples.of(e.getKey(), e.getValue());
}
if (statusWithTime.containsKey(StatusInfo.STATUS_UP)) {
Instant oldestNonUp = statusWithTime.entrySet()
.stream()
.filter((e) -> !StatusInfo.STATUS_UP.equals(e.getKey()))
.map(Map.Entry::getValue)
.min(naturalOrder())
.orElse(Instant.EPOCH);
Instant latest = getMax(oldestNonUp, statusWithTime.getOrDefault(StatusInfo.STATUS_UP, Instant.EPOCH));
return Tuples.of(StatusInfo.STATUS_RESTRICTED, latest);
}
return statusWithTime.entrySet()
.stream()
.min(Map.Entry.comparingByKey(StatusInfo.severity()))
.map((e) -> Tuples.of(e.getKey(), e.getValue()))
.orElse(Tuples.of(STATUS_UNKNOWN, Instant.EPOCH));
}
protected Instant getMax(Instant t1, Instant t2) {
return (t1.compareTo(t2) >= 0) ? t1 : t2;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\ApplicationRegistry.java | 2 |
请完成以下Java代码 | public boolean hasDefinedServices() {
return !this.cli.run(new DockerCliCommand.ComposeConfig()).services().isEmpty();
}
@Override
public List<RunningService> getRunningServices() {
List<DockerCliComposePsResponse> runningPsResponses = runComposePs().stream().filter(this::isRunning).toList();
if (runningPsResponses.isEmpty()) {
return Collections.emptyList();
}
DockerComposeFile dockerComposeFile = this.cli.getDockerComposeFile();
List<RunningService> result = new ArrayList<>();
Map<String, DockerCliInspectResponse> inspected = inspect(runningPsResponses);
for (DockerCliComposePsResponse psResponse : runningPsResponses) {
DockerCliInspectResponse inspectResponse = inspectContainer(psResponse.id(), inspected);
Assert.state(inspectResponse != null, () -> "Failed to inspect container '%s'".formatted(psResponse.id()));
result.add(new DefaultRunningService(this.hostname, dockerComposeFile, psResponse, inspectResponse));
}
return Collections.unmodifiableList(result);
}
private Map<String, DockerCliInspectResponse> inspect(List<DockerCliComposePsResponse> runningPsResponses) {
List<String> ids = runningPsResponses.stream().map(DockerCliComposePsResponse::id).toList();
List<DockerCliInspectResponse> inspectResponses = this.cli.run(new DockerCliCommand.Inspect(ids));
return inspectResponses.stream().collect(Collectors.toMap(DockerCliInspectResponse::id, Function.identity()));
}
private @Nullable DockerCliInspectResponse inspectContainer(String id, | Map<String, DockerCliInspectResponse> inspected) {
DockerCliInspectResponse inspect = inspected.get(id);
if (inspect != null) {
return inspect;
}
// Docker Compose v2.23.0 returns truncated ids, so we have to do a prefix match
for (Entry<String, DockerCliInspectResponse> entry : inspected.entrySet()) {
if (entry.getKey().startsWith(id)) {
return entry.getValue();
}
}
return null;
}
private List<DockerCliComposePsResponse> runComposePs() {
return this.cli.run(new DockerCliCommand.ComposePs());
}
private boolean isRunning(DockerCliComposePsResponse psResponse) {
return !"exited".equals(psResponse.state());
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DefaultDockerCompose.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Year.
@param FiscalYear
The Fiscal Year
*/
public void setFiscalYear (String FiscalYear)
{
set_Value (COLUMNNAME_FiscalYear, FiscalYear);
}
/** Get Year.
@return The Fiscal Year
*/
public String getFiscalYear ()
{
return (String)get_Value(COLUMNNAME_FiscalYear);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair() | {
return new KeyNamePair(get_ID(), getFiscalYear());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Year.java | 1 |
请完成以下Java代码 | private ShipperId getDeliveryAddressShipperId(final I_C_Order orderRecord)
{
final Optional<ShipperId> deliveryShipShipperId = partnerDAO.getShipperIdByBPLocationId(
BPartnerLocationId.ofRepoId(
orderRecord.getC_BPartner_ID(),
orderRecord.getC_BPartner_Location_ID()));
return deliveryShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID())));
}
private ShipperId getPartnerShipperId(@NonNull final BPartnerId partnerId)
{
return partnerDAO.getShipperId(partnerId);
}
@Override
public PaymentTermId getPaymentTermId(@NonNull final I_C_Order orderRecord)
{
return PaymentTermId.ofRepoId(orderRecord.getC_PaymentTerm_ID());
}
@Override
public Money getGrandTotal(@NonNull final I_C_Order order)
{
final BigDecimal grandTotal = order.getGrandTotal();
return Money.of(grandTotal, CurrencyId.ofRepoId(order.getC_Currency_ID()));
}
@Override
public void save(final I_C_Order order)
{
orderDAO.save(order);
} | @Override
public void syncDatesFromTransportOrder(@NonNull final OrderId orderId, @NonNull final I_M_ShipperTransportation transportOrder)
{
final I_C_Order order = getById(orderId);
order.setBLDate(transportOrder.getBLDate());
order.setETA(transportOrder.getETA());
save(order);
}
@Override
public void syncDateInvoicedFromInvoice(@NonNull final OrderId orderId, @NonNull final I_C_Invoice invoice)
{
final I_C_Order order = getById(orderId);
order.setInvoiceDate(invoice.getDateInvoiced());
save(order);
}
public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter)
{
return orderDAO.getByQueryFilter(queryFilter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderBL.java | 1 |
请完成以下Java代码 | public static Builder success(String code) {
Assert.hasText(code, "code cannot be empty");
return new Builder().code(code);
}
/**
* Returns a new {@link Builder}, initialized with the error code.
* @param errorCode the error code
* @return the {@link Builder}
*/
public static Builder error(String errorCode) {
Assert.hasText(errorCode, "errorCode cannot be empty");
return new Builder().errorCode(errorCode);
}
/**
* A builder for {@link OAuth2AuthorizationResponse}.
*/
public static final class Builder {
private String redirectUri;
private String state;
private String code;
private String errorCode;
private String errorDescription;
private String errorUri;
private Builder() {
}
/**
* Sets the uri where the response was redirected to.
* @param redirectUri the uri where the response was redirected to
* @return the {@link Builder}
*/
public Builder redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
/**
* Sets the state.
* @param state the state
* @return the {@link Builder}
*/
public Builder state(String state) {
this.state = state;
return this;
}
/**
* Sets the authorization code.
* @param code the authorization code
* @return the {@link Builder}
*/
public Builder code(String code) {
this.code = code; | return this;
}
/**
* Sets the error code.
* @param errorCode the error code
* @return the {@link Builder}
*/
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
/**
* Sets the error description.
* @param errorDescription the error description
* @return the {@link Builder}
*/
public Builder errorDescription(String errorDescription) {
this.errorDescription = errorDescription;
return this;
}
/**
* Sets the error uri.
* @param errorUri the error uri
* @return the {@link Builder}
*/
public Builder errorUri(String errorUri) {
this.errorUri = errorUri;
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationResponse}.
* @return a {@link OAuth2AuthorizationResponse}
*/
public OAuth2AuthorizationResponse build() {
if (StringUtils.hasText(this.code) && StringUtils.hasText(this.errorCode)) {
throw new IllegalArgumentException("code and errorCode cannot both be set");
}
Assert.hasText(this.redirectUri, "redirectUri cannot be empty");
OAuth2AuthorizationResponse authorizationResponse = new OAuth2AuthorizationResponse();
authorizationResponse.redirectUri = this.redirectUri;
authorizationResponse.state = this.state;
if (StringUtils.hasText(this.code)) {
authorizationResponse.code = this.code;
}
else {
authorizationResponse.error = new OAuth2Error(this.errorCode, this.errorDescription, this.errorUri);
}
return authorizationResponse;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationResponse.java | 1 |
请完成以下Java代码 | protected ScopeImpl getTargetFlowScope(ProcessDefinitionImpl processDefinition) {
TransitionImpl transition = findTransition(processDefinition);
return transition.getDestination().getFlowScope();
}
@Override
protected CoreModelElement getTargetElement(ProcessDefinitionImpl processDefinition) {
return findTransition(processDefinition);
}
protected TransitionImpl findTransition(ProcessDefinitionImpl processDefinition) {
PvmActivity activity = processDefinition.findActivity(activityId);
EnsureUtil.ensureNotNull(NotValidException.class,
describeFailure("Activity '" + activityId + "' does not exist"),
"activity",
activity);
if (activity.getOutgoingTransitions().isEmpty()) {
throw new ProcessEngineException("Cannot start after activity " + activityId + "; activity "
+ "has no outgoing sequence flow to take");
}
else if (activity.getOutgoingTransitions().size() > 1) {
throw new ProcessEngineException("Cannot start after activity " + activityId + "; "
+ "activity has more than one outgoing sequence flow");
}
return (TransitionImpl) activity.getOutgoingTransitions().get(0);
}
@Override
public String getTargetElementId() { | return activityId;
}
@Override
protected String describe() {
StringBuilder sb = new StringBuilder();
sb.append("Start after activity '");
sb.append(activityId);
sb.append("'");
if (ancestorActivityInstanceId != null) {
sb.append(" with ancestor activity instance '");
sb.append(ancestorActivityInstanceId);
sb.append("'");
}
return sb.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\ActivityAfterInstantiationCmd.java | 1 |
请完成以下Java代码 | private I_C_UOM getWeightUOM(final AttributeCode weightAttribute)
{
final IAttributeStorage attributeStorage = getAttributeStorage();
final IAttributeValue attributeValue = attributeStorage.getAttributeValue(weightAttribute);
if (attributeValue == null)
{
return null;
}
return attributeValue.getC_UOM();
}
/**
* @return true if has WeightGross attribute
*/
@Override
public boolean hasWeightGross()
{
final AttributeCode attr_WeightGross = getWeightGrossAttribute();
return hasWeightAttribute(attr_WeightGross);
}
/**
* @return true if has WeightNet attribute
*/
@Override
public boolean hasWeightNet()
{
final AttributeCode attr_WeightNet = getWeightNetAttribute();
return hasWeightAttribute(attr_WeightNet);
}
/**
* @return true if has WeightTare attribute
*/
@Override
public boolean hasWeightTare()
{
final AttributeCode attr_WeightTare = getWeightTareAttribute();
return hasWeightAttribute(attr_WeightTare);
}
/** | * @return true if has WeightTare(adjust) attribute
*/
@Override
public boolean hasWeightTareAdjust()
{
final AttributeCode attr_WeightTareAdjust = getWeightTareAdjustAttribute();
return hasWeightAttribute(attr_WeightTareAdjust);
}
/**
* @return true if given attribute exists
*/
private boolean hasWeightAttribute(final AttributeCode weightAttribute)
{
if (weightAttribute == null)
{
return false;
}
final IAttributeStorage attributeStorage = getAttributeStorage();
return attributeStorage.hasAttribute(weightAttribute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\weightable\AttributeStorageWeightableWrapper.java | 1 |
请完成以下Java代码 | public boolean isVirtualColumn()
{
return this.virtualColumn;
}
public String getColumnSqlForSelect()
{
return sqlColumnForSelect;
}
public ReferenceId getAD_Reference_Value_ID()
{
return AD_Reference_Value_ID;
}
public boolean isSelectionColumn()
{
return IsSelectionColumn;
}
public boolean isMandatory()
{
return IsMandatory;
}
public boolean isKey()
{
return IsKey;
}
public boolean isParent()
{
return IsParent;
}
public boolean isStaleable()
{
return IsStaleable;
}
public boolean isLookup()
{
return org.compiere.util.DisplayType.isLookup(displayType);
}
public int getAD_Sequence_ID() | {
return AD_Sequence_ID;
}
public boolean isIdentifier()
{
return IsIdentifier;
}
@Nullable
public String getReferencedTableNameOrNull()
{
return _referencedTableName.orElse(null);
}
private static Optional<String> computeReferencedTableName(
final int displayType,
@Nullable final TableName adReferenceValueTableName)
{
// Special lookups (Location, Locator etc)
final String refTableName = DisplayType.getTableName(displayType);
if (refTableName != null)
{
return Optional.of(refTableName);
}
if (DisplayType.isLookup(displayType) && adReferenceValueTableName != null)
{
return Optional.of(adReferenceValueTableName.getAsString());
}
return Optional.empty();
}
public boolean isPasswordColumn()
{
return DisplayType.isPassword(ColumnName, displayType);
}
} // POInfoColumn | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfoColumn.java | 1 |
请完成以下Spring Boot application配置 | #
# Minio profile
#
aws:
s3:
region: sa-east-1
endpoint: http://localhost:9000
accessKeyId: 8KLF8U60JER4AP23H0A6
secretAccessKe | y: vX4uM7e7nNGPqjcXycVVhceNR7NQkiMQkR9Hoctf
bucket: bucket1 | repos\tutorials-master\aws-modules\aws-reactive\src\main\resources\application-minio.yml | 2 |
请完成以下Java代码 | public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getHidden() {
return hidden;
} | public void setHidden(Integer hidden) {
this.hidden = hidden;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", parentId=").append(parentId);
sb.append(", createTime=").append(createTime);
sb.append(", title=").append(title);
sb.append(", level=").append(level);
sb.append(", sort=").append(sort);
sb.append(", name=").append(name);
sb.append(", icon=").append(icon);
sb.append(", hidden=").append(hidden);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMenu.java | 1 |
请完成以下Java代码 | private List<JsonViewRowGeoLocation> retrieveGeoLocationsForBPartnerId(final ImmutableSetMultimap<BPartnerId, DocumentId> rowIdsByBPartnerId)
{
if (rowIdsByBPartnerId.isEmpty())
{
return ImmutableList.of();
}
final List<JsonViewRowGeoLocation> result = new ArrayList<>();
final ImmutableSet<BPartnerId> bpartnerIds = rowIdsByBPartnerId.keySet();
for (final GeographicalCoordinatesWithBPartnerLocationId bplCoordinates : bpartnersRepo.getGeoCoordinatesByBPartnerIds(bpartnerIds))
{
final BPartnerId bpartnerId = bplCoordinates.getBPartnerId();
final ImmutableSet<DocumentId> rowIds = rowIdsByBPartnerId.get(bpartnerId);
if (rowIds.isEmpty())
{
// shall not happen
logger.warn("Ignored unexpected bpartnerId={}. We have no rows for it.", bpartnerId);
continue; | }
final GeographicalCoordinates coordinate = bplCoordinates.getCoordinate();
for (final DocumentId rowId : rowIds)
{
result.add(JsonViewRowGeoLocation.builder()
.rowId(rowId)
.latitude(coordinate.getLatitude())
.longitude(coordinate.getLongitude())
.build());
}
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\geo_location\ViewGeoLocationsRestController.java | 1 |
请完成以下Java代码 | public class SimpleAuthenticationEncoder extends AbstractEncoder<UsernamePasswordMetadata> {
private static final MimeType AUTHENTICATION_MIME_TYPE = MimeTypeUtils
.parseMimeType("message/x.rsocket.authentication.v0");
private NettyDataBufferFactory defaultBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
public SimpleAuthenticationEncoder() {
super(AUTHENTICATION_MIME_TYPE);
}
@Override
public Flux<DataBuffer> encode(Publisher<? extends UsernamePasswordMetadata> inputStream,
DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
return Flux.from(inputStream)
.map((credentials) -> encodeValue(credentials, bufferFactory, elementType, mimeType, hints));
}
@Override
public DataBuffer encodeValue(UsernamePasswordMetadata credentials, DataBufferFactory bufferFactory,
ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
String username = credentials.getUsername(); | String password = credentials.getPassword();
NettyDataBufferFactory factory = nettyFactory(bufferFactory);
ByteBufAllocator allocator = factory.getByteBufAllocator();
ByteBuf simpleAuthentication = AuthMetadataCodec.encodeSimpleMetadata(allocator, username.toCharArray(),
password.toCharArray());
return factory.wrap(simpleAuthentication);
}
private NettyDataBufferFactory nettyFactory(DataBufferFactory bufferFactory) {
if (bufferFactory instanceof NettyDataBufferFactory) {
return (NettyDataBufferFactory) bufferFactory;
}
return this.defaultBufferFactory;
}
} | repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\metadata\SimpleAuthenticationEncoder.java | 1 |
请完成以下Java代码 | public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public long getTotalPage() {
return totalPage;
}
public void setTotalPage(long totalPage) {
this.totalPage = totalPage;
}
public long getTotalNumber() {
return totalNumber;
} | public void setTotalNumber(long totalNumber) {
this.totalNumber = totalNumber;
}
public List<E> getList() {
return list;
}
public void setList(List<E> list) {
this.list = list;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
} | repos\spring-boot-leaning-master\1.x\第07课:Spring Boot 集成 MyBatis\spring-boot-mybatis-annotation\src\main\java\com\neo\result\Page.java | 1 |
请完成以下Java代码 | protected UserId extractUserInChargeOrNull(final Object model)
{
final Properties ctx = extractCtxFromItem(model);
return Env.getLoggedUserIdIfExists(ctx).orElse(null);
}
@Override
public Optional<AsyncBatchId> extractAsyncBatchFromItem(final WorkpackagesOnCommitSchedulerTemplate<Object>.Collector collector, final Object item)
{
return asyncBatchBL.getAsyncBatchId(item);
}
};
static
{
SCHEDULER.setCreateOneWorkpackagePerAsyncBatch(true);
}
// services
private final transient IQueueDAO queueDAO = Services.get(IQueueDAO.class);
private final transient IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class);
private final transient IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class);
@Override
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName)
{
try (final IAutoCloseable ignored = invoiceCandBL.setUpdateProcessInProgress())
{
final List<Object> models = queueDAO.retrieveAllItemsSkipMissing(workpackage, Object.class);
for (final Object model : models) | {
try (final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(model))
{
final List<I_C_Invoice_Candidate> invoiceCandidates = invoiceCandidateHandlerBL.createMissingCandidatesFor(model);
Loggables.addLog("Created {} invoice candidate for {}", invoiceCandidates.size(), model);
}
}
}
catch (final LockFailedException e)
{
// One of the models could not be locked => postpone processing this workpackage
throw WorkpackageSkipRequestException.createWithThrowable("Skip processing because: " + e.getLocalizedMessage(), e);
}
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\CreateMissingInvoiceCandidatesWorkpackageProcessor.java | 1 |
请完成以下Java代码 | public int getPA_Hierarchy_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Hierarchy_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_MeasureCalc getPA_MeasureCalc() throws RuntimeException
{
return (I_PA_MeasureCalc)MTable.get(getCtx(), I_PA_MeasureCalc.Table_Name)
.getPO(getPA_MeasureCalc_ID(), get_TrxName()); }
/** Set Measure Calculation.
@param PA_MeasureCalc_ID
Calculation method for measuring performance
*/
public void setPA_MeasureCalc_ID (int PA_MeasureCalc_ID)
{
if (PA_MeasureCalc_ID < 1)
set_Value (COLUMNNAME_PA_MeasureCalc_ID, null);
else
set_Value (COLUMNNAME_PA_MeasureCalc_ID, Integer.valueOf(PA_MeasureCalc_ID));
}
/** Get Measure Calculation.
@return Calculation method for measuring performance
*/
public int getPA_MeasureCalc_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_MeasureCalc_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Ratio getPA_Ratio() throws RuntimeException
{
return (I_PA_Ratio)MTable.get(getCtx(), I_PA_Ratio.Table_Name)
.getPO(getPA_Ratio_ID(), get_TrxName()); }
/** Set Ratio.
@param PA_Ratio_ID
Performace Ratio
*/
public void setPA_Ratio_ID (int PA_Ratio_ID)
{
if (PA_Ratio_ID < 1)
set_Value (COLUMNNAME_PA_Ratio_ID, null);
else
set_Value (COLUMNNAME_PA_Ratio_ID, Integer.valueOf(PA_Ratio_ID));
}
/** Get Ratio.
@return Performace Ratio
*/
public int getPA_Ratio_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Ratio_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Measure.java | 1 |
请完成以下Java代码 | static Money computeAllocationAmt(
@NonNull final Timestamp dateTrx,
@NonNull final Money invoiceOpenAmt,
@NonNull final Money payAmt,
@NonNull final Money discountAmt,
@NonNull final Money writeOffAmt,
@Nullable final CurrencyConversionTypeId conversionTypeId,
@NonNull final ClientAndOrgId clientAndOrgId)
{
final Money discountAndWriteOffAmt = discountAmt.add(writeOffAmt);
final Money payAmtEffective;
final Money discountAndWriteOffAmtEffective;
if (CurrencyId.equals(payAmt.getCurrencyId(), invoiceOpenAmt.getCurrencyId()))
{
payAmtEffective = payAmt;
discountAndWriteOffAmtEffective = discountAndWriteOffAmt;
}
else
{
final ICurrencyBL currencyBL = Services.get(ICurrencyBL.class);
final CurrencyConversionContext currencyConversionContext = currencyBL.createCurrencyConversionContext(TimeUtil.asInstant(dateTrx),
conversionTypeId,
clientAndOrgId.getClientId(),
clientAndOrgId.getOrgId());
payAmtEffective = currencyBL.convert(currencyConversionContext, payAmt, invoiceOpenAmt.getCurrencyId()).getAmountAsMoney();
discountAndWriteOffAmtEffective = currencyBL.convert(currencyConversionContext, discountAndWriteOffAmt, invoiceOpenAmt.getCurrencyId()).getAmountAsMoney();
}
final Money maxAllocAmt = invoiceOpenAmt.subtract(discountAndWriteOffAmtEffective);
return payAmtEffective.min(maxAllocAmt);
}
@NonNull
private Money getPayAmtAsMoney() | {
return Money.of(getPayAmt(), CurrencyId.ofRepoId(getC_Currency_ID()));
}
@NonNull
private Money getDiscountAmtAsMoney()
{
return Money.of(getDiscountAmt(), CurrencyId.ofRepoId(getC_Currency_ID()));
}
@NonNull
private Money getWriteOffAmtAsMoney()
{
return Money.of(getWriteOffAmt(), CurrencyId.ofRepoId(getC_Currency_ID()));
}
} // MPayment | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MPayment.java | 1 |
请完成以下Java代码 | public void close() throws IOException {
this.data.close();
}
/**
* {@link DataBlock} that points to part of the original data block.
*/
final class DataPart implements DataBlock {
private final long offset;
private final long size;
DataPart(long offset, long size) {
this.offset = offset;
this.size = size;
}
@Override
public long size() throws IOException {
return this.size;
}
@Override
public int read(ByteBuffer dst, long pos) throws IOException {
int remaining = (int) (this.size - pos); | if (remaining <= 0) {
return -1;
}
int originalLimit = -1;
if (dst.remaining() > remaining) {
originalLimit = dst.limit();
dst.limit(dst.position() + remaining);
}
int result = VirtualZipDataBlock.this.data.read(dst, this.offset + pos);
if (originalLimit != -1) {
dst.limit(originalLimit);
}
return result;
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\zip\VirtualZipDataBlock.java | 1 |
请完成以下Java代码 | public boolean isAllowThreadInherited()
{
return true;
}
};
}
@Override
public void setThreadInheritedOnRunnableFail(final OnRunnableFail onRunnableFail)
{
threadLocalOnRunnableFail.set(onRunnableFail);
}
private final OnRunnableFail getThreadInheritedOnRunnableFail(final OnRunnableFail onRunnableFailDefault)
{
final OnRunnableFail onRunnableFail = threadLocalOnRunnableFail.get();
return onRunnableFail == null ? onRunnableFailDefault : onRunnableFail;
}
@Override
public final boolean isDebugTrxCreateStacktrace()
{
return debugTrxCreateStacktrace;
}
@Override
public final void setDebugTrxCreateStacktrace(final boolean debugTrxCreateStacktrace)
{
this.debugTrxCreateStacktrace = debugTrxCreateStacktrace;
}
@Override
public final boolean isDebugTrxCloseStacktrace()
{
return debugTrxCloseStacktrace;
}
@Override
public final void setDebugTrxCloseStacktrace(final boolean debugTrxCloseStacktrace)
{
this.debugTrxCloseStacktrace = debugTrxCloseStacktrace;
}
@Override
public final void setDebugClosedTransactions(final boolean enabled)
{
trxName2trxLock.lock();
try
{
if (enabled)
{
if (debugClosedTransactionsList == null)
{
debugClosedTransactionsList = new ArrayList<>();
}
}
else
{
debugClosedTransactionsList = null;
}
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public final boolean isDebugClosedTransactions()
{
return debugClosedTransactionsList != null;
}
@Override | public final List<ITrx> getDebugClosedTransactions()
{
trxName2trxLock.lock();
try
{
if (debugClosedTransactionsList == null)
{
return Collections.emptyList();
}
return new ArrayList<>(debugClosedTransactionsList);
}
finally
{
trxName2trxLock.unlock();
}
}
@Override
public void setDebugConnectionBackendId(boolean debugConnectionBackendId)
{
this.debugConnectionBackendId = debugConnectionBackendId;
}
@Override
public boolean isDebugConnectionBackendId()
{
return debugConnectionBackendId;
}
@Override
public String toString()
{
return "AbstractTrxManager [trxName2trx=" + trxName2trx + ", trxName2trxLock=" + trxName2trxLock + ", trxNameGenerator=" + trxNameGenerator + ", threadLocalTrx=" + threadLocalTrx + ", threadLocalOnRunnableFail=" + threadLocalOnRunnableFail + ", debugTrxCreateStacktrace=" + debugTrxCreateStacktrace + ", debugTrxCloseStacktrace=" + debugTrxCloseStacktrace + ", debugClosedTransactionsList="
+ debugClosedTransactionsList + ", debugConnectionBackendId=" + debugConnectionBackendId + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrxManager.java | 1 |
请完成以下Java代码 | public Optional<BPartnerId> getLastUpdatedPreferredPharmacyByPartnerId(@NonNull final BPartnerId bpartnerId)
{
return queryBL.createQueryBuilder(org.compiere.model.I_C_BP_Relation.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(org.compiere.model.I_C_BP_Relation.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addEqualsFilter(org.compiere.model.I_C_BP_Relation.COLUMNNAME_Role, X_C_BP_Relation.ROLE_PreferredPharmacy)
.orderByDescending(org.compiere.model.I_C_BP_Relation.COLUMNNAME_Updated)
.create()
.firstOptional(org.compiere.model.I_C_BP_Relation.class)
.map(bpRelation -> BPartnerId.ofRepoId(bpRelation.getC_BPartnerRelation_ID()));
}
@Override
public void saveOrUpdate(final @NonNull OrgId orgId, final BPRelation rel)
{
final I_C_BP_Relation relation;
if (rel.getBpRelationId() != null)
{
relation = InterfaceWrapperHelper.load(rel.getBpRelationId(), I_C_BP_Relation.class);
}
else
{
final Optional<I_C_BP_Relation> bpartnerRelation = getRelationsForSourceBpartner(rel.getBpartnerId())
.filter(r -> r.getC_BPartnerRelation_ID() == rel.getTargetBPartnerId().getRepoId())
.findFirst();
relation = bpartnerRelation.orElseGet(() -> InterfaceWrapperHelper.newInstance(I_C_BP_Relation.class));
}
relation.setAD_Org_ID(orgId.getRepoId());
relation.setC_BPartner_ID(rel.getBpartnerId().getRepoId());
if (rel.getBpRelationId() != null)
{
relation.setC_BPartner_Location_ID(rel.getBpRelationId().getRepoId());
}
relation.setC_BPartnerRelation_ID(rel.getTargetBPartnerId().getRepoId());
relation.setC_BPartnerRelation_Location_ID(rel.getTargetBPLocationId().getRepoId());
relation.setName(coalesceNotNull(rel.getName(), relation.getName())); | relation.setDescription(coalesce(rel.getDescription(), relation.getDescription()));
relation.setRole(rel.getRole() != null ? rel.getRole().getCode() : relation.getRole());
if (rel.getExternalId() != null)
{
relation.setExternalId(rel.getExternalId().getValue());
}
relation.setIsActive(coalesceNotNull(rel.getActive(), relation.isActive(), true));
relation.setIsBillTo(coalesceNotNull(rel.getBillTo(), relation.isBillTo()));
relation.setIsFetchedFrom(coalesceNotNull(rel.getFetchedFrom(), relation.isFetchedFrom()));
relation.setIsHandOverLocation(coalesceNotNull(rel.getHandoverLocation(), relation.isHandOverLocation()));
relation.setIsPayFrom(coalesceNotNull(rel.getPayFrom(), relation.isPayFrom()));
relation.setIsRemitTo(coalesceNotNull(rel.getRemitTo(), relation.isRemitTo()));
relation.setIsShipTo(coalesceNotNull(rel.getShipTo(), relation.isShipTo()));
InterfaceWrapperHelper.save(relation);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\api\impl\BPRelationDAO.java | 1 |
请完成以下Java代码 | public MFColor setGradientUpperColor(final Color color)
{
if (!isGradient() || color == null)
{
return this;
}
return toBuilder().gradientUpperColor(color).build();
}
public MFColor setGradientLowerColor(final Color color)
{
if (!isGradient() || color == null)
{
return this;
}
return toBuilder().gradientLowerColor(color).build();
}
public MFColor setGradientStartPoint(final int startPoint)
{
if (!isGradient())
{
return this;
}
return toBuilder().gradientStartPoint(startPoint).build();
}
public MFColor setGradientRepeatDistance(final int repeatDistance)
{
if (!isGradient())
{
return this;
}
return toBuilder().gradientRepeatDistance(repeatDistance).build();
}
public MFColor setTextureURL(final URL textureURL)
{
if (!isTexture() || textureURL == null)
{
return this;
}
return toBuilder().textureURL(textureURL).build();
}
public MFColor setTextureTaintColor(final Color color)
{
if (!isTexture() || color == null)
{
return this;
}
return toBuilder().textureTaintColor(color).build();
}
public MFColor setTextureCompositeAlpha(final float alpha)
{
if (!isTexture())
{
return this;
}
return toBuilder().textureCompositeAlpha(alpha).build();
}
public MFColor setLineColor(final Color color)
{
if (!isLine() || color == null)
{
return this;
}
return toBuilder().lineColor(color).build();
}
public MFColor setLineBackColor(final Color color)
{
if (!isLine() || color == null)
{
return this;
}
return toBuilder().lineBackColor(color).build();
}
public MFColor setLineWidth(final float width)
{
if (!isLine())
{
return this;
}
return toBuilder().lineWidth(width).build();
} | public MFColor setLineDistance(final int distance)
{
if (!isLine())
{
return this;
}
return toBuilder().lineDistance(distance).build();
}
public MFColor toFlatColor()
{
switch (getType())
{
case FLAT:
return this;
case GRADIENT:
return ofFlatColor(getGradientUpperColor());
case LINES:
return ofFlatColor(getLineBackColor());
case TEXTURE:
return ofFlatColor(getTextureTaintColor());
default:
throw new IllegalStateException("Type not supported: " + getType());
}
}
public String toHexString()
{
final Color awtColor = toFlatColor().getFlatColor();
return toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
public static String toHexString(final int red, final int green, final int blue)
{
Check.assume(red >= 0 && red <= 255, "Invalid red value: {}", red);
Check.assume(green >= 0 && green <= 255, "Invalid green value: {}", green);
Check.assume(blue >= 0 && blue <= 255, "Invalid blue value: {}", blue);
return String.format("#%02x%02x%02x", red, green, blue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\MFColor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static List<JsonVendorContact> toJsonBPartnerContact(@NonNull final List<JsonResponseContact> contacts)
{
return contacts.stream()
.map(contact -> JsonVendorContact.builder()
.metasfreshId(contact.getMetasfreshId())
.firstName(contact.getFirstName())
.lastName(contact.getLastName())
.email(contact.getEmail())
.fax(contact.getFax())
.greeting(contact.getGreeting())
.title(contact.getTitle())
.phone(contact.getPhone())
.phone2(contact.getPhone2())
.contactRoles(toContactRoles(contact.getRoles()))
.position(contact.getPosition() == null ? null : contact.getPosition().getName())
.build())
.collect(ImmutableList.toImmutableList());
}
@Nullable
private static List<String> toContactRoles(@Nullable final List<JsonResponseContactRole> roles)
{
if (Check.isEmpty(roles))
{
return null;
}
return roles.stream() | .map(JsonResponseContactRole::getName)
.collect(ImmutableList.toImmutableList());
}
@NonNull
private static JsonVendor.JsonVendorBuilder initVendorWithLocationFields(@NonNull final JsonResponseLocation jsonResponseLocation)
{
return JsonVendor.builder()
.address1(jsonResponseLocation.getAddress1())
.address2(jsonResponseLocation.getAddress2())
.address3(jsonResponseLocation.getAddress3())
.address4(jsonResponseLocation.getAddress4())
.postal(jsonResponseLocation.getPostal())
.city(jsonResponseLocation.getCity())
.countryCode(jsonResponseLocation.getCountryCode())
.gln(jsonResponseLocation.getGln());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\ExportVendorProcessor.java | 2 |
请完成以下Java代码 | public class CountryAttributeDAO implements ICountryAttributeDAO
{
public static final String SYSCONFIG_CountryAttribute = "de.metas.swat.CountryAttribute";
@Override
public AttributeListValue retrieveAttributeValue(final Properties ctx, @NonNull final I_C_Country country, final boolean includeInactive)
{
final String countryValue = country.getCountryCode();
if (Check.isEmpty(countryValue, true))
{
return null;
}
final Attribute countryAttribute = retrieveCountryAttribute(ctx);
if (countryAttribute == null)
{
return null;
}
//
// First try: search by CountryCode
final AttributeListValue attributeValueByCode = Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(countryAttribute, countryValue, includeInactive);
if (attributeValueByCode != null)
{
return attributeValueByCode;
}
//
// Second try: Search by country name
final String countryName = country.getName();
final AttributeListValue attributeValueByName = Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(countryAttribute, countryName, includeInactive);
if (attributeValueByName != null)
{
return attributeValueByName;
}
//
// Nothing found, just return null
return null;
}
@Override
public Attribute retrieveCountryAttribute(final Properties ctx)
{
final int adClientId = Env.getAD_Client_ID(ctx); | final int adOrgId = Env.getAD_Org_ID(ctx);
final AttributeId countryAttributeId = retrieveCountryAttributeId(adClientId, adOrgId);
if (countryAttributeId == null)
{
return null;
}
return Services.get(IAttributeDAO.class).getAttributeById(countryAttributeId);
}
@Override
public AttributeId retrieveCountryAttributeId(final int adClientId, final int adOrgId)
{
final int countryAttributeId = Services.get(ISysConfigBL.class)
.getIntValue(SYSCONFIG_CountryAttribute,
-1, // defaultValue
adClientId,
adOrgId);
return AttributeId.ofRepoIdOrNull(countryAttributeId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\CountryAttributeDAO.java | 1 |
请完成以下Java代码 | public String getCreatorId() {
return this.creatorId;
}
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public int getTotalPlayers() {
return this.totalPlayers;
}
public void setTotalPlayers(int totalPlayers) {
this.totalPlayers = totalPlayers;
}
public GameMode getMode() {
return this.mode;
} | public void setMode(GameMode mode) {
this.mode = mode;
}
public int getMaxPlayers() {
return this.maxPlayers;
}
public void setMaxPlayers(int maxPlayers) {
this.maxPlayers = maxPlayers;
}
public List<PlayerDTO> getPlayers() {
return this.players;
}
public void setPlayers(List<PlayerDTO> players) {
this.players = players;
}
} | repos\tutorials-master\libraries-data\src\main\java\com\baeldung\modelmapper\dto\GameDTO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Group
{
public Campaign toCampaign()
{
return finishAndBuild(Campaign.builder());
}
public Campaign updateCampaign(@NonNull final Campaign campaign)
{
return finishAndBuild(campaign.toBuilder());
}
private Campaign finishAndBuild(@NonNull final CampaignBuilder builder)
{
return builder
.name(name)
.remoteId(String.valueOf(id))
.build();
}
String name;
int id;
long stamp;
long last_mailing;
long last_changed;
boolean isLocked; | @JsonCreator
public Group(
@JsonProperty("name") @NonNull final String name,
@JsonProperty("id") int id,
@JsonProperty("stamp") long stamp,
@JsonProperty("last_mailing") long last_mailing,
@JsonProperty("last_changed") long last_changed,
@JsonProperty("isLocked") boolean isLocked)
{
this.name = name;
this.id = id;
this.stamp = stamp;
this.last_mailing = last_mailing;
this.last_changed = last_changed;
this.isLocked = isLocked;
}
public CampaignRemoteUpdate toCampaignUpdate()
{
return CampaignRemoteUpdate.builder()
.remoteId(String.valueOf(id))
.name(name)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\cleverreach\src\main\java\de\metas\marketing\gateway\cleverreach\restapi\models\Group.java | 2 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Net Days.
@param NetDays
Net Days in which payment is due
*/
public void setNetDays (int NetDays)
{
set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays));
}
/** Get Net Days.
@return Net Days in which payment is due
*/
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from. | @return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java | 1 |
请完成以下Java代码 | public CloudEvent exec(CloudEvent cloudEvent) {
eventList.add(cloudEvent);
demoActivities.before(cloudEvent);
// wait for second event
Workflow.await(() -> eventList.size() == 2);
demoActivities.after(cloudEvent);
// return demo result CE
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.createObjectNode();
((ObjectNode)node).putArray("events");
for(CloudEvent c : eventList) {
((ArrayNode)node.get("events")).add(c.getId());
}
((ObjectNode)node).put("outcome", "done");
return CloudEventBuilder.v1()
.withId(String.valueOf(Workflow.newRandom().nextInt(1000 - 1 + 1) + 1)) | .withType("example.demo.result")
.withSource(URI.create("http://temporal.io"))
.withData(
"application/json",
node.toPrettyString().getBytes(StandardCharsets.UTF_8))
.build();
}
@Override // SignalMethod
public void addEvent(CloudEvent cloudEvent) {
eventList.add(cloudEvent);
}
@Override // QueryMethod
public CloudEvent getLastEvent() {
if (eventList == null || eventList.isEmpty()) {
return null;
}
return eventList.get(eventList.size() - 1);
}
} | repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\workflows\DemoWorkflowImpl.java | 1 |
请完成以下Java代码 | public java.math.BigDecimal getPriceList ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceList);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Standardpreis.
@param PriceStd Standardpreis */
@Override
public void setPriceStd (java.math.BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standardpreis.
@return Standardpreis */
@Override
public java.math.BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return BigDecimal.ZERO;
return bd;
} | /** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\pricing\attributebased\X_M_ProductPrice_Attribute.java | 1 |
请完成以下Java代码 | public ImmutableList<Node<T>> listAllNodesBelow()
{
final ArrayList<Node<T>> list = new ArrayList<>();
listAllNodesBelow_rec(this, list);
return ImmutableList.copyOf(list);
}
/**
* Creates and returns an ordered list with {@code this} and all
* the nodes found above it on the same branch in the tree.
*
* e.g given the following tree:
* ----1----
* ---/-\---
* --2---3--
* --|---|--
* --4---5--
* /-|-\----
* 6-7-8----
*
* if {@code getUpStream()} it's called for node 8,
* it will return: [8,4,2,1]
*/
public ArrayList<Node<T>> getUpStream()
{
Node<T> currentNode = this;
final ArrayList<Node<T>> upStream = new ArrayList<>();
upStream.add(currentNode);
while (currentNode.parent != null)
{
upStream.add(currentNode.parent);
currentNode = currentNode.parent;
}
return upStream;
}
/**
* Tries to found a node among the ones found below {@code this} on the same branch
* in the tree with {@code value} equal to the given one.
*
* e.g given the following tree:
* ----1----
* ---/-\---
* --2---3--
* --|---|--
* --4---5--
* /-|-\----
* 6-7-8----
*
* if {@code getNode(4)} it's called for node 1,
* it will return: Optional.of(Node(4)).
*/
@NonNull
public Optional<Node<T>> getNode(final T value)
{
return Optional.ofNullable(getNode_rec(this, value));
}
@NonNull
public String toString() | {
return this.getValue().toString();
}
@Nullable
private Node<T> getNode_rec(final Node<T> currentNode, final T value)
{
if (currentNode.value.equals(value))
{
return currentNode;
}
else
{
final Iterator<Node<T>> iterator = currentNode.getChildren().iterator();
Node<T> requestedNode = null;
while (requestedNode == null && iterator.hasNext())
{
requestedNode = getNode_rec(iterator.next(), value);
}
return requestedNode;
}
}
private void listAllNodesBelow_rec(final Node<T> currentNode, final List<Node<T>> nodeList)
{
nodeList.add(currentNode);
if (!currentNode.isLeaf())
{
currentNode.getChildren().forEach(child -> listAllNodesBelow_rec(child, nodeList));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Node.java | 1 |
请完成以下Java代码 | protected Object instantiateDelegate(String className, List<FieldDeclaration> fieldDeclarations) {
return AbstractClassDelegate.defaultInstantiateDelegate(className, fieldDeclarations);
}
// --HELPER METHODS (also usable by external classes)
// ----------------------------------------
public static Object defaultInstantiateDelegate(Class<?> clazz, List<FieldDeclaration> fieldDeclarations, ServiceTask serviceTask) {
return defaultInstantiateDelegate(clazz.getName(), fieldDeclarations, serviceTask);
}
public static Object defaultInstantiateDelegate(Class<?> clazz, List<FieldDeclaration> fieldDeclarations) {
return defaultInstantiateDelegate(clazz.getName(), fieldDeclarations);
}
public static Object defaultInstantiateDelegate(String className, List<FieldDeclaration> fieldDeclarations, ServiceTask serviceTask) {
Object object = ReflectUtil.instantiate(className);
applyFieldDeclaration(fieldDeclarations, object);
if (serviceTask != null) {
ReflectUtil.invokeSetterOrField(object, "serviceTask", serviceTask, false);
}
return object;
}
public static Object defaultInstantiateDelegate(String className, List<FieldDeclaration> fieldDeclarations) {
return defaultInstantiateDelegate(className, fieldDeclarations, null);
}
public static void applyFieldDeclaration(List<FieldDeclaration> fieldDeclarations, Object target) {
applyFieldDeclaration(fieldDeclarations, target, true);
}
public static void applyFieldDeclaration(List<FieldDeclaration> fieldDeclarations, Object target, boolean throwExceptionOnMissingField) {
if (fieldDeclarations != null) {
for (FieldDeclaration declaration : fieldDeclarations) { | applyFieldDeclaration(declaration, target, throwExceptionOnMissingField);
}
}
}
public static void applyFieldDeclaration(FieldDeclaration declaration, Object target) {
applyFieldDeclaration(declaration, target, true);
}
public static void applyFieldDeclaration(FieldDeclaration declaration, Object target, boolean throwExceptionOnMissingField) {
ReflectUtil.invokeSetterOrField(target, declaration.getName(), declaration.getValue(), throwExceptionOnMissingField);
}
/**
* returns the class name this {@link AbstractClassDelegate} is configured to. Comes in handy if you want to check which delegates you already have e.g. in a list of listeners
*/
public String getClassName() {
return className;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\helper\AbstractClassDelegate.java | 1 |
请完成以下Java代码 | public class PlanFragmentExport extends AbstractPlanItemDefinitionExport<PlanFragment> {
private static final PlanFragmentExport instance = new PlanFragmentExport();
public static PlanFragmentExport getInstance() {
return instance;
}
private PlanFragmentExport() {
}
@Override
protected Class<PlanFragment> getExportablePlanItemDefinitionClass() {
return PlanFragment.class;
}
@Override
protected String getPlanItemDefinitionXmlElementValue(PlanFragment planFragment) {
return ELEMENT_PLAN_FRAGMENT;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(PlanFragment planFragment, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(planFragment, xtw); | }
@Override
protected void writePlanItemDefinitionBody(CmmnModel model, PlanFragment planFragment, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception {
super.writePlanItemDefinitionBody(model, planFragment, xtw, options);
for (PlanItem planItem : planFragment.getPlanItems()) {
PlanItemExport.writePlanItem(model, planItem, xtw);
}
for (Sentry sentry : planFragment.getSentries()) {
SentryExport.writeSentry(model, sentry, xtw);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\PlanFragmentExport.java | 1 |
请完成以下Java代码 | public CommentEntityManager getCommentEntityManager() {
return getSession(CommentEntityManager.class);
}
public PropertyEntityManager getPropertyEntityManager() {
return getSession(PropertyEntityManager.class);
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getSession(EventSubscriptionEntityManager.class);
}
public Map<Class<?>, SessionFactory> getSessionFactories() {
return sessionFactories;
}
public HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
// getters and setters //////////////////////////////////////////////////////
public TransactionContext getTransactionContext() {
return transactionContext;
}
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
} | public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public FlowableEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java | 1 |
请完成以下Java代码 | default DocumentFilterDescriptorsProvider getFilterDescriptors()
{
throw new UnsupportedOperationException();
}
/**
* @return registered document filter to SQL converters
*/
default SqlDocumentFilterConvertersList getFilterConverters()
{
return SqlDocumentFilterConverters.emptyList();
}
default Optional<SqlDocumentFilterConverterDecorator> getFilterConverterDecorator()
{
return Optional.empty();
}
default String replaceTableNameWithTableAlias(final String sql)
{
final String tableName = getTableName();
final String tableAlias = getTableAlias();
return replaceTableNameWithTableAlias(sql, tableName, tableAlias);
}
default String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableAlias)
{
final String tableName = getTableName(); | return replaceTableNameWithTableAlias(sql, tableName, tableAlias);
}
default SqlAndParams replaceTableNameWithTableAlias(final SqlAndParams sql, @NonNull final String tableAlias)
{
return SqlAndParams.of(
replaceTableNameWithTableAlias(sql.getSql(), tableAlias),
sql.getSqlParams());
}
static String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableName, @NonNull final String tableAlias)
{
if (sql == null || sql.isEmpty())
{
return sql;
}
final String matchTableNameIgnoringCase = "(?i)" + Pattern.quote(tableName + ".");
final String sqlFixed = sql.replaceAll(matchTableNameIgnoringCase, tableAlias + ".");
return sqlFixed;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlEntityBinding.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ManagedChannel configureSsl(NettyChannelBuilder NettyChannelBuilder) throws SSLException {
return NettyChannelBuilder.useTransportSecurity().sslContext(getSslContext()).build();
}
private SslContext getSslContext() throws SSLException {
final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
final HttpClientProperties.Ssl ssl = getSslProperties();
boolean useInsecureTrustManager = ssl.isUseInsecureTrustManager();
SslBundle bundle = getBundle();
if (useInsecureTrustManager) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]);
}
if (!useInsecureTrustManager && ssl.getTrustedX509Certificates().size() > 0) { | sslContextBuilder.trustManager(getTrustedX509CertificatesForTrustManager());
}
else if (bundle != null) {
sslContextBuilder.trustManager(bundle.getManagers().getTrustManagerFactory());
}
if (bundle != null) {
sslContextBuilder.keyManager(bundle.getManagers().getKeyManagerFactory());
}
else {
sslContextBuilder.keyManager(getKeyManagerFactory());
}
return sslContextBuilder.build();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GrpcSslConfigurer.java | 2 |
请完成以下Java代码 | private void deactivateUsers(final List<BPartnerId> partnerIds, final Instant date)
{
final ICompositeQueryUpdater<I_AD_User> queryUpdater = queryBL.createCompositeQueryUpdater(I_AD_User.class)
.addSetColumnValue(I_AD_User.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_AD_User.class)
.addInArrayFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, partnerIds)
.create()
.update(queryUpdater);
}
private void deactivateLocations(final List<BPartnerId> partnerIds, final Instant date)
{
final ICompositeQueryUpdater<I_C_BPartner_Location> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BPartner_Location.class)
.addSetColumnValue(I_C_BPartner_Location.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_C_BPartner_Location.class)
.addInArrayFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, partnerIds) | .create()
.update(queryUpdater);
}
private void deactivatePartners(final List<BPartnerId> partnerIds, final Instant date)
{
final ICompositeQueryUpdater<I_C_BPartner> queryUpdater = queryBL.createCompositeQueryUpdater(I_C_BPartner.class)
.addSetColumnValue(I_C_BPartner.COLUMNNAME_IsActive, false);
queryBL
.createQueryBuilder(I_C_BPartner.class)
.addInArrayFilter(I_C_BPartner.COLUMNNAME_C_BPartner_ID, partnerIds)
.create()
.update(queryUpdater);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\process\C_BPartner_DeactivateAfterOrgChange.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", emailId=" + emailId + ", phoneNumber=" +
phoneNumber + "]";
}
Customer(Integer id, String name, String emailId, Long phoneNumber) { | super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
} | repos\tutorials-master\core-java-modules\core-java-streams-6\src\main\java\com\baeldung\streams\gettersreturningnull\Customer.java | 1 |
请完成以下Java代码 | public XMLGregorianCalendar getBirthdate() {
return birthdate;
}
/**
* Sets the value of the birthdate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setBirthdate(XMLGregorianCalendar value) {
this.birthdate = value;
}
/**
* Gets the value of the ssn property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getSsn() {
return ssn;
}
/**
* Sets the value of the ssn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSsn(String value) {
this.ssn = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\PatientAddressType.java | 1 |
请完成以下Java代码 | class UrlJarManifest {
private static final Object NONE = new Object();
private final ManifestSupplier supplier;
private volatile Object supplied;
UrlJarManifest(ManifestSupplier supplier) {
this.supplier = supplier;
}
Manifest get() throws IOException {
Manifest manifest = supply();
if (manifest == null) {
return null;
}
Manifest copy = new Manifest();
copy.getMainAttributes().putAll((Map<?, ?>) manifest.getMainAttributes().clone());
manifest.getEntries().forEach((key, value) -> copy.getEntries().put(key, cloneAttributes(value)));
return copy;
}
Attributes getEntryAttributes(JarEntry entry) throws IOException {
Manifest manifest = supply();
if (manifest == null) {
return null;
}
Attributes attributes = manifest.getEntries().get(entry.getName());
return cloneAttributes(attributes);
} | private Attributes cloneAttributes(Attributes attributes) {
return (attributes != null) ? (Attributes) attributes.clone() : null;
}
private Manifest supply() throws IOException {
Object supplied = this.supplied;
if (supplied == null) {
supplied = this.supplier.getManifest();
this.supplied = (supplied != null) ? supplied : NONE;
}
return (supplied != NONE) ? (Manifest) supplied : null;
}
/**
* Interface used to supply the actual manifest.
*/
@FunctionalInterface
interface ManifestSupplier {
Manifest getManifest() throws IOException;
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\UrlJarManifest.java | 1 |
请完成以下Java代码 | public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeightUOM (final @Nullable java.lang.String WeightUOM)
{
set_Value (COLUMNNAME_WeightUOM, WeightUOM);
}
@Override
public java.lang.String getWeightUOM()
{
return get_ValueAsString(COLUMNNAME_WeightUOM);
}
@Override
public void setWeight_UOM_ID (final int Weight_UOM_ID)
{
if (Weight_UOM_ID < 1)
set_Value (COLUMNNAME_Weight_UOM_ID, null);
else
set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID);
}
@Override
public int getWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID);
} | @Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
@Override
public void setX12DE355 (final @Nullable java.lang.String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
@Override
public java.lang.String getX12DE355()
{
return get_ValueAsString(COLUMNNAME_X12DE355);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Product.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.