instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public ImmutableList<POSCashJournalLine> getLines() {return ImmutableList.copyOf(lines);}
public void close(
@NonNull final Money cashClosingBalance,
@Nullable final String closingNote,
@NonNull final UserId cashierId)
{
cashClosingBalance.assertCurrencyId(currencyId);
if (isClosed)
{
throw new AdempiereException("Already closed");
}
final Money closingDifferenceAmt = cashClosingBalance.subtract(this.cashEndingBalance);
if (!closingDifferenceAmt.isZero())
{
addClosingDifference(closingDifferenceAmt, cashierId, closingNote);
}
this.closingNote = closingNote;
this.isClosed = true;
}
private void addClosingDifference(@NonNull final Money closingDifferenceAmt, @NonNull final UserId cashierId, @Nullable final String description)
{
add(POSCashJournalLine.builder()
.type(POSCashJournalLineType.CASH_CLOSING_DIFFERENCE)
.amount(closingDifferenceAmt)
.cashierId(cashierId)
.description(description)
.build());
}
private void add(@NonNull final POSCashJournalLine line)
{
lines.add(line);
updateTotals();
}
private void updateTotals()
{
Money cashEndingBalance = this.cashBeginningBalance;
for (final POSCashJournalLine line : lines)
{
if (line.isCash()) | {
cashEndingBalance = cashEndingBalance.add(line.getAmount());
}
}
this.cashEndingBalance = cashEndingBalance;
}
public void addPayments(final POSOrder posOrder)
{
final POSOrderId posOrderId = posOrder.getLocalIdNotNull();
final UserId cashierId = posOrder.getCashierId();
posOrder.streamPaymentsNotDeleted()
.filter(POSPayment::isSuccessful)
.forEach(posPayment -> addPayment(posPayment, posOrderId, cashierId));
}
private void addPayment(final POSPayment posPayment, POSOrderId posOrderId, UserId cashierId)
{
add(
POSCashJournalLine.builder()
.type(POSCashJournalLineType.ofPaymentMethod(posPayment.getPaymentMethod()))
.amount(posPayment.getAmount())
.cashierId(cashierId)
.posOrderAndPaymentId(POSOrderAndPaymentId.of(posOrderId, posPayment.getLocalIdNotNull()))
.build()
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSCashJournal.java | 1 |
请完成以下Java代码 | public void setDocumentNo (String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
/** Get Document No.
@return Document sequence number of the document
*/
public String getDocumentNo ()
{
return (String)get_Value(COLUMNNAME_DocumentNo);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getDocumentNo());
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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;
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_C_InvoiceBatch.java | 1 |
请完成以下Java代码 | public class SelfNameResolverFactory extends NameResolverProvider {
/**
* The constant containing the scheme that will be used by this factory.
*/
public static final String SELF_SCHEME = "self";
private final GrpcServerProperties properties;
/**
* Creates a new SelfNameResolverFactory that uses the given properties.
*
* @param properties The properties used to resolve this server's address.
*/
public SelfNameResolverFactory(final GrpcServerProperties properties) {
this.properties = properties;
}
@Override
public NameResolver newNameResolver(final URI targetUri, final Args args) {
if (SELF_SCHEME.equals(targetUri.getScheme())) {
return new SelfNameResolver(this.properties, args);
}
return null;
}
@Override
public String getDefaultScheme() { | return SELF_SCHEME;
}
@Override
protected boolean isAvailable() {
return true;
}
@Override
protected int priority() {
return 0; // Lowest priority
}
@Override
public String toString() {
return "SelfNameResolverFactory [scheme=" + getDefaultScheme() + "]";
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\nameresolver\SelfNameResolverFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected <T> T defaultIfNotNull(T value, T defaultValue) {
if (value == null) {
return defaultValue;
}
return value;
}
public static class EngineDeploymentProperties {
/**
* Whether to use a lock when performing the auto deployment.
* If not set then the global default would be used.
*/
private Boolean useLock;
/**
* Duration to wait for the auto deployment lock before giving up.
* If not set then the global default would be used.
*/
private Duration lockWaitTime;
/**
* Whether to throw an exception if there was some kind of failure during the auto deployment.
* If not set then the global default would be used.
*/
private Boolean throwExceptionOnDeploymentFailure;
/**
* Name of the lock that should be used for the auto deployment.
* If not defined then the deployment name or the global default would be used.
*/
private String lockName;
public Boolean getUseLock() { | return useLock;
}
public void setUseLock(Boolean useLock) {
this.useLock = useLock;
}
public Duration getLockWaitTime() {
return lockWaitTime;
}
public void setLockWaitTime(Duration lockWaitTime) {
this.lockWaitTime = lockWaitTime;
}
public Boolean getThrowExceptionOnDeploymentFailure() {
return throwExceptionOnDeploymentFailure;
}
public void setThrowExceptionOnDeploymentFailure(Boolean throwExceptionOnDeploymentFailure) {
this.throwExceptionOnDeploymentFailure = throwExceptionOnDeploymentFailure;
}
public String getLockName() {
return lockName;
}
public void setLockName(String lockName) {
this.lockName = lockName;
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableAutoDeploymentProperties.java | 2 |
请完成以下Java代码 | public String toString()
{
return "PgPassEntry [host=" + host + ", port=" + port + ", dbName=" + dbName + ", user=" + user + ", password=" + password + "]";
}
public String getHost()
{
return host;
}
public String getPort()
{
return port;
} | public String getDbName()
{
return dbName;
}
public String getUser()
{
return user;
}
public String getPassword()
{
return password;
}
} // PgPassEntry | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\postgresql\PgPassEntry.java | 1 |
请完成以下Java代码 | public Optional<Language> getBPartnerLanguage(@NonNull final I_C_BPartner bpartner)
{
return bpartnerBL.getLanguage(bpartner);
}
public BPartnerPrintFormatMap getBPartnerPrintFormats(final BPartnerId bpartnerId)
{
return bpartnerBL.getPrintFormats(bpartnerId);
}
@NonNull
public DefaultPrintFormats getDefaultPrintFormats(@NonNull final ClientId clientId)
{
return defaultPrintFormatsRepository.getByClientId(clientId);
}
@NonNull
public AdProcessId getReportProcessIdByPrintFormatId(@NonNull final PrintFormatId printFormatId)
{
return getReportProcessIdByPrintFormatIdIfExists(printFormatId).get();
}
@NonNull
public ExplainedOptional<AdProcessId> getReportProcessIdByPrintFormatIdIfExists(@NonNull final PrintFormatId printFormatId)
{
final PrintFormat printFormat = printFormatRepository.getById(printFormatId);
final AdProcessId reportProcessId = printFormat.getReportProcessId();
return reportProcessId != null
? ExplainedOptional.of(reportProcessId)
: ExplainedOptional.emptyBecause("No report process defined by " + printFormat);
}
@NonNull
public I_C_DocType getDocTypeById(@NonNull final DocTypeId docTypeId)
{
return docTypeDAO.getById(docTypeId);
}
public PrintCopies getDocumentCopies( | @Nullable final I_C_DocType docType,
@Nullable final BPPrintFormatQuery bpPrintFormatQuery)
{
final BPPrintFormat bpPrintFormat = bpPrintFormatQuery == null ? null : bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery);
if(bpPrintFormat == null)
{
return getDocumentCopies(docType);
}
return bpPrintFormat.getPrintCopies();
}
private static PrintCopies getDocumentCopies(@Nullable final I_C_DocType docType)
{
return docType != null && !InterfaceWrapperHelper.isNull(docType, I_C_DocType.COLUMNNAME_DocumentCopies)
? PrintCopies.ofInt(docType.getDocumentCopies())
: PrintCopies.ONE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportAdvisorUtil.java | 1 |
请完成以下Java代码 | public void registerGlobalEventListener(
@NonNull final Topic topic,
@NonNull final IEventListener listener)
{
// Register the listener to EventBus
getEventBus(topic).subscribe(listener);
// Add the listener to our global listeners-multimap.
// Note that getEventBus(topic) creates the bus on the fly if needed **and subscribes all global listeners to it**
// Therefore we need to add this listener to the global map *after* having gotten and possibly on-the-fly-created the event bus.
if (!globalEventListeners.put(topic, listener))
{
// listener already exists => do nothing
return;
}
logger.info("Registered global listener to {}: {}", topic, listener);
}
@Override
public void addAvailableUserNotificationsTopic(@NonNull final Topic topic)
{
final boolean added = availableUserNotificationsTopic.add(topic);
logger.info("Registered user notifications topic: {} (already registered: {})", topic, !added);
}
/**
* @return set of available topics on which user can subscribe for UI notifications
*/
private Set<Topic> getAvailableUserNotificationsTopics()
{
return ImmutableSet.copyOf(availableUserNotificationsTopic);
}
@Override | public void registerUserNotificationsListener(@NonNull final IEventListener listener)
{
getAvailableUserNotificationsTopics()
.stream()
.map(this::getEventBus)
.forEach(eventBus -> eventBus.subscribe(listener));
}
@Override
public void unregisterUserNotificationsListener(@NonNull final IEventListener listener)
{
getAvailableUserNotificationsTopics()
.stream()
.map(this::getEventBus)
.forEach(eventBus -> eventBus.unsubscribe(listener));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\EventBusFactory.java | 1 |
请完成以下Java代码 | public TaskFormData createTaskForm(TaskEntity task) {
TaskFormDataImpl taskFormData = new TaskFormDataImpl();
TaskDefinition taskDefinition = task.getTaskDefinition();
FormDefinition formDefinition = taskDefinition.getFormDefinition();
Expression formKey = formDefinition.getFormKey();
Expression camundaFormDefinitionKey = formDefinition.getCamundaFormDefinitionKey();
String camundaFormDefinitionBinding = formDefinition.getCamundaFormDefinitionBinding();
Expression camundaFormDefinitionVersion = formDefinition.getCamundaFormDefinitionVersion();
if (formKey != null) {
Object formValue = formKey.getValue(task);
if (formValue != null) {
taskFormData.setFormKey(formValue.toString());
}
} else if (camundaFormDefinitionKey != null && camundaFormDefinitionBinding != null) {
Object formRefKeyValue = camundaFormDefinitionKey.getValue(task);
if(formRefKeyValue != null) {
CamundaFormRefImpl ref = new CamundaFormRefImpl(formRefKeyValue.toString(), camundaFormDefinitionBinding);
if(camundaFormDefinitionBinding.equals(FORM_REF_BINDING_VERSION) && camundaFormDefinitionVersion != null) {
Object formRefVersionValue = camundaFormDefinitionVersion.getValue(task); | if(formRefVersionValue != null) {
ref.setVersion(Integer.parseInt((String)formRefVersionValue));
}
}
taskFormData.setCamundaFormRef(ref);
}
}
taskFormData.setDeploymentId(deploymentId);
taskFormData.setTask(task);
initializeFormProperties(taskFormData, task.getExecution());
initializeFormFields(taskFormData, task.getExecution());
return taskFormData;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\handler\DefaultTaskFormHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FormDataResponse {
protected String formKey;
protected String deploymentId;
protected String processDefinitionId;
protected String processDefinitionUrl;
protected String taskId;
protected String taskUrl;
protected List<RestFormProperty> formProperties = new ArrayList<>();
@ApiModelProperty(example = "null")
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
@ApiModelProperty(example = "2")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@ApiModelProperty(example = "3")
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@ApiModelProperty(example = "http://localhost:8182/repository/process-definition/3") | public String getProcessDefinitionUrl() {
return processDefinitionUrl;
}
public void setProcessDefinitionUrl(String processDefinitionUrl) {
this.processDefinitionUrl = processDefinitionUrl;
}
@ApiModelProperty(example = "6")
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@ApiModelProperty(example = "http://localhost:8182/runtime/task/6")
public String getTaskUrl() {
return taskUrl;
}
public void setTaskUrl(String taskUrl) {
this.taskUrl = taskUrl;
}
public List<RestFormProperty> getFormProperties() {
return formProperties;
}
public void setFormProperties(List<RestFormProperty> formProperties) {
this.formProperties = formProperties;
}
public void addFormProperty(RestFormProperty formProperty) {
formProperties.add(formProperty);
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\form\FormDataResponse.java | 2 |
请完成以下Java代码 | public static BooleanWithReason falseBecause(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters)
{
return falseBecause(TranslatableStrings.adMessage(adMessage, msgParameters));
}
public static BooleanWithReason falseBecause(@NonNull final Exception exception)
{
return falseBecause(AdempiereException.extractMessageTrl(exception));
}
public static BooleanWithReason falseIf(final boolean condition, @NonNull final String falseReason)
{
return condition ? falseBecause(falseReason) : TRUE;
}
private static ITranslatableString toTrl(@Nullable final String reasonStr)
{
if (reasonStr == null || Check.isBlank(reasonStr))
{
return TranslatableStrings.empty();
}
else
{
return TranslatableStrings.anyLanguage(reasonStr.trim());
}
}
public static final BooleanWithReason TRUE = new BooleanWithReason(true, TranslatableStrings.empty());
public static final BooleanWithReason FALSE = new BooleanWithReason(false, TranslatableStrings.empty());
private final boolean value;
@NonNull @Getter private final ITranslatableString reason;
private BooleanWithReason(
final boolean value,
@NonNull final ITranslatableString reason)
{
this.value = value;
this.reason = reason;
}
@Override
public String toString()
{
final String valueStr = String.valueOf(value);
final String reasonStr = !TranslatableStrings.isBlank(reason)
? reason.getDefaultValue()
: null;
return reasonStr != null
? valueStr + " because " + reasonStr
: valueStr;
}
public boolean toBoolean()
{
return value;
} | public boolean isTrue()
{
return value;
}
public boolean isFalse()
{
return !value;
}
public String getReasonAsString()
{
return reason.getDefaultValue();
}
public void assertTrue()
{
if (isFalse())
{
throw new AdempiereException(reason);
}
}
public BooleanWithReason and(@NonNull final Supplier<BooleanWithReason> otherSupplier)
{
return isFalse()
? this
: Check.assumeNotNull(otherSupplier.get(), "otherSupplier shall not return null");
}
public void ifTrue(@NonNull final Consumer<String> consumer)
{
if (isTrue())
{
consumer.accept(getReasonAsString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\BooleanWithReason.java | 1 |
请完成以下Java代码 | final class ProductPriceMasterDataProvider
{
private final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
private final IPriceListDAO priceListsRepo = Services.get(IPriceListDAO.class);
public void createProductPrice(@NonNull final ProductPriceCreateRequest request)
{
final BPartnerLocationId bpartnerAndLocationId = request.getBpartnerAndLocationId();
final BPartnerId bpartnerId = bpartnerAndLocationId.getBpartnerId();
final ZonedDateTime date = request.getDate();
final ProductId productId = request.getProductId();
final UomId uomId = request.getUomId();
final BigDecimal priceStd = request.getPriceStd();
final SOTrx soTrx = SOTrx.SALES;
final PricingSystemId pricingSystemId;
if (request.getPricingSystemId() != null)
{
pricingSystemId = request.getPricingSystemId();
}
else
{
// we need to retrieve within the current trx, because maybe the BPartner itself was also only just created
pricingSystemId = bpartnersRepo.retrievePricingSystemIdOrNullInTrx(bpartnerId, soTrx);
if (pricingSystemId == null)
{
throw new AdempiereException("@NotFound@ @M_PricingSystem_ID@")
.setParameter("C_BPartner_ID", bpartnerId)
.setParameter("SOTrx", soTrx);
}
}
final CountryId countryId = bpartnersRepo.getCountryIdInTrx(bpartnerAndLocationId);
final PriceListsCollection priceLists = priceListsRepo.retrievePriceListsCollectionByPricingSystemId(pricingSystemId);
final I_M_PriceList priceList = priceLists.getPriceList(countryId, soTrx).orElse(null); | if (priceList == null)
{
throw new AdempiereException("@NotFound@ @M_PriceList_ID@")
.setParameter("priceLists", priceLists)
.setParameter("countryId", countryId)
.setParameter("soTrx", soTrx);
}
final PriceListId priceListId = PriceListId.ofRepoId(priceList.getM_PriceList_ID());
final TaxCategoryId taxCategoryId = TaxCategoryId.ofRepoIdOrNull(priceList.getDefault_TaxCategory_ID());
if (taxCategoryId == null)
{
throw new AdempiereException("@NotFound@ @Default_TaxCategory_ID@ of @M_PriceList_ID@")
.setParameter("priceListId", priceListId);
}
final PriceListVersionId priceListVersionId = priceListsRepo.retrievePriceListVersionId(
priceListId,
date);
priceListsRepo.addProductPrice(AddProductPriceRequest.builder()
.priceListVersionId(priceListVersionId)
.productId(productId)
.uomId(uomId)
.priceStd(priceStd)
// .priceList(price)
// .priceLimit(price)
.taxCategoryId(taxCategoryId)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\ProductPriceMasterDataProvider.java | 1 |
请完成以下Java代码 | public <T extends RepoIdAware> T getParameterAsId(String parameterName, Class<T> type)
{
return null;
}
@Override
public boolean getParameterAsBool(final String parameterName)
{
return false;
}
@Nullable
@Override
public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue)
{
return defaultValue;
}
@Override
public Timestamp getParameterAsTimestamp(final String parameterName)
{
return null;
}
@Override
public LocalDate getParameterAsLocalDate(final String parameterName)
{
return null;
}
@Override
public ZonedDateTime getParameterAsZonedDateTime(final String parameterName)
{
return null;
}
@Nullable
@Override
public Instant getParameterAsInstant(final String parameterName) | {
return null;
}
@Override
public BigDecimal getParameterAsBigDecimal(final String paraCheckNetamttoinvoice)
{
return null;
}
/**
* Returns an empty list.
*/
@Override
public Collection<String> getParameterNames()
{
return ImmutableList.of();
}
@Override
public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType)
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\NullParams.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ConfigDataLocation getConfigDataLocation() {
return this.configDataLocation;
}
String getResourceLocation() {
return this.resourceLocation;
}
boolean isMandatoryDirectory() {
return !this.configDataLocation.isOptional() && this.directory != null;
}
@Nullable String getDirectory() {
return this.directory;
}
@Nullable String getProfile() {
return this.profile;
}
boolean isSkippable() {
return this.configDataLocation.isOptional() || this.directory != null || this.profile != null;
}
PropertySourceLoader getPropertySourceLoader() {
return this.propertySourceLoader;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false; | }
StandardConfigDataReference other = (StandardConfigDataReference) obj;
return this.resourceLocation.equals(other.resourceLocation);
}
@Override
public int hashCode() {
return this.resourceLocation.hashCode();
}
@Override
public String toString() {
return this.resourceLocation;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\StandardConfigDataReference.java | 2 |
请完成以下Java代码 | public static final class SimpleWebAuthUserImpl implements AuthUser {
private String username;
public SimpleWebAuthUserImpl(String username) {
this.username = username;
}
@Override
public boolean authTarget(String target, PrivilegeType privilegeType) {
return true;
}
@Override
public boolean isSuperUser() {
return true;
} | @Override
public String getNickName() {
return username;
}
@Override
public String getLoginName() {
return username;
}
@Override
public String getId() {
return username;
}
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\auth\SimpleWebAuthServiceImpl.java | 1 |
请完成以下Java代码 | public void addDiDiagram(DmnDiDiagram diDiagram) {
diDiagrams.add(diDiagram);
setCurrentDiDiagram(diDiagram);
}
public void addDiShape(DmnDiShape diShape) {
diShapes.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>());
diShapes.get(getCurrentDiDiagram().getId()).add(diShape);
setCurrentDiShape(diShape);
}
public void addDiEdge(DmnDiEdge diEdge) {
diEdges.computeIfAbsent(getCurrentDiDiagram().getId(), k -> new ArrayList<>());
diEdges.get(getCurrentDiDiagram().getId()).add(diEdge);
setCurrentDiEdge(diEdge);
}
public DmnDiDiagram getCurrentDiDiagram() {
return currentDiDiagram;
}
public void setCurrentDiDiagram(DmnDiDiagram currentDiDiagram) {
this.currentDiDiagram = currentDiDiagram;
}
public DmnDiShape getCurrentDiShape() {
return currentDiShape;
}
public void setCurrentDiShape(DmnDiShape currentDiShape) {
this.currentDiShape = currentDiShape;
} | public DiEdge getCurrentDiEdge() {
return currentDiEdge;
}
public void setCurrentDiEdge(DiEdge currentDiEdge) {
this.currentDiEdge = currentDiEdge;
}
public List<DmnDiDiagram> getDiDiagrams() {
return diDiagrams;
}
public List<DmnDiShape> getDiShapes(String diagramId) {
return diShapes.get(diagramId);
}
public List<DmnDiEdge> getDiEdges(String diagramId) {
return diEdges.get(diagramId);
}
} | repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\ConversionHelper.java | 1 |
请完成以下Java代码 | public int getM_HU_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Attribute_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_Value (COLUMNNAME_M_HU_ID, null);
else
set_Value (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_PI_Attribute_ID (final int M_HU_PI_Attribute_ID)
{
if (M_HU_PI_Attribute_ID < 1)
set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_HU_PI_Attribute_ID, M_HU_PI_Attribute_ID);
}
@Override
public int getM_HU_PI_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Attribute_ID);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setValueDate (final @Nullable java.sql.Timestamp ValueDate)
{
set_Value (COLUMNNAME_ValueDate, ValueDate);
}
@Override
public java.sql.Timestamp getValueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValueDate);
}
@Override
public void setValueDateInitial (final @Nullable java.sql.Timestamp ValueDateInitial)
{
set_Value (COLUMNNAME_ValueDateInitial, ValueDateInitial); | }
@Override
public java.sql.Timestamp getValueDateInitial()
{
return get_ValueAsTimestamp(COLUMNNAME_ValueDateInitial);
}
@Override
public void setValueInitial (final @Nullable java.lang.String ValueInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueInitial, ValueInitial);
}
@Override
public java.lang.String getValueInitial()
{
return get_ValueAsString(COLUMNNAME_ValueInitial);
}
@Override
public void setValueNumber (final @Nullable BigDecimal ValueNumber)
{
set_Value (COLUMNNAME_ValueNumber, ValueNumber);
}
@Override
public BigDecimal getValueNumber()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumber);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValueNumberInitial (final @Nullable BigDecimal ValueNumberInitial)
{
set_ValueNoCheck (COLUMNNAME_ValueNumberInitial, ValueNumberInitial);
}
@Override
public BigDecimal getValueNumberInitial()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueNumberInitial);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Attribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Job vtollJob(JobBuilderFactory jobBuilderFactory, @Qualifier("vtollStep1") Step s1) {
return jobBuilderFactory.get("vtollJob")
.incrementer(new RunIdIncrementer())
.flow(s1)//为Job指定Step
.end()
.listener(new MyJobListener())//绑定监听器csvJobListener
.build();
}
/**
* step步骤,包含ItemReader,ItemProcessor和ItemWriter
*
* @param stepBuilderFactory
* @param reader
* @param writer
* @param processor
* @return
*/
@Bean(name = "vtollStep1")
public Step vtollStep1(StepBuilderFactory stepBuilderFactory,
@Qualifier("vtollReader") ItemReader<BudgetVtoll> reader,
@Qualifier("vtollWriter") ItemWriter<BudgetVtoll> writer,
@Qualifier("vtollProcessor") ItemProcessor<BudgetVtoll, BudgetVtoll> processor) {
return stepBuilderFactory
.get("vtollStep1")
.<BudgetVtoll, BudgetVtoll>chunk(5000)//批处理每次提交5000条数据
.reader(reader)//给step绑定reader
.processor(processor)//给step绑定processor
.writer(writer)//给step绑定writer
.faultTolerant()
.retry(Exception.class) // 重试
.noRetry(ParseException.class)
.retryLimit(1) //每条记录重试一次 | .skip(Exception.class)
.skipLimit(200) //一共允许跳过200次异常
// .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好
// .throttleLimit(10) //并发任务数为 10,默认为4
.build();
}
@Bean
public Validator<BudgetVtoll> csvBeanValidator() {
return new MyBeanValidator<>();
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtollConfig.java | 2 |
请完成以下Java代码 | public final class ElementResource implements Resource
{
public static ElementResource of(final String tableName, final int elementId)
{
return new ElementResource(tableName, elementId);
}
@Getter
private final String elementTableName;
private final String elementTableNameUC;
@Getter
private final int elementId;
private ElementResource(@NonNull final String elementTableName, final int elementId) | {
Check.assumeNotEmpty(elementTableName, "elementTableName not empty");
Check.assume(elementId > 0, "elementId > 0");
this.elementTableName = elementTableName.trim();
this.elementTableNameUC = this.elementTableName.toUpperCase();
this.elementId = elementId;
}
@Override
public String toString()
{
return elementTableName + "-" + elementId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementResource.java | 1 |
请完成以下Java代码 | public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
public String getCredential() {
return credential;
}
public void setCredential(String credential) {
this.credential = credential;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName; | }
public String getProxyEndpoint() {
return proxyEndpoint;
}
public void setProxyEndpoint(String proxyEndpoint) {
this.proxyEndpoint = proxyEndpoint;
}
public String getLocalFileBaseDirectory() {
return localFileBaseDirectory;
}
public void setLocalFileBaseDirectory(String localFileBaseDirectory) {
this.localFileBaseDirectory = localFileBaseDirectory;
}
} | repos\tutorials-master\aws-modules\s3proxy\src\main\java\com\baeldung\s3proxy\StorageProperties.java | 1 |
请完成以下Java代码 | public static int getTotalBooks() {
return totalBooks;
}
public static void printLibraryDetails(Library library) {
LOGGER.info("Library Name: " + library.name);
LOGGER.info("Number of Books: " + library.books);
}
public static String getLibraryInformation(Library library) {
return library.getName() + " has " + library.getBooks() + " books.";
}
public static synchronized void addBooks(int count) {
totalBooks += count;
}
public String getName() {
return name;
}
public int getBooks() {
return books;
}
public static class LibraryStatistics {
public static int getAverageBooks(Library[] libraries) {
int total = 0; | for (Library library : libraries) {
total += library.books;
}
return libraries.length > 0 ? total / libraries.length : 0;
}
}
public static class Book {
private final String title;
private final String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public void displayBookDetails() {
LOGGER.info("Book Title: " + title);
LOGGER.info("Book Author: " + author);
}
}
public record BookRecord(String title, String author) {
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers\src\main\java\com\baeldung\statickeyword\Library.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DDOrderCandidateEnqueueService
{
private final ILockManager lockManager = Services.get(ILockManager.class);
private final IWorkPackageQueueFactory workPackageQueueFactory = Services.get(IWorkPackageQueueFactory.class);
private final DDOrderCandidateRepository ddOrderCandidateRepository;
private static final String WP_PARAM_request = "request";
private static final String LOCK_OWNER_PREFIX = "DDOrderCandidateEnqueueService";
public void enqueueId(@NonNull final DDOrderCandidateId id)
{
enqueueIds(ImmutableSet.of(id));
}
public void enqueueIds(@NonNull final Collection<DDOrderCandidateId> ids)
{
if (ids.isEmpty())
{
return;
}
final PInstanceId selectionId = ddOrderCandidateRepository.createSelection(ids);
enqueueSelection(DDOrderCandidateEnqueueRequest.ofSelectionId(selectionId));
}
public void enqueueSelection(@NonNull final PInstanceId selectionId)
{
enqueueSelection(DDOrderCandidateEnqueueRequest.ofSelectionId(selectionId));
}
public void enqueueSelection(@NonNull final DDOrderCandidateEnqueueRequest request)
{
getQueue().newWorkPackage()
.parameter(WP_PARAM_request, toJsonString(request))
.setElementsLocker(toWorkPackageElementsLocker(request))
.bindToThreadInheritedTrx()
.buildAndEnqueue();
}
private IWorkPackageQueue getQueue()
{
return workPackageQueueFactory.getQueueForEnqueuing(Env.getCtx(), GenerateDDOrderFromDDOrderCandidate.class);
}
private ILockCommand toWorkPackageElementsLocker(final @NonNull DDOrderCandidateEnqueueRequest request)
{
final PInstanceId selectionId = request.getSelectionId();
final LockOwner lockOwner = LockOwner.newOwner(LOCK_OWNER_PREFIX, selectionId.getRepoId());
return lockManager
.lock()
.setOwner(lockOwner)
.setAutoCleanup(false)
.setFailIfAlreadyLocked(true)
.setRecordsBySelection(I_DD_Order_Candidate.class, selectionId); | }
private static String toJsonString(@NonNull final DDOrderCandidateEnqueueRequest request)
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(request);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Cannot convert to json: " + request, e);
}
}
public static DDOrderCandidateEnqueueRequest extractRequest(@NonNull final IParams params)
{
final String jsonString = params.getParameterAsString(WP_PARAM_request);
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(jsonString, DDOrderCandidateEnqueueRequest.class);
}
catch (final JsonProcessingException e)
{
throw new AdempiereException("Cannot read json: " + jsonString, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\async\DDOrderCandidateEnqueueService.java | 2 |
请完成以下Java代码 | public void setValue(Object value) {
m_value = value;
boolean sel = false;
if (value == null)
sel = false;
else if (value.toString().equals("Y"))
sel = true;
else if (value.toString().equals("N"))
sel = false;
else if (value instanceof Boolean)
sel = ((Boolean) value).booleanValue();
else {
try {
sel = Boolean.getBoolean(value.toString());
} catch (Exception e) {
}
}
this.setSelected(sel);
} // setValue
/**
* Return Editor value
*
* @return current value as String or Boolean
*/
@Override
public Object getValue() {
if (m_value instanceof String)
return super.isSelected() ? "Y" : "N";
return new Boolean(isSelected());
} // getValue
/**
* Return Display Value
*
* @return displayed String value
*/
@Override
public String getDisplay() {
if (m_value instanceof String)
return super.isSelected() ? "Y" : "N";
return Boolean.toString(super.isSelected());
} // getDisplay
/**
* Set Text
*
* @param mnemonicLabel
* text
*/
@Override
public void setText(String mnemonicLabel) {
super.setText(createMnemonic(mnemonicLabel));
} // setText
/**
* Create Mnemonics of text containing "&". Based on MS notation of &Help => | * H is Mnemonics Creates ALT_
*
* @param text
* test with Mnemonics
* @return text w/o &
*/
private String createMnemonic(String text) {
if (text == null)
return text;
int pos = text.indexOf('&');
if (pos != -1) // We have a nemonic
{
char ch = text.charAt(pos + 1);
if (ch != ' ') // &_ - is the & character
{
setMnemonic(ch);
return text.substring(0, pos) + text.substring(pos + 1);
}
}
return text;
} // createMnemonic
/**
* Overrides the JCheckBox.setMnemonic() method, setting modifier keys to
* CTRL+SHIFT.
*
* @param mnemonic
* The mnemonic character code.
*/
@Override
public void setMnemonic(int mnemonic) {
super.setMnemonic(mnemonic);
InputMap map = SwingUtilities.getUIInputMap(this,
JComponent.WHEN_IN_FOCUSED_WINDOW);
if (map == null) {
map = new ComponentInputMapUIResource(this);
SwingUtilities.replaceUIInputMap(this,
JComponent.WHEN_IN_FOCUSED_WINDOW, map);
}
map.clear();
String className = this.getClass().getName();
int mask = InputEvent.ALT_MASK; // Default Buttons
if (this instanceof JCheckBox // In Tab
|| className.indexOf("VButton") != -1)
mask = InputEvent.SHIFT_MASK + InputEvent.CTRL_MASK;
map.put(KeyStroke.getKeyStroke(mnemonic, mask, false), "pressed");
map.put(KeyStroke.getKeyStroke(mnemonic, mask, true), "released");
map.put(KeyStroke.getKeyStroke(mnemonic, 0, true), "released");
setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, map);
} // setMnemonic
} // CCheckBox | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CCheckBox.java | 1 |
请完成以下Java代码 | public class MDepreciationWorkfile extends X_A_Depreciation_Workfile
{
/**
*
*/
private static final long serialVersionUID = 9075233803956474274L;
/**
* Default Constructor X_A_Depreciation_Workfile
* @param ctx context
* @param M_InventoryLine_ID line
*/
public MDepreciationWorkfile (Properties ctx, int A_Depreciation_Workfile_ID, String trxName)
{
super (ctx,A_Depreciation_Workfile_ID, trxName);
if (A_Depreciation_Workfile_ID == 0)
{
//
}
} // MAssetAddition
/**
* Load Constructor
* @param ctx context
* @param rs result set
*/
public MDepreciationWorkfile (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MInventoryLine
protected boolean afterSave (boolean newRecord)
{
log.info("beforeSave");
//int p_A_Asset_ID = 0;
int p_wkasset_ID = 0;
//p_A_Asset_ID = getA_Asset_ID();
p_wkasset_ID = getA_Depreciation_Workfile_ID();
StringBuffer sqlB = new StringBuffer ("UPDATE A_Depreciation_Workfile "
+ "SET Processing = 'Y'"
+ " WHERE A_Depreciation_Workfile_ID = " + p_wkasset_ID );
int no = DB.executeUpdateAndSaveErrorOnFail(sqlB.toString(), null);
if (no == -1)
log.info("Update to Deprecaition Workfile failed");
return true;
}
/**
* after Save
* @param newRecord new
* @return true
*/ | protected boolean beforeSave (boolean newRecord)
{
log.info("beforeSave");
int p_A_Asset_ID = 0;
//int p_wkasset_ID = 0;
p_A_Asset_ID = getA_Asset_ID();
//p_wkasset_ID = getA_Depreciation_Workfile_ID();
log.info("afterSave");
X_A_Asset asset = new X_A_Asset (getCtx(), p_A_Asset_ID, null);
asset.setA_QTY_Current(getA_QTY_Current());
asset.setA_QTY_Original(getA_QTY_Current());
asset.save();
if (getA_Accumulated_Depr().equals(null))
setA_Accumulated_Depr(new BigDecimal(0.0));
if (new BigDecimal(getA_Period_Posted()).equals(null))
setA_Period_Posted(0);
MAssetChange change = new MAssetChange (getCtx(), 0,null);
log.info("0");
String sql2 = "SELECT COUNT(*) FROM A_Depreciation_Workfile WHERE A_Asset_ID=? AND PostingType = ?";
if (DB.getSQLValue(null, sql2, p_A_Asset_ID,getPostingType())!= 0)
{
change.setA_Asset_ID(p_A_Asset_ID);
change.setChangeType("BAL");
MRefList RefList = new MRefList (getCtx(), 0, null);
change.setTextDetails(RefList.getListDescription (getCtx(),"A_Update_Type" , "BAL"));
change.setPostingType(getPostingType());
change.setAssetValueAmt(getA_Asset_Cost());
change.setA_QTY_Current(getA_QTY_Current());
change.setA_QTY_Original(getA_QTY_Current());
change.setAssetAccumDepreciationAmt(getA_Accumulated_Depr());
change.save();
}
return true;
} // beforeSave
} // MAssetAddition | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MDepreciationWorkfile.java | 1 |
请完成以下Java代码 | public I_C_UOM getC_UOM()
{
return uomDAO.getById(getUomId());
}
@NonNull
public UomId getUomId()
{
return UomId.ofRepoId(ppOrder.getC_UOM_ID());
}
@Override
public ProductionMaterialType getType()
{
return ProductionMaterialType.PRODUCED;
}
@Override
public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw)
{
ppOrder.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw);
}
@Override
public BigDecimal getQM_QtyDeliveredPercOfRaw()
{
return ppOrder.getQM_QtyDeliveredPercOfRaw();
}
@Override
public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg)
{
ppOrder.setQM_QtyDeliveredAvg(qtyDeliveredAvg);
}
@Override
public BigDecimal getQM_QtyDeliveredAvg()
{
return ppOrder.getQM_QtyDeliveredAvg();
}
@Override
public Object getModel()
{
return ppOrder;
} | @Override
public String getVariantGroup()
{
return null;
}
@Override
public BOMComponentType getComponentType()
{
return null;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
if (!_handlingUnitsInfoLoaded)
{
_handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder);
_handlingUnitsInfoLoaded = true;
}
return _handlingUnitsInfo;
}
@Override
public I_M_Product getMainComponentProduct()
{
// there is no substitute for a produced material
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java | 1 |
请完成以下Java代码 | public static ContextVariablesExpression ofLogicExpression(@NonNull final ILogicExpression expression)
{
return new ContextVariablesExpression(expression, expression.getParameterNames());
}
@NonNull
public static ContextVariablesExpression ofLookupDescriptor(@NonNull final LookupDescriptor lookupDescriptor)
{
final HashSet<String> requiredContextVariables = new HashSet<>();
if (lookupDescriptor instanceof SqlLookupDescriptor)
{
// NOTE: don't add lookupDescriptor.getDependsOnFieldNames() because that collection contains the postQueryPredicate's required params,
// which in case they are missing it's hard to determine if that's a problem or not.
// e.g. FilterWarehouseByDocTypeValidationRule requires C_DocType_ID but behaves OK/expected when the C_DocType_ID context var is missing.
final SqlLookupDescriptor sqlLookupDescriptor = (SqlLookupDescriptor)lookupDescriptor;
final GenericSqlLookupDataSourceFetcher lookupDataSourceFetcher = sqlLookupDescriptor.getLookupDataSourceFetcher();
requiredContextVariables.addAll(CtxNames.toNames(lookupDataSourceFetcher.getSqlForFetchingLookups().getParameters()));
requiredContextVariables.addAll(CtxNames.toNames(lookupDataSourceFetcher.getSqlForFetchingLookupById().getParameters()));
}
else
{
requiredContextVariables.addAll(lookupDescriptor.getDependsOnFieldNames()); | }
return new ContextVariablesExpression(lookupDescriptor, requiredContextVariables);
}
@Override
public String toString()
{
return String.valueOf(actualExpression);
}
public boolean isConstant()
{
return requiredContextVariables.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariablesExpression.java | 1 |
请完成以下Java代码 | public BooleanWithReason isStartServicePossible(
@NonNull final PCMExternalRequest pcmExternalRequest,
@NonNull final ExternalSystemParentConfigId parentId,
@NonNull final IMsgBL msgBL)
{
if (!pcmExternalRequest.isStartService())
{
return BooleanWithReason.TRUE;
}
final ImmutableMap<PCMExternalRequest, String> request2LookupInfo = getLookupInfoByExternalRequest();
final String targetLookupInfo = Optional.ofNullable(request2LookupInfo.get(pcmExternalRequest))
.orElseThrow(() -> new AdempiereException("Unexpected pcmExternalRequest=" + pcmExternalRequest.getCode()));
final boolean isFileLookupInfoDuplicated = CollectionUtils.hasDuplicatesForValue(request2LookupInfo.values(), targetLookupInfo);
if (isFileLookupInfoDuplicated)
{
final ITranslatableString duplicateFileLookupInfoErrorMsg = msgBL.getTranslatableMsgText(MSG_DUPLICATE_FILE_LOOKUP_DETAILS,
pcmExternalRequest.getCode(),
parentId.getRepoId());
return BooleanWithReason.falseBecause(duplicateFileLookupInfoErrorMsg);
} | return BooleanWithReason.TRUE;
}
@NonNull
private ImmutableMap<PCMExternalRequest, String> getLookupInfoByExternalRequest()
{
return ImmutableMap.of(
PCMExternalRequest.START_PRODUCT_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternProduct),
PCMExternalRequest.START_BPARTNER_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternBPartner),
PCMExternalRequest.START_WAREHOUSE_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternWarehouse),
PCMExternalRequest.START_PURCHASE_ORDER_SYNC_LOCAL_FILE, Strings.nullToEmpty(fileNamePatternPurchaseOrder)
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\pcm\source\PCMContentSourceLocalFile.java | 1 |
请完成以下Java代码 | public final class DeviceConfigParam implements IDeviceConfigParam
{
private final String systemName;
private final String userFriendlyName;
private final String defaultValue;
private String value;
public DeviceConfigParam(final String systemName, final String userFriendlyName, final String defaultValue)
{
this.systemName = systemName;
this.userFriendlyName = userFriendlyName;
this.defaultValue = defaultValue;
}
@Override
public String getSystemName()
{
return systemName;
}
@Override
public String getUserFriendlyName()
{
return userFriendlyName;
}
@Override
public String getDefaultValue()
{
return defaultValue;
}
@Override
public String getValue()
{ | return value;
}
@Override
public void setValue(String value)
{
this.value = value;
}
@Override
public String toString()
{
return "DeviceConfigParamPojo [systemName=" + systemName + ", userFriendlyName=" + userFriendlyName + ", defaultValue=" + defaultValue + ", value=" + value + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\util\DeviceConfigParam.java | 1 |
请完成以下Java代码 | public <T> T mapInternalToJava(Object parameter, String typeIdentifier, DeserializationTypeValidator validator) {
try {
//sometimes the class identifier is at once a fully qualified class name
final Class<?> aClass = Class.forName(typeIdentifier, true, Thread.currentThread().getContextClassLoader());
return (T) mapInternalToJava(parameter, aClass, validator);
} catch (ClassNotFoundException e) {
JavaType javaType = format.constructJavaTypeFromCanonicalString(typeIdentifier);
T result = mapInternalToJava(parameter, javaType, validator);
return result;
}
}
public <C> C mapInternalToJava(Object parameter, JavaType type) {
return mapInternalToJava(parameter, type, null);
}
public <C> C mapInternalToJava(Object parameter, JavaType type, DeserializationTypeValidator validator) {
JsonNode jsonNode = (JsonNode) parameter;
try {
validateType(type, validator);
ObjectMapper mapper = format.getObjectMapper();
return mapper.readValue(mapper.treeAsTokens(jsonNode), type);
} catch (IOException | SpinRuntimeException e) {
throw LOG.unableToDeserialize(jsonNode, type, e);
}
}
/**
* Validate the type with the help of the validator.<br>
* Note: when adjusting this method, please also consider adjusting
* the {@code AbstractVariablesResource#validateType} in the REST API
*/
protected void validateType(JavaType type, DeserializationTypeValidator validator) { | if (validator != null) {
List<String> invalidTypes = new ArrayList<>();
validateType(type, validator, invalidTypes);
if (!invalidTypes.isEmpty()) {
throw new SpinRuntimeException("The following classes are not whitelisted for deserialization: " + invalidTypes);
}
}
}
protected void validateType(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) {
if (!type.isPrimitive()) {
if (!type.isArrayType()) {
validateTypeInternal(type, validator, invalidTypes);
}
if (type.isMapLikeType()) {
validateType(type.getKeyType(), validator, invalidTypes);
}
if (type.isContainerType() || type.hasContentType()) {
validateType(type.getContentType(), validator, invalidTypes);
}
}
}
protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List<String> invalidTypes) {
String className = type.getRawClass().getName();
if (!validator.validate(className) && !invalidTypes.contains(className)) {
invalidTypes.add(className);
}
}
} | repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormatMapper.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getMigrationDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_MigrationDate);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{ | set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Titel.
@param Title
Name this entity is referred to as
*/
@Override
public void setTitle (java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class PricingInfo
{
@NonNull PriceListVersionId priceListVersionId;
@NonNull CurrencyId currencyId;
}
private PricingInfo getPricingInfo(
@NonNull final BPartnerLocationAndCaptureId bpartnerAndLocationId,
@NonNull final ZonedDateTime customerReturnDate)
{
final PricingSystemId pricingSystemId = bpartnerDAO.retrievePricingSystemIdOrNull(bpartnerAndLocationId.getBpartnerId(), SOTrx.SALES);
if (pricingSystemId == null)
{
throw new AdempiereException("@NotFound@ @M_PricingSystem_ID@")
.setParameter("C_BPartner_ID", bpartnerDAO.getBPartnerNameById(bpartnerAndLocationId.getBpartnerId()))
.setParameter("SOTrx", SOTrx.SALES);
}
final PriceListId priceListId = priceListDAO.retrievePriceListIdByPricingSyst(pricingSystemId, bpartnerAndLocationId, SOTrx.SALES);
if (priceListId == null)
{ | throw new PriceListNotFoundException(
priceListDAO.getPricingSystemName(pricingSystemId),
SOTrx.SALES);
}
final I_M_PriceList_Version priceListVersion = priceListDAO.retrievePriceListVersionOrNull(priceListId, customerReturnDate, null);
if (priceListVersion == null)
{
throw new PriceListVersionNotFoundException(priceListId, customerReturnDate);
}
return PricingInfo.builder()
.priceListVersionId(PriceListVersionId.ofRepoId(priceListVersion.getM_PriceList_Version_ID()))
.currencyId(priceListDAO.getCurrencyId(priceListId))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\CreateServiceRepairProjectCommand.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getUsernameFromToken(String token) {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
private Claims getAllClaimsFromToken(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
final Date expiration = getExpirationDateFromToken(token);
return expiration.before(new Date());
}
private Boolean ignoreTokenExpiration(String token) { | // here you specify tokens, for that the expiration is ignored
return false;
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return doGenerateToken(claims, userDetails.getUsername());
}
private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();
}
public Boolean canTokenBeRefreshed(String token) {
return (!isTokenExpired(token) || ignoreTokenExpiration(token));
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = getUsernameFromToken(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
} | repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-boot-jwt-without-JPA\spring-boot-jwt\src\main\java\com\javainuse\config\JwtTokenUtil.java | 2 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausgelagerte Menge.
@param QtyIssued Ausgelagerte Menge */
@Override
public void setQtyIssued (java.math.BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
}
/** Get Ausgelagerte Menge.
@return Ausgelagerte Menge */
@Override
public java.math.BigDecimal getQtyIssued ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued);
if (bd == null)
return Env.ZERO;
return bd; | }
/** Set Empfangene Menge.
@param QtyReceived Empfangene Menge */
@Override
public void setQtyReceived (java.math.BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report_Line.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure()
{
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
//@formatter:off
from(direct(REST_API_AUTHENTICATE_TOKEN))
.routeId(REST_API_AUTHENTICATE_TOKEN)
.streamCache("true")
.log("Route invoked!")
.process(this::processorRegisterRoute)
.end();
from(direct(REST_API_EXPIRE_TOKEN))
.routeId(REST_API_EXPIRE_TOKEN)
.streamCache("true")
.log("Route invoked!")
.process(this::processorExpireRoute)
.end();
//@formatter:on
}
public void processorRegisterRoute(@NotNull final Exchange exchange)
{
final JsonAuthenticateRequest request = exchange.getIn().getBody(JsonAuthenticateRequest.class);
final SimpleGrantedAuthority authority = new SimpleGrantedAuthority(request.getGrantedAuthority());
tokenService.store(request.getAuthKey(), ImmutableList.of(authority), getTokenCredentials(request));
}
public void processorExpireRoute(@NotNull final Exchange exchange) | {
final JsonAuthenticateRequest request = exchange.getIn().getBody(JsonAuthenticateRequest.class);
tokenService.expiryToken(request.getAuthKey());
final int numberOfAuthenticatedTokens = tokenService.getNumberOfAuthenticatedTokens(request.getGrantedAuthority());
exchange.getIn().setBody(JsonExpireTokenResponse.builder()
.numberOfAuthenticatedTokens(numberOfAuthenticatedTokens)
.build());
}
@NotNull
private TokenCredentials getTokenCredentials(@NotNull final JsonAuthenticateRequest request)
{
return TokenCredentials.builder()
.pInstance(request.getPInstance())
.auditTrailEndpoint(request.getAuditTrailEndpoint())
.externalSystemValue(request.getExternalSystemValue())
.orgCode(request.getOrgCode())
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\RestAPIAuthenticateRoute.java | 2 |
请完成以下Java代码 | public class DunningValidator implements ModelValidator
{
private int adClientId = -1;
@Override
public void initialize(ModelValidationEngine engine, MClient client)
{
if (client != null)
{
adClientId = client.getAD_Client_ID();
}
Check.assume(Services.isAutodetectServices(), "We work with activated service auto detection");
engine.addModelValidator(new C_Dunning(), client);
engine.addModelValidator(new C_DunningLevel(), client);
engine.addModelValidator(new C_Dunning_Candidate(), client);
engine.addModelValidator(new C_DunningDoc(), client);
engine.addModelValidator(new C_DunningDoc_Line_Source(), client);
// 03405 registering the default dunning candidate producer
Services.get(de.metas.dunning.api.IDunningBL.class)
.getDunningConfig()
.getDunningCandidateProducerFactory()
.registerDunningCandidateProducer(de.metas.dunning.api.impl.DefaultDunningCandidateProducer.class);
//
// Register dunning modules
engine.addModelValidator(new InvoiceDunningValidator(), client); // invoice
Services.get(IPrintingQueueBL.class).registerHandler(DunningPrintingQueueHandler.instance);
}
@Override
public int getAD_Client_ID()
{
return adClientId;
} | @Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
return null;
}
@Override
public String modelChange(PO po, int type)
{
return null;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\modelvalidator\DunningValidator.java | 1 |
请完成以下Java代码 | public int hashCode(Integer[] x) {
return Arrays.hashCode(x);
}
@Override
public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Array array = rs.getArray(position);
return array != null ? (Integer[]) array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException {
if (st != null) {
if (value != null) {
Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value);
st.setArray(index, array);
} else {
st.setNull(index, Types.ARRAY);
}
}
}
@Override
public Integer[] deepCopy(Integer[] value) {
return value != null ? Arrays.copyOf(value, value.length) : null;
} | @Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Integer[] value) {
return value;
}
@Override
public Integer[] assemble(Serializable cached, Object owner) {
return (Integer[]) cached;
}
@Override
public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) {
return detached;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\hibernate\arraymapping\CustomIntegerArrayType.java | 1 |
请完成以下Java代码 | public boolean isApplicable(@NonNull final Evaluatee context, @NonNull final DocumentSequenceInfo docSeqInfo)
{
final String poReference = getPOReferenceOrNull(context);
final boolean result = Check.isNotBlank(poReference);
logger.debug("isApplicable - Given evaluatee-context contains {}={}; -> returning {}; context={}", PARAM_POReference, poReference, result, context);
return result;
}
/** @return the given {@code context}'s {@code POReference} value. */
@Override
public String provideSequenceNo(@NonNull final Evaluatee context, @NonNull final DocumentSequenceInfo docSeqInfo, final String autoIncrementedSeqNumber)
{
final String poReference = getPOReferenceOrNull(context);
Check.assumeNotNull(poReference, "The given context needs to have a non-empty POreference value; context={}", context);
final String poReferenceResult;
if (Check.isNotBlank(autoIncrementedSeqNumber))
{
poReferenceResult = poReference + "-" + autoIncrementedSeqNumber;
} | else {
poReferenceResult = poReference;
}
logger.debug("provideSequenceNo - returning {};", poReferenceResult);
return poReferenceResult;
}
private static String getPOReferenceOrNull(@NonNull final Evaluatee context)
{
String poReference = context.get_ValueAsString(PARAM_POReference);
if (poReference == null)
{
return null;
}
poReference = poReference.trim();
return !poReference.isEmpty() ? poReference : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequenceno\POReferenceAsSequenceNoProvider.java | 1 |
请完成以下Java代码 | public byte[] getEncodedValue() {
return this.value.toByteArray();
}
@Override
public ExtendedResponse createExtendedResponse(String id, byte[] berValue, int offset, int length) {
return null;
}
/**
* Only minimal support for <a target="_blank" href=
* "https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf"> BER
* encoding </a>; just what is necessary for the Password Modify request.
*
*/
private void berEncode(byte type, byte[] src, ByteArrayOutputStream dest) {
int length = src.length;
dest.write(type);
if (length < 128) {
dest.write(length);
}
else if ((length & 0x0000_00FF) == length) {
dest.write((byte) 0x81);
dest.write((byte) (length & 0xFF));
}
else if ((length & 0x0000_FFFF) == length) {
dest.write((byte) 0x82);
dest.write((byte) ((length >> 8) & 0xFF));
dest.write((byte) (length & 0xFF));
}
else if ((length & 0x00FF_FFFF) == length) { | dest.write((byte) 0x83);
dest.write((byte) ((length >> 16) & 0xFF));
dest.write((byte) ((length >> 8) & 0xFF));
dest.write((byte) (length & 0xFF));
}
else {
dest.write((byte) 0x84);
dest.write((byte) ((length >> 24) & 0xFF));
dest.write((byte) ((length >> 16) & 0xFF));
dest.write((byte) ((length >> 8) & 0xFF));
dest.write((byte) (length & 0xFF));
}
try {
dest.write(src);
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to BER encode provided value of type: " + type);
}
}
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HistogramFlavor getHistogramFlavor() {
return this.histogramFlavor;
}
public void setHistogramFlavor(HistogramFlavor histogramFlavor) {
this.histogramFlavor = histogramFlavor;
}
public int getMaxScale() {
return this.maxScale;
}
public void setMaxScale(int maxScale) {
this.maxScale = maxScale;
}
public int getMaxBucketCount() {
return this.maxBucketCount;
}
public void setMaxBucketCount(int maxBucketCount) {
this.maxBucketCount = maxBucketCount;
}
public TimeUnit getBaseTimeUnit() {
return this.baseTimeUnit;
}
public void setBaseTimeUnit(TimeUnit baseTimeUnit) {
this.baseTimeUnit = baseTimeUnit;
}
public Map<String, Meter> getMeter() {
return this.meter;
}
/**
* Per-meter settings.
*/
public static class Meter {
/**
* Maximum number of buckets to be used for exponential histograms, if configured.
* This has no effect on explicit bucket histograms.
*/
private @Nullable Integer maxBucketCount; | /**
* Histogram type when histogram publishing is enabled.
*/
private @Nullable HistogramFlavor histogramFlavor;
public @Nullable Integer getMaxBucketCount() {
return this.maxBucketCount;
}
public void setMaxBucketCount(@Nullable Integer maxBucketCount) {
this.maxBucketCount = maxBucketCount;
}
public @Nullable HistogramFlavor getHistogramFlavor() {
return this.histogramFlavor;
}
public void setHistogramFlavor(@Nullable HistogramFlavor histogramFlavor) {
this.histogramFlavor = histogramFlavor;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsProperties.java | 2 |
请完成以下Java代码 | public String getId()
{
return id;
}
@Override
public Date getDate()
{
return date;
}
@Override
public ITableRecordReference getRecord()
{
return record;
}
public static final class Builder
{
private String id;
private String name;
private Date date;
private ITableRecordReference record;
private IPaymentBatchProvider paymentBatchProvider;
private Builder()
{
super();
}
public PaymentBatch build()
{
return new PaymentBatch(this);
}
public Builder setId(final String id)
{
this.id = id;
return this;
}
private String getId()
{
if (id != null)
{
return id;
}
if (record != null)
{
return record.getTableName() + "#" + record.getRecord_ID();
}
throw new IllegalStateException("id is null");
}
public Builder setName(final String name)
{ | this.name = name;
return this;
}
private String getName()
{
if (name != null)
{
return name;
}
if (record != null)
{
return Services.get(IMsgBL.class).translate(Env.getCtx(), record.getTableName()) + " #" + record.getRecord_ID();
}
return "";
}
public Builder setDate(final Date date)
{
this.date = date;
return this;
}
private Date getDate()
{
if (date == null)
{
return null;
}
return (Date)date.clone();
}
public Builder setRecord(final Object record)
{
this.record = TableRecordReference.of(record);
return this;
}
private ITableRecordReference getRecord()
{
return record;
}
public Builder setPaymentBatchProvider(IPaymentBatchProvider paymentBatchProvider)
{
this.paymentBatchProvider = paymentBatchProvider;
return this;
}
private IPaymentBatchProvider getPaymentBatchProvider()
{
return paymentBatchProvider;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\bankstatement\match\spi\PaymentBatch.java | 1 |
请完成以下Java代码 | public static Optional<Path> findNotExistingFile(
@NonNull final Path directory,
@NonNull final String desiredFilename,
final int tries)
{
final String fileBaseNameInitial = getFileBaseName(desiredFilename);
final String ext = StringUtils.trimBlankToNull(getFileExtension(desiredFilename));
Path file = directory.resolve(desiredFilename);
for (int i = 1; Files.exists(file) && i <= tries - 1; i++)
{
final String newFilename = fileBaseNameInitial
+ "_" + (i + 1)
+ (ext != null ? "." + ext : "");
file = directory.resolve(newFilename);
}
return !Files.exists(file) ? Optional.of(file) : Optional.empty();
}
public static File zip(@NonNull final List<File> files) throws IOException
{
final File zipFile = File.createTempFile("ZIP", ".zip");
zipFile.deleteOnExit();
try (final FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
final ZipOutputStream zip = new ZipOutputStream(fileOutputStream))
{
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(Deflater.BEST_COMPRESSION);
for (final File file : files)
{
addToZipFile(file, zip);
} | }
return zipFile;
}
private static void addToZipFile(@NonNull final File file, @NonNull final ZipOutputStream zos) throws IOException
{
try (final FileInputStream fis = new FileInputStream(file))
{
final ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0)
{
zos.write(bytes, 0, length);
}
zos.closeEntry();
}
}
/**
* Java 8 implemention of Files.writeString
*/
public static void writeString(final Path path, final String content, final Charset charset, final OpenOption... options) throws IOException
{
final byte[] bytes = content.getBytes(charset);
Files.write(path, bytes, options);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\FileUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void onApplicationEvent(ApplicationReadyEvent event) {
try {
long startTime = System.currentTimeMillis(); // 记录开始时间
log.info(" Init Code Generate Template [ 检测如果是JAR启动,Copy模板到config目录 ] ");
this.initJarConfigCodeGeneratorTemplate();
long endTime = System.currentTimeMillis(); // 记录结束时间
log.info(" Init Code Generate Template completed in " + (endTime - startTime) + " ms"); // 计算并记录耗时
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ::Jar包启动模式下::
* 初始化代码生成器模板文件
*/
private void initJarConfigCodeGeneratorTemplate() throws Exception {
//1.获取jar同级下的config路径
String configPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:jeecg/code-template-online/**/*");
for (Resource re : resources) {
URL url = re.getURL(); | String filepath = url.getPath();
//System.out.println("native url= " + filepath);
filepath = java.net.URLDecoder.decode(filepath, "utf-8");
//System.out.println("decode url= " + filepath);
//2.在config下,创建jeecg/code-template-online/*模板
String createFilePath = configPath + filepath.substring(filepath.indexOf("jeecg/code-template-online"));
// 非jar模式不生成模板
// 不生成目录,只生成具体模板文件
if ((!filepath.contains(".jar!/BOOT-INF/lib/") && !filepath.contains(".jar/!BOOT-INF/lib/")) || !createFilePath.contains(".")) {
continue;
}
if (!FileUtil.exist(createFilePath)) {
log.info("create file codeTemplate = " + createFilePath);
FileUtil.writeString(IOUtils.toString(url, StandardCharsets.UTF_8), createFilePath, "UTF-8");
}
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\config\init\CodeTemplateInitListener.java | 2 |
请完成以下Java代码 | public void deleteLinesByRevaluationId(@NonNull final CostRevaluationId costRevaluationId)
{
queryBL.createQueryBuilder(I_M_CostRevaluationLine.class)
.addEqualsFilter(I_M_CostRevaluationLine.COLUMNNAME_M_CostRevaluation_ID, costRevaluationId)
.create()
.delete();
}
public void deleteDetailsByRevaluationId(@NonNull final CostRevaluationId costRevaluationId)
{
queryBL.createQueryBuilder(I_M_CostRevaluation_Detail.class)
.addEqualsFilter(I_M_CostRevaluation_Detail.COLUMNNAME_M_CostRevaluation_ID, costRevaluationId)
.create()
.delete();
}
public void deleteDetailsByLineId(@NonNull final CostRevaluationLineId lineId)
{
deleteDetailsByLineIds(ImmutableSet.of(lineId));
}
public void deleteDetailsByLineIds(@NonNull final Collection<CostRevaluationLineId> lineIds)
{
if (lineIds.isEmpty())
{
return;
} | queryBL.createQueryBuilder(I_M_CostRevaluation_Detail.class)
.addInArrayFilter(I_M_CostRevaluation_Detail.COLUMNNAME_M_CostRevaluationLine_ID, lineIds)
.create()
.delete();
}
public void save(@NonNull final CostRevaluationLine line)
{
final I_M_CostRevaluationLine record = InterfaceWrapperHelper.load(line.getId(), I_M_CostRevaluationLine.class);
record.setIsRevaluated(line.isRevaluated());
record.setDeltaAmt(line.getDeltaAmountToBook().toBigDecimal());
InterfaceWrapperHelper.save(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\CostRevaluationRepository.java | 1 |
请完成以下Java代码 | public int getPromotionCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionCounter);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usage Limit.
@param PromotionUsageLimit
Maximum usage limit
*/
public void setPromotionUsageLimit (int PromotionUsageLimit)
{
set_Value (COLUMNNAME_PromotionUsageLimit, Integer.valueOf(PromotionUsageLimit));
}
/** Get Usage Limit.
@return Maximum usage limit
*/
public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence. | @return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请完成以下Java代码 | public String createConsignment(Consignment consignment) {
try (Session session = sessionFactory.openSession()) {
consignment.setDelivered(false);
consignment.setId(UUID.randomUUID().toString());
shippingDao.save(session, consignment);
return consignment.getId();
}
}
public void addItem(String consignmentId, Item item) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> addItem(session, consignment, item));
}
}
private void addItem(Session session, Consignment consignment, Item item) {
consignment.getItems()
.add(item);
shippingDao.save(session, consignment);
}
public void checkIn(String consignmentId, Checkin checkin) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> checkIn(session, consignment, checkin));
}
} | private void checkIn(Session session, Consignment consignment, Checkin checkin) {
consignment.getCheckins().add(checkin);
consignment.getCheckins().sort(Comparator.comparing(Checkin::getTimeStamp));
if (checkin.getLocation().equals(consignment.getDestination())) {
consignment.setDelivered(true);
}
shippingDao.save(session, consignment);
}
public Consignment view(String consignmentId) {
try (Session session = sessionFactory.openSession()) {
return shippingDao.find(session, consignmentId)
.orElseGet(Consignment::new);
}
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\ShippingService.java | 1 |
请完成以下Java代码 | public class MembershipEntity implements Serializable, DbEntity {
private static final long serialVersionUID = 1L;
protected UserEntity user;
protected GroupEntity group;
/**
* To handle a MemberhipEntity in the cache, an id is necessary.
* Even though it is not going to be persisted in the database.
*/
protected String id;
public Object getPersistentState() {
// membership is not updatable
return MembershipEntity.class;
}
public String getId() {
// For the sake of Entity caching the id is necessary
return id;
}
public void setId(String id) {
// For the sake of Entity caching the id is necessary
this.id = id;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
} | public GroupEntity getGroup() {
return group;
}
public void setGroup(GroupEntity group) {
this.group = group;
}
// required for mybatis
public String getUserId(){
return user.getId();
}
// required for mybatis
public String getGroupId(){
return group.getId();
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[user=" + user
+ ", group=" + group
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MembershipEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CalculatorConfiguration {
@Bean
InlineCachingRegionConfigurer<ResultHolder, ResultHolder.ResultKey> inlineCachingForCalculatorApplicationRegionsConfigurer(
CalculatorRepository calculatorRepository) {
Predicate<String> regionBeanNamePredicate = regionBeanName ->
Arrays.asList("Factorials", "SquareRoots").contains(regionBeanName);
return new InlineCachingRegionConfigurer<>(calculatorRepository, regionBeanNamePredicate);
}
// tag::key-generator[]
@Bean
KeyGenerator resultKeyGenerator() { | return (target, method, arguments) -> {
int operand = Integer.parseInt(String.valueOf(arguments[0]));
Operator operator = "sqrt".equals(method.getName())
? Operator.SQUARE_ROOT
: Operator.FACTORIAL;
return ResultHolder.ResultKey.of(operand, operator);
};
}
// end::key-generator[]
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline\src\main\java\example\app\caching\inline\config\CalculatorConfiguration.java | 2 |
请完成以下Java代码 | public class XmlToPdfConverter {
public static void convertXMLtoPDFUsingFop(String xmlFilePath, String xsltFilePath, String pdfFilePath) throws Exception {
// Initialize FOP
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
// Specify output stream for PDF
try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(new File(pdfFilePath).toPath()))) {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
// Create Transformer from XSLT
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(new File(xsltFilePath)));
// Apply transformation
Source src = new StreamSource(new File(xmlFilePath));
Result res = new SAXResult(fop.getDefaultHandler()); | transformer.transform(src, res);
}
}
public static void convertXMLtoPDFUsingIText(String xmlFilePath, String pdfFilePath) throws Exception {
try (FileOutputStream outputStream = new FileOutputStream(pdfFilePath)) {
Document document = new Document();
PdfWriter.getInstance(document, outputStream);
document.open();
// Read XML content and add it to the Document
String xmlContent = new String(Files.readAllBytes(Paths.get(xmlFilePath)));
document.add(new Paragraph(xmlContent));
document.close();
}
}
} | repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xml\xml2pdf\XmlToPdfConverter.java | 1 |
请完成以下Java代码 | private void incrementHUCount()
{
final BigDecimal count = item.getQty();
final BigDecimal countNew = count.add(BigDecimal.ONE);
item.setQty(countNew);
dao.save(item);
}
private void decrementHUCount()
{
final BigDecimal count = item.getQty();
final BigDecimal countNew = count.subtract(BigDecimal.ONE);
item.setQty(countNew);
dao.save(item);
}
@Override
public int getHUCount()
{
final int count = item.getQty().intValueExact();
return count;
}
@Override
public int getHUCapacity()
{
if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType()))
{
return Quantity.QTY_INFINITE.intValue();
}
return Services.get(IHandlingUnitsBL.class).getPIItem(item).getQty().intValueExact();
}
@Override
public IProductStorage getProductStorage(final ProductId productId, final I_C_UOM uom, final ZonedDateTime date)
{
return new HUItemProductStorage(this, productId, uom, date);
}
@Override
public List<IProductStorage> getProductStorages(final ZonedDateTime date)
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
final List<IProductStorage> result = new ArrayList<>(storages.size());
for (final I_M_HU_Item_Storage storage : storages)
{
final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID());
final I_C_UOM uom = extractUOM(storage);
final HUItemProductStorage productStorage = new HUItemProductStorage(this, productId, uom, date);
result.add(productStorage);
}
return result;
}
private I_C_UOM extractUOM(final I_M_HU_Item_Storage storage)
{
return Services.get(IUOMDAO.class).getById(storage.getC_UOM_ID());
}
@Override
public boolean isEmpty()
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
for (final I_M_HU_Item_Storage storage : storages)
{ | if (!isEmpty(storage))
{
return false;
}
}
return true;
}
private boolean isEmpty(final I_M_HU_Item_Storage storage)
{
final BigDecimal qty = storage.getQty();
if (qty.signum() != 0)
{
return false;
}
return true;
}
@Override
public boolean isEmpty(final ProductId productId)
{
final I_M_HU_Item_Storage storage = dao.retrieveItemStorage(item, productId);
if (storage == null)
{
return true;
}
return isEmpty(storage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemStorage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public Credentials getCredentials() {
return credentials;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public List<String> getDefaultRecipients() { | return defaultRecipients;
}
public void setDefaultRecipients(List<String> defaultRecipients) {
this.defaultRecipients = defaultRecipients;
}
public Map<String, String> getAdditionalHeaders() {
return additionalHeaders;
}
public void setAdditionalHeaders(Map<String, String> additionalHeaders) {
this.additionalHeaders = additionalHeaders;
}
@Bean
@ConfigurationProperties(prefix = "item")
public Item item(){
return new Item();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\ConfigProperties.java | 2 |
请完成以下Java代码 | public boolean isLowerCaseServiceId() {
return lowerCaseServiceId;
}
public void setLowerCaseServiceId(boolean lowerCaseServiceId) {
this.lowerCaseServiceId = lowerCaseServiceId;
}
public List<PredicateDefinition> getPredicates() {
return predicates;
}
public void setPredicates(List<PredicateDefinition> predicates) {
this.predicates = predicates;
}
public List<FilterDefinition> getFilters() {
return filters;
} | public void setFilters(List<FilterDefinition> filters) {
this.filters = filters;
}
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", enabled)
.append("routeIdPrefix", routeIdPrefix)
.append("includeExpression", includeExpression)
.append("urlExpression", urlExpression)
.append("lowerCaseServiceId", lowerCaseServiceId)
.append("predicates", predicates)
.append("filters", filters)
.toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\discovery\DiscoveryLocatorProperties.java | 1 |
请完成以下Java代码 | public class JsonMapperUtil
{
/**
* Uses {@link JsonObjectMapperHolder} to make sure that the given {@code target} is serialized/deserialized into an instance of the given {@code type}.
* If this fails, it does not throw an exception, but returns an empty optional.
*/
@NonNull
public <T> Optional<T> tryDeserializeToType(@NonNull final Object target, @NonNull final Class<T> type)
{
if (type.isInstance(target))
{
return Optional.of((T)target);
}
final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{ | if (target instanceof String)
{
return Optional.of(objectMapper.readValue((String)target, type));
}
final String targetAsString = objectMapper.writeValueAsString(target);
return Optional.of(objectMapper.readValue(targetAsString, type));
}
catch (final JsonProcessingException exception)
{
return Optional.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\JsonMapperUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
/**
* 获取可用余额
*
* @return
*/
public BigDecimal getAvailableBalance() {
return this.balance.subtract(unbalance);
}
/**
* 获取实际可结算金额
*
* @return
*/
public BigDecimal getAvailableSettAmount() {
BigDecimal subSettAmount = this.settAmount.subtract(unbalance);
if (getAvailableBalance().compareTo(subSettAmount) == -1) {
return getAvailableBalance();
}
return subSettAmount;
}
/**
* 验证可用余额是否足够
*
* @param amount
* @return
*/
public boolean availableBalanceIsEnough(BigDecimal amount) {
return this.getAvailableBalance().compareTo(amount) >= 0;
}
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo == null ? null : accountNo.trim();
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public BigDecimal getUnbalance() {
return unbalance;
}
public void setUnbalance(BigDecimal unbalance) {
this.unbalance = unbalance;
}
public BigDecimal getSecurityMoney() {
return securityMoney;
}
public void setSecurityMoney(BigDecimal securityMoney) {
this.securityMoney = securityMoney;
}
public BigDecimal getTotalIncome() {
return totalIncome;
}
public void setTotalIncome(BigDecimal totalIncome) {
this.totalIncome = totalIncome;
}
public BigDecimal getTotalExpend() {
return totalExpend;
} | public void setTotalExpend(BigDecimal totalExpend) {
this.totalExpend = totalExpend;
}
public BigDecimal getTodayIncome() {
return todayIncome;
}
public void setTodayIncome(BigDecimal todayIncome) {
this.todayIncome = todayIncome;
}
public BigDecimal getTodayExpend() {
return todayExpend;
}
public void setTodayExpend(BigDecimal todayExpend) {
this.todayExpend = todayExpend;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType == null ? null : accountType.trim();
}
public BigDecimal getSettAmount() {
return settAmount;
}
public void setSettAmount(BigDecimal settAmount) {
this.settAmount = settAmount;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpAccount.java | 2 |
请完成以下Java代码 | public class Escalation {
protected final String id;
protected String name;
protected String escalationCode;
public Escalation(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) { | this.name = name;
}
public String getEscalationCode() {
return escalationCode;
}
public void setEscalationCode(String escalationCode) {
this.escalationCode = escalationCode;
}
public String getId() {
return id;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\Escalation.java | 1 |
请完成以下Java代码 | protected VariableMap filterVariables(VariableMap variables) {
if (variables != null) {
for (String key : variablesFilter) {
variables.remove(key);
}
}
return variables;
}
@Override
public void completed(ActivityExecution execution) throws Exception {
// only control flow. no sub instance data available
leave(execution);
}
public CallableElement getCallableElement() {
return callableElement;
}
public void setCallableElement(CallableElement callableElement) {
this.callableElement = callableElement;
}
protected String getBusinessKey(ActivityExecution execution) {
return getCallableElement().getBusinessKey(execution);
}
protected VariableMap getInputVariables(ActivityExecution callingExecution) {
return getCallableElement().getInputVariables(callingExecution);
}
protected VariableMap getOutputVariables(VariableScope calledElementScope) {
return getCallableElement().getOutputVariables(calledElementScope);
} | protected VariableMap getOutputVariablesLocal(VariableScope calledElementScope) {
return getCallableElement().getOutputVariablesLocal(calledElementScope);
}
protected Integer getVersion(ActivityExecution execution) {
return getCallableElement().getVersion(execution);
}
protected String getDeploymentId(ActivityExecution execution) {
return getCallableElement().getDeploymentId();
}
protected CallableElementBinding getBinding() {
return getCallableElement().getBinding();
}
protected boolean isLatestBinding() {
return getCallableElement().isLatestBinding();
}
protected boolean isDeploymentBinding() {
return getCallableElement().isDeploymentBinding();
}
protected boolean isVersionBinding() {
return getCallableElement().isVersionBinding();
}
protected abstract void startInstance(ActivityExecution execution, VariableMap variables, String businessKey);
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\CallableElementActivityBehavior.java | 1 |
请完成以下Java代码 | public static DeploymentMappings of(DeploymentMapping mapping) {
DeploymentMappings mappings = new DeploymentMappings();
mappings.add(mapping);
return mappings;
}
@Override
public boolean add(DeploymentMapping mapping) {
overallIdCount += mapping.getCount();
return super.add(mapping);
}
@Override
public DeploymentMapping remove(int mappingIndex) {
overallIdCount -= get(mappingIndex).getCount();
return super.remove(mappingIndex);
} | @Override
public boolean remove(Object mapping) {
if (super.remove(mapping)) {
overallIdCount -= ((DeploymentMapping) mapping).getCount();
return true;
}
return false;
}
public int getOverallIdCount() {
return overallIdCount;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\DeploymentMappings.java | 1 |
请完成以下Java代码 | public class MessageReceivedListenerDelegate implements ActivitiEventListener {
private List<BPMNElementEventListener<BPMNMessageReceivedEvent>> processRuntimeEventListeners;
private ToMessageReceivedConverter converter;
public MessageReceivedListenerDelegate(
List<BPMNElementEventListener<BPMNMessageReceivedEvent>> processRuntimeEventListeners,
ToMessageReceivedConverter converter
) {
this.processRuntimeEventListeners = processRuntimeEventListeners;
this.converter = converter;
}
@Override
public void onEvent(ActivitiEvent event) { | if (event instanceof ActivitiMessageEvent) {
converter
.from((ActivitiMessageEvent) event)
.ifPresent(convertedEvent -> {
for (BPMNElementEventListener<BPMNMessageReceivedEvent> listener : processRuntimeEventListeners) {
listener.onEvent(convertedEvent);
}
});
}
}
@Override
public boolean isFailOnException() {
return false;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\MessageReceivedListenerDelegate.java | 1 |
请完成以下Java代码 | public JobDefinitionQuery orderByJobType() {
return orderBy(JobDefinitionQueryProperty.JOB_TYPE);
}
public JobDefinitionQuery orderByJobConfiguration() {
return orderBy(JobDefinitionQueryProperty.JOB_CONFIGURATION);
}
public JobDefinitionQuery orderByTenantId() {
return orderBy(JobDefinitionQueryProperty.TENANT_ID);
}
// results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getJobDefinitionManager()
.findJobDefinitionCountByQueryCriteria(this);
}
@Override
public List<JobDefinition> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getJobDefinitionManager()
.findJobDefnitionByQueryCriteria(this, page);
}
// getters /////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getActivityIds() {
return activityIds;
} | public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getJobType() {
return jobType;
}
public String getJobConfiguration() {
return jobConfiguration;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getWithOverridingJobPriority() {
return withOverridingJobPriority;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\JobDefinitionQueryImpl.java | 1 |
请完成以下Java代码 | public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote)
{
set_Value (COLUMNNAME_TechnicalNote, TechnicalNote);
}
@Override
public java.lang.String getTechnicalNote()
{
return get_ValueAsString(COLUMNNAME_TechnicalNote);
}
/**
* Type AD_Reference_ID=540087
* Reference name: AD_Process Type
*/
public static final int TYPE_AD_Reference_ID=540087;
/** SQL = SQL */
public static final String TYPE_SQL = "SQL";
/** Java = Java */
public static final String TYPE_Java = "Java";
/** Excel = Excel */
public static final String TYPE_Excel = "Excel";
/** JasperReportsSQL = JasperReportsSQL */
public static final String TYPE_JasperReportsSQL = "JasperReportsSQL";
/** JasperReportsJSON = JasperReportsJSON */
public static final String TYPE_JasperReportsJSON = "JasperReportsJSON";
/** PostgREST = PostgREST */
public static final String TYPE_PostgREST = "PostgREST";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@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 setWorkflowValue (final @Nullable java.lang.String WorkflowValue)
{
set_Value (COLUMNNAME_WorkflowValue, WorkflowValue);
}
@Override
public java.lang.String getWorkflowValue()
{
return get_ValueAsString(COLUMNNAME_WorkflowValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
//object 中包含用户请求的request 信息
HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
for (Iterator<String> it = map.keySet().iterator() ; it.hasNext();) {
String url = it.next();
if (new AntPathRequestMatcher( url ).matches( request )) {
return map.get( url );
}
}
return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
//初始化 所有资源 对应的角色
loadResourceDefine();
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
/**
* 初始化 所有资源 对应的角色
*/
public void loadResourceDefine() {
map = new HashMap<>(16);
//权限资源 和 角色对应的表 也就是 角色权限 中间表
List<RolePermisson> rolePermissons = permissionMapper.getRolePermissions();
//某个资源 可以被哪些角色访问
for (RolePermisson rolePermisson : rolePermissons) { | String url = rolePermisson.getUrl();
String roleName = rolePermisson.getRoleName();
ConfigAttribute role = new SecurityConfig(roleName);
if(map.containsKey(url)){
map.get(url).add(role);
}else{
List<ConfigAttribute> list = new ArrayList<>();
list.add( role );
map.put( url , list );
}
}
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyInvocationSecurityMetadataSourceService.java | 2 |
请完成以下Java代码 | public class PrintfExamples {
public static void main(String[] args) {
printfNewLine();
printfChar();
printfString();
printfNumber();
printfDateTime();
printfBoolean();
}
private static void printfNewLine() {
System.out.printf("baeldung%nline%nterminator");
}
private static void printfString() {
System.out.printf("'%s' %n", "baeldung");
System.out.printf("'%S' %n", "baeldung");
System.out.printf("'%15s' %n", "baeldung");
System.out.printf("'%-10s' %n", "baeldung");
}
private static void printfChar() {
System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');
}
private static void printfNumber() {
System.out.printf("simple integer: %d%n", 10000L);
System.out.printf(Locale.US, "%,d %n", 10000);
System.out.printf(Locale.ITALY, "%,d %n", 10000);
System.out.printf("%f%n", 5.1473);
System.out.printf("'%5.2f'%n", 5.1473);
System.out.printf("'%5.2e'%n", 5.1473); | }
private static void printfBoolean() {
System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");
}
private static void printfDateTime() {
Date date = new Date();
System.out.printf("%tT%n", date);
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
System.out.printf("%1$tA %1$tB %1$tY %n", date);
System.out.printf("%1$td.%1$tm.%1$ty %n", date);
}
} | repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\printf\PrintfExamples.java | 1 |
请完成以下Java代码 | public void createBucket(String bucketName) {
logger.debug("Creating S3 bucket: {}", bucketName);
amazonS3.createBucket(bucketName);
logger.info("{} bucket created successfully", bucketName);
}
public void downloadObject(String bucketName, String objectName) {
String s3Url = "s3://" + bucketName + "/" + objectName;
try {
springCloudS3.downloadS3Object(s3Url);
logger.info("{} file download result: {}", objectName, new File(objectName).exists());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
public void uploadObject(String bucketName, String objectName) {
String s3Url = "s3://" + bucketName + "/" + objectName;
File file = new File(objectName);
try {
springCloudS3.uploadFileToS3(file, s3Url);
logger.info("{} file uploaded to S3", objectName); | } catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
public void deleteBucket(String bucketName) {
logger.trace("Deleting S3 objects under {} bucket...", bucketName);
ListObjectsV2Result listObjectsV2Result = amazonS3.listObjectsV2(bucketName);
for (S3ObjectSummary objectSummary : listObjectsV2Result.getObjectSummaries()) {
logger.info("Deleting S3 object: {}", objectSummary.getKey());
amazonS3.deleteObject(bucketName, objectSummary.getKey());
}
logger.info("Deleting S3 bucket: {}", bucketName);
amazonS3.deleteBucket(bucketName);
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\java\com\baeldung\spring\cloud\aws\s3\SpringCloudS3Service.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
if (p_AD_Tab_ID <= 0)
{
throw new FillMandatoryException(I_AD_Tab.COLUMNNAME_AD_Tab_ID);
}
final I_AD_Tab adTab = InterfaceWrapperHelper.create(getCtx(), p_AD_Tab_ID, I_AD_Tab.class, getTrxName());
copySingleLayoutToGridLayout(adTab);
return MSG_OK;
}
private void copySingleLayoutToGridLayout(final I_AD_Tab adTab) | {
final List<I_AD_Field> adFields = Services.get(IADWindowDAO.class).retrieveFields(adTab);
for (final I_AD_Field adField : adFields)
{
copySingleLayoutToGridLayout(adField);
InterfaceWrapperHelper.save(adField);
}
}
private void copySingleLayoutToGridLayout(final I_AD_Field adField)
{
adField.setIsDisplayedGrid(adField.isDisplayed());
adField.setSeqNoGrid(adField.getSeqNo());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\process\AD_Tab_SetGridLayoutFromSingleLayout.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InstantType implements VariableType {
public static final String TYPE_NAME = "instant";
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Instant.class.isAssignableFrom(value.getClass());
} | @Override
public Object getValue(ValueFields valueFields) {
Long longValue = valueFields.getLongValue();
if (longValue != null) {
return Instant.ofEpochMilli(longValue);
}
return null;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
Instant instant = (Instant) value;
valueFields.setLongValue(instant.toEpochMilli());
} else {
valueFields.setLongValue(null);
}
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\InstantType.java | 2 |
请完成以下Java代码 | public Object execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("Task id should not be null");
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("Task '" + taskId + "' not found", Task.class);
}
FormHandlerHelper formHandlerHelper = processEngineConfiguration.getFormHandlerHelper();
TaskFormHandler taskFormHandler = formHandlerHelper.getTaskFormHandlder(task);
if (taskFormHandler != null) { | FormEngine formEngine = processEngineConfiguration.getFormEngines().get(formEngineName);
if (formEngine == null) {
throw new FlowableException("No formEngine '" + formEngineName + "' defined process engine configuration");
}
TaskFormData taskForm = taskFormHandler.createTaskForm(task);
return formEngine.renderTaskForm(taskForm);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetRenderedTaskFormCmd.java | 1 |
请完成以下Java代码 | public void setOrgColumn (String OrgColumn)
{
set_Value (COLUMNNAME_OrgColumn, OrgColumn);
}
/** Get Org Column.
@return Fully qualified Organization column (AD_Org_ID)
*/
public String getOrgColumn ()
{
return (String)get_Value(COLUMNNAME_OrgColumn);
}
/** 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_ValueNoCheck (COLUMNNAME_PA_MeasureCalc_ID, null);
else
set_ValueNoCheck (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 Product Column.
@param ProductColumn
Fully qualified Product column (M_Product_ID)
*/
public void setProductColumn (String ProductColumn)
{
set_Value (COLUMNNAME_ProductColumn, ProductColumn);
}
/** Get Product Column. | @return Fully qualified Product column (M_Product_ID)
*/
public String getProductColumn ()
{
return (String)get_Value(COLUMNNAME_ProductColumn);
}
/** Set Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_MeasureCalc.java | 1 |
请完成以下Java代码 | default Optional<PO> copyToNew(@NonNull PO fromPO) {return copyToNew(fromPO, null);}
/**
* Recursively copy given PO and it's children
*
* @return copied PO or empty if given PO shall not be copied for some reason
*/
Optional<PO> copyToNew(@NonNull PO fromPO, @Nullable CopyTemplate template);
/**
* Recursively copy all childrens of <code>fromPO</code> to given <code>toPO</code>
*/
void copyChildren(@NonNull PO toPO, @NonNull PO fromPO);
CopyRecordSupport setParentLink(@NonNull PO parentPO, @NonNull String parentLinkColumnName);
CopyRecordSupport setAdWindowId(@Nullable AdWindowId adWindowId);
/**
* Allows other modules to install custom code to be executed each time a record was copied.
* <p>
* <b>Important:</b> usually it makes sense to register a listener not here, but by invoking {@link CopyRecordFactory#registerCopyRecordSupport(String, Class)}.
* A listener that is registered there will be added to each CopyRecordSupport instance created by that factory.
*/
@SuppressWarnings("UnusedReturnValue") | CopyRecordSupport onRecordCopied(OnRecordCopiedListener listener);
default CopyRecordSupport onRecordCopied(final List<OnRecordCopiedListener> listeners)
{
listeners.forEach(this::onRecordCopied);
return this;
}
CopyRecordSupport onChildRecordCopied(OnRecordCopiedListener listener);
default CopyRecordSupport oChildRecordCopied(final List<OnRecordCopiedListener> listeners)
{
listeners.forEach(this::onChildRecordCopied);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\CopyRecordSupport.java | 1 |
请完成以下Java代码 | public class InOutCostsView extends AbstractCustomView<InOutCostRow>
{
@NonNull private final ImmutableList<RelatedProcessDescriptor> relatedProcesses;
@Builder
private InOutCostsView(
final @NonNull ViewId viewId,
final @NonNull InOutCostsViewData rowsData,
final @NonNull DocumentFilterDescriptor filterDescriptor,
final @NonNull @Singular ImmutableList<RelatedProcessDescriptor> relatedProcesses)
{
super(viewId, null, rowsData, ImmutableDocumentFilterDescriptorsProvider.of(filterDescriptor));
this.relatedProcesses = relatedProcesses;
}
@Nullable
@Override | public String getTableNameOrNull(@Nullable final DocumentId documentId) {return null;}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors() {return relatedProcesses;}
@Override
public DocumentFilterList getFilters() {return DocumentFilterList.ofNullable(getRowsData().getFilter());}
@Override
protected InOutCostsViewData getRowsData() {return (InOutCostsViewData)super.getRowsData();}
public SOTrx getSoTrx() {return getRowsData().getSoTrx();}
public InvoiceAndLineId getInvoiceLineId() {return getRowsData().getInvoiceAndLineId();}
@Override
public ViewHeaderProperties getHeaderProperties() {return getRowsData().getHeaderProperties();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsView.java | 1 |
请完成以下Java代码 | public List<LwM2MModelConfig> getAll() {
try (var connection = connectionFactory.getConnection()) {
List<LwM2MModelConfig> configs = new ArrayList<>();
ScanOptions scanOptions = ScanOptions.scanOptions().count(100).match(MODEL_EP + "*").build();
List<Cursor<byte[]>> scans = new ArrayList<>();
if (connection instanceof RedisClusterConnection) {
((RedisClusterConnection) connection).clusterGetNodes().forEach(node -> {
scans.add(((RedisClusterConnection) connection).scan(node, scanOptions));
});
} else {
scans.add(connection.scan(scanOptions));
}
scans.forEach(scan -> {
scan.forEachRemaining(key -> {
byte[] element = connection.get(key);
configs.add(JacksonUtil.fromBytes(element, LwM2MModelConfig.class));
});
});
return configs;
}
} | @Override
public void put(LwM2MModelConfig modelConfig) {
byte[] clientSerialized = JacksonUtil.writeValueAsBytes(modelConfig);
try (var connection = connectionFactory.getConnection()) {
connection.getSet(getKey(modelConfig.getEndpoint()), clientSerialized);
}
}
@Override
public void remove(String endpoint) {
try (var connection = connectionFactory.getConnection()) {
connection.del(getKey(endpoint));
}
}
private byte[] getKey(String endpoint) {
return (MODEL_EP + endpoint).getBytes();
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbRedisLwM2MModelConfigStore.java | 1 |
请完成以下Java代码 | private static LookupValue toLookupValue(
@Nullable final Array sqlArray,
final boolean isNumericKey,
final boolean isTranslatable,
@Nullable final String adLanguage) throws SQLException
{
if (sqlArray == null)
{
return null;
}
final String[] array = (String[])sqlArray.getArray();
if (array == null || array.length == 0)
{
return null;
}
final String idString = StringUtils.trimBlankToNull(array[0]);
if (idString == null)
{
return null;
}
final String displayName = StringUtils.trimBlankToOptional(array[1]).orElse("");
final String description = StringUtils.trimBlankToNull(array[2]);
final boolean active = StringUtils.toBoolean(array[3]);
final ITranslatableString displayNameTrl;
final ITranslatableString descriptionTrl;
if (isTranslatable)
{
displayNameTrl = TranslatableStrings.singleLanguage(adLanguage, displayName);
descriptionTrl = TranslatableStrings.singleLanguage(adLanguage, description);
}
else
{
displayNameTrl = TranslatableStrings.anyLanguage(displayName);
descriptionTrl = TranslatableStrings.anyLanguage(description);
}
if (isNumericKey)
{
final int idInt = Integer.parseInt(idString);
return LookupValue.IntegerLookupValue.builder()
.id(idInt)
.displayName(displayNameTrl)
.description(descriptionTrl)
.active(active)
.build();
}
else
{
final ValueNamePairValidationInformation validationInformation = StringUtils.trimBlankToOptional(array[4])
.map(questionMsg -> ValueNamePairValidationInformation.builder() | .question(AdMessageKey.of(questionMsg))
.build())
.orElse(null);
return LookupValue.StringLookupValue.builder()
.id(idString)
.displayName(displayNameTrl)
.description(descriptionTrl)
.active(active)
.validationInformation(validationInformation)
.build();
}
}
@Nullable
public static LookupValue.IntegerLookupValue retrieveIntegerLookupValue(
@NonNull final ResultSet rs,
@NonNull final String columnName,
@Nullable final String adLanguage) throws SQLException
{
final Array sqlArray = rs.getArray(columnName);
return (LookupValue.IntegerLookupValue)toLookupValue(sqlArray, true, true, adLanguage);
}
@Nullable
public static LookupValue.StringLookupValue retrieveStringLookupValue(
@NonNull final ResultSet rs,
@NonNull final String columnName,
@Nullable final String adLanguage) throws SQLException
{
final Array sqlArray = rs.getArray(columnName);
return (LookupValue.StringLookupValue)toLookupValue(sqlArray, false, true, adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlForFetchingLookupById.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setOrderPrice(BigDecimal orderPrice) {
this.orderPrice = orderPrice;
}
public String getOrderIp() {
return orderIp;
}
public void setOrderIp(String orderIp) {
this.orderIp = orderIp;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getOrderTime() {
return orderTime;
}
public void setOrderTime(String orderTime) {
this.orderTime = orderTime;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
} | public String getPayType() {
return payType;
}
public void setPayType(String payType) {
this.payType = payType;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
@Override
public String toString() {
return "ProgramPayRequestBo{" +
"payKey='" + payKey + '\'' +
", openId='" + openId + '\'' +
", productName='" + productName + '\'' +
", orderNo='" + orderNo + '\'' +
", orderPrice=" + orderPrice +
", orderIp='" + orderIp + '\'' +
", orderDate='" + orderDate + '\'' +
", orderTime='" + orderTime + '\'' +
", notifyUrl='" + notifyUrl + '\'' +
", sign='" + sign + '\'' +
", remark='" + remark + '\'' +
", payType='" + payType + '\'' +
'}';
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\bo\ProgramPayRequestBo.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private RootBeanDefinition getRootBeanDefinition(String mode) {
if (isUnboundidEnabled(mode)) {
return new RootBeanDefinition(UNBOUNDID_CONTAINER_CLASSNAME, null, null);
}
throw new IllegalStateException("Embedded LDAP server is not provided");
}
private String resolveBeanId(String mode) {
if (isUnboundidEnabled(mode)) {
return BeanIds.EMBEDDED_UNBOUNDID;
}
return null;
}
private boolean isUnboundidEnabled(String mode) {
return "unboundid".equals(mode) || unboundIdPresent;
}
private String getPort(Element element) {
String port = element.getAttribute(ATT_PORT);
return (StringUtils.hasText(port) ? port : getDefaultPort());
}
private String getDefaultPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return String.valueOf(serverSocket.getLocalPort());
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
private static class EmbeddedLdapServerConfigBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
} | @SuppressWarnings("unused")
private DefaultSpringSecurityContextSource createEmbeddedContextSource(String suffix) {
int port = getPort();
String providerUrl = "ldap://127.0.0.1:" + port + "/" + suffix;
return new DefaultSpringSecurityContextSource(providerUrl);
}
private int getPort() {
if (unboundIdPresent) {
UnboundIdContainer unboundIdContainer = this.applicationContext.getBean(UnboundIdContainer.class);
return unboundIdContainer.getPort();
}
throw new IllegalStateException("Embedded LDAP server is not provided");
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapServerBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public boolean load(ByteArray byteArray)
{
loadTagSet(byteArray);
int size = byteArray.nextInt();
for (int i = 0; i < size; i++)
{
idOf(byteArray.nextUTF());
}
return true;
}
protected final void loadTagSet(ByteArray byteArray)
{
TaskType type = TaskType.values()[byteArray.nextInt()];
switch (type)
{ | case CWS:
tagSet = new CWSTagSet();
break;
case POS:
tagSet = new POSTagSet();
break;
case NER:
tagSet = new NERTagSet();
break;
case CLASSIFICATION:
tagSet = new TagSet(TaskType.CLASSIFICATION);
break;
}
tagSet.load(byteArray);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\FeatureMap.java | 1 |
请完成以下Spring Boot application配置 | spring:
# datasource 数据源配置内容,对应 DataSourceProperties 配置属性类
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root # 数据库账号
password: # 数据库密码
# HikariCP 自定义配置,对应 HikariConf | ig 配置属性类
hikari:
minimum-idle: 20 # 池中维护的最小空闲连接数,默认为 10 个。
maximum-pool-size: 20 # 池中最大连接数,包括闲置和使用中的连接,默认为 10 个。 | repos\SpringBoot-Labs-master\lab-19\lab-19-datasource-pool-hikaricp-single\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public void setDueDate (final java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override | 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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoicePaySchedule.java | 1 |
请完成以下Java代码 | public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if ((servletRequest instanceof HttpServletRequest) && (servletResponse instanceof HttpServletResponse)) {
// create a session if none exists yet
((HttpServletRequest) servletRequest).getSession();
// execute filter chain with a response wrapper that handles sameSite attributes
filterChain.doFilter(servletRequest, new SameSiteResponseProxy((HttpServletResponse) servletResponse));
}
}
@Override
public void destroy() {
}
protected class SameSiteResponseProxy extends HttpServletResponseWrapper {
protected HttpServletResponse response;
public SameSiteResponseProxy(HttpServletResponse resp) {
super(resp);
response = resp;
}
@Override
public void sendError(int sc) throws IOException {
appendSameSiteIfMissing();
super.sendError(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
appendSameSiteIfMissing();
super.sendError(sc, msg);
}
@Override
public void sendRedirect(String location) throws IOException {
appendSameSiteIfMissing();
super.sendRedirect(location);
} | @Override
public PrintWriter getWriter() throws IOException {
appendSameSiteIfMissing();
return super.getWriter();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
appendSameSiteIfMissing();
return super.getOutputStream();
}
protected void appendSameSiteIfMissing() {
Collection<String> cookieHeaders = response.getHeaders(CookieConstants.SET_COOKIE_HEADER_NAME);
boolean firstHeader = true;
String cookieHeaderStart = cookieConfigurator.getCookieName("JSESSIONID") + "=";
for (String cookieHeader : cookieHeaders) {
if (cookieHeader.startsWith(cookieHeaderStart)) {
cookieHeader = cookieConfigurator.getConfig(cookieHeader);
}
if (firstHeader) {
response.setHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader);
firstHeader = false;
} else {
response.addHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader);
}
}
}
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SessionCookieFilter.java | 1 |
请完成以下Java代码 | public class GatewaySessionHandler extends AbstractGatewaySessionHandler<GatewayDeviceSessionContext> {
public GatewaySessionHandler(DeviceSessionCtx deviceSessionCtx, UUID sessionId, boolean overwriteDevicesActivity) {
super(deviceSessionCtx, sessionId, overwriteDevicesActivity);
}
public void onDeviceConnect(MqttPublishMessage mqttMsg) throws AdaptorException {
if (isJsonPayloadType()) {
onDeviceConnectJson(mqttMsg);
} else {
onDeviceConnectProto(mqttMsg);
}
}
public void onDeviceTelemetry(MqttPublishMessage mqttMsg) throws AdaptorException {
int msgId = getMsgId(mqttMsg);
ByteBuf payload = mqttMsg.payload();
if (isJsonPayloadType()) {
onDeviceTelemetryJson(msgId, payload);
} else {
onDeviceTelemetryProto(msgId, payload);
}
} | @Override
protected GatewayDeviceSessionContext newDeviceSessionCtx(GetOrCreateDeviceFromGatewayResponse msg) {
return new GatewayDeviceSessionContext(this, msg.getDeviceInfo(), msg.getDeviceProfile(), mqttQoSMap, transportService);
}
public void onGatewayUpdate(TransportProtos.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) {
this.onDeviceUpdate(sessionInfo, device, deviceProfileOpt);
gatewayMetricsService.onDeviceUpdate(sessionInfo, gateway.getDeviceId());
}
public void onGatewayDelete(DeviceId deviceId) {
gatewayMetricsService.onDeviceDelete(deviceId);
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\session\GatewaySessionHandler.java | 1 |
请完成以下Java代码 | public boolean doCatch(final Throwable e) throws Throwable
{
throw AdempiereException.wrapIfNeeded(e)
.markUserNotified();
}
@Override
public void doFinally()
{
// nothing
}
});
}
}
private ReportResult printPicklist(@NonNull final PackageableRow row)
{
final PInstanceRequest pinstanceRequest = createPInstanceRequest(row);
final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder()
.setCtx(getCtx())
.setAD_Process_ID(PickListPdf_AD_Process_ID)
.setAD_PInstance(adPInstanceDAO.getById(pinstanceId))
.setReportLanguage(getProcessInfo().getReportLanguage())
.setJRDesiredOutputType(OutputType.PDF)
.build();
final ReportsClient reportsClient = ReportsClient.get();
return reportsClient.report(jasperProcessInfo);
}
private PInstanceRequest createPInstanceRequest(@NonNull final PackageableRow row) | {
final String orderNo = row.getOrderDocumentNo();
final List<ProcessInfoParameter> piParams = ImmutableList.of(ProcessInfoParameter.of(I_M_Packageable_V.COLUMNNAME_OrderDocumentNo, orderNo));
final PInstanceRequest pinstanceRequest = PInstanceRequest.builder()
.processId(PickListPdf_AD_Process_ID)
.processParams(piParams)
.build();
return pinstanceRequest;
}
private String buildFilename(@NonNull final PackageableRow row)
{
final String customer = row.getCustomer().getDisplayName();
final String docuemntNo = row.getOrderDocumentNo();
return Joiner.on("_")
.skipNulls()
.join(docuemntNo, customer)
+ ".pdf";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\process\PackageablesView_PrintPicklist.java | 1 |
请完成以下Java代码 | default boolean isNoBPartners()
{
final Set<Integer> bpartnerIds = getBpartnerIds();
return bpartnerIds == null || bpartnerIds.isEmpty();
}
default boolean isAnyBPartner()
{
final Set<Integer> bpartnerIds = getBpartnerIds();
return bpartnerIds != null
? bpartnerIds.contains(0) || bpartnerIds.contains(-1) || bpartnerIds.contains(ANY)
: false;
}
Set<Integer> getLocatorIds();
default boolean isNoLocators()
{
final Set<Integer> locatorIds = getLocatorIds();
return locatorIds == null || locatorIds.isEmpty();
} | Set<Integer> getBillBPartnerIds();
default boolean isAnyBillBPartner()
{
final Set<Integer> billBPartnerIds = getBillBPartnerIds();
return billBPartnerIds.isEmpty() || billBPartnerIds.contains(0) || billBPartnerIds.contains(-1) || billBPartnerIds.contains(ANY);
}
default boolean isAnyLocator()
{
final Set<Integer> locatorIds = getLocatorIds();
return locatorIds != null
? locatorIds.contains(0) || locatorIds.contains(-1) || locatorIds.contains(ANY)
: false;
}
Set<ShipmentScheduleAttributeSegment> getAttributes();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\segments\IShipmentScheduleSegment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SpnegoEntryPoint spnegoEntryPoint() {
return new SpnegoEntryPoint("/login");
}
@Bean
public SpnegoAuthenticationProcessingFilter spnegoAuthenticationProcessingFilter(AuthenticationManager authenticationManager) {
SpnegoAuthenticationProcessingFilter filter = new SpnegoAuthenticationProcessingFilter();
filter.setAuthenticationManager(authenticationManager);
return filter;
}
@Bean
public KerberosServiceAuthenticationProvider kerberosServiceAuthenticationProvider() {
KerberosServiceAuthenticationProvider provider = new KerberosServiceAuthenticationProvider();
provider.setTicketValidator(sunJaasKerberosTicketValidator());
provider.setUserDetailsService(dummyUserDetailsService());
return provider;
} | @Bean
public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
ticketValidator.setServicePrincipal("HTTP/demo.kerberos.bealdung.com@baeldung.com");
ticketValidator.setKeyTabLocation(new FileSystemResource("baeldung.keytab"));
ticketValidator.setDebug(true);
return ticketValidator;
}
@Bean
public DummyUserDetailsService dummyUserDetailsService() {
return new DummyUserDetailsService();
}
} | repos\tutorials-master\spring-security-modules\spring-security-oauth2-sso\spring-security-sso-kerberos\src\main\java\com\baeldung\intro\config\WebSecurityConfig.java | 2 |
请完成以下Java代码 | public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID)
{
if (MobileUI_UserProfile_Picking_ID < 1)
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null);
else
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID);
}
@Override
public int getMobileUI_UserProfile_Picking_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID);
}
/**
* PickingJobField AD_Reference_ID=541850
* Reference name: PickingJobField_Options
*/
public static final int PICKINGJOBFIELD_AD_Reference_ID=541850;
/** DocumentNo = DocumentNo */
public static final String PICKINGJOBFIELD_DocumentNo = "DocumentNo";
/** Customer = Customer */
public static final String PICKINGJOBFIELD_Customer = "Customer";
/** Delivery Address = ShipToLocation */
public static final String PICKINGJOBFIELD_DeliveryAddress = "ShipToLocation";
/** Date Ready = PreparationDate */
public static final String PICKINGJOBFIELD_DateReady = "PreparationDate";
/** Handover Location = HandoverLocation */
public static final String PICKINGJOBFIELD_HandoverLocation = "HandoverLocation";
/** Rüstplatz Nr. = Setup_Place_No */
public static final String PICKINGJOBFIELD_RuestplatzNr = "Setup_Place_No";
/** Product = Product */
public static final String PICKINGJOBFIELD_Product = "Product";
/** QtyToDeliver = QtyToDeliver */
public static final String PICKINGJOBFIELD_QtyToDeliver = "QtyToDeliver";
@Override
public void setPickingJobField (final java.lang.String PickingJobField)
{ | set_Value (COLUMNNAME_PickingJobField, PickingJobField);
}
@Override
public java.lang.String getPickingJobField()
{
return get_ValueAsString(COLUMNNAME_PickingJobField);
}
@Override
public void setPickingProfile_PickingJobConfig_ID (final int PickingProfile_PickingJobConfig_ID)
{
if (PickingProfile_PickingJobConfig_ID < 1)
set_ValueNoCheck (COLUMNNAME_PickingProfile_PickingJobConfig_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PickingProfile_PickingJobConfig_ID, PickingProfile_PickingJobConfig_ID);
}
@Override
public int getPickingProfile_PickingJobConfig_ID()
{
return get_ValueAsInt(COLUMNNAME_PickingProfile_PickingJobConfig_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\picking\model\X_PickingProfile_PickingJobConfig.java | 1 |
请完成以下Java代码 | public BatchDto executeModificationAsync(ModificationDto modificationExecutionDto) {
Batch batch = null;
try {
batch = createModificationBuilder(modificationExecutionDto).executeAsync();
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
return BatchDto.fromBatch(batch);
}
private ModificationBuilder createModificationBuilder(ModificationDto dto) {
ModificationBuilder builder = getProcessEngine().getRuntimeService().createModification(dto.getProcessDefinitionId());
if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) {
dto.applyTo(builder, getProcessEngine(), objectMapper);
}
List<String> processInstanceIds = dto.getProcessInstanceIds();
builder.processInstanceIds(processInstanceIds);
ProcessInstanceQueryDto processInstanceQueryDto = dto.getProcessInstanceQuery();
if (processInstanceQueryDto != null) {
ProcessInstanceQuery processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine());
builder.processInstanceQuery(processInstanceQuery);
} | HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = dto.getHistoricProcessInstanceQuery();
if(historicProcessInstanceQueryDto != null) {
HistoricProcessInstanceQuery historicProcessInstanceQuery = historicProcessInstanceQueryDto.toQuery(getProcessEngine());
builder.historicProcessInstanceQuery(historicProcessInstanceQuery);
}
if (dto.isSkipCustomListeners()) {
builder.skipCustomListeners();
}
if (dto.isSkipIoMappings()) {
builder.skipIoMappings();
}
if (dto.getAnnotation() != null) {
builder.setAnnotation(dto.getAnnotation());
}
return builder;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ModificationRestServiceImpl.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_AcctSchema getC_AcctSchema()
{
return get_ValueAsPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class);
}
@Override
public void setC_AcctSchema(final org.compiere.model.I_C_AcctSchema C_AcctSchema)
{
set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema);
}
@Override
public void setC_AcctSchema_ID (final int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID);
}
@Override
public int getC_AcctSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID);
}
@Override
public void setC_Project_ID (final int C_Project_ID)
{
if (C_Project_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Project_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID);
}
@Override
public int getC_Project_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Project_ID);
}
@Override
public org.compiere.model.I_C_ValidCombination getPJ_Asset_A()
{
return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A)
{
set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A);
}
@Override
public void setPJ_Asset_Acct (final int PJ_Asset_Acct)
{
set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct);
}
@Override
public int getPJ_Asset_Acct() | {
return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct);
}
@Override
public org.compiere.model.I_C_ValidCombination getPJ_WIP_A()
{
return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A)
{
set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A);
}
@Override
public void setPJ_WIP_Acct (final int PJ_WIP_Acct)
{
set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct);
}
@Override
public int getPJ_WIP_Acct()
{
return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java | 1 |
请完成以下Java代码 | public String getLifeCycleTransition() {
return PlanItemTransition.ASYNC_ACTIVATE;
}
@Override
public String getNewState() {
return PlanItemInstanceState.ASYNC_ACTIVE;
}
@Override
protected void internalExecute() {
planItemInstanceEntity.setLastStartedTime(getCurrentTime(commandContext));
CommandContextUtil.getCmmnHistoryManager(commandContext).recordPlanItemInstanceStarted(planItemInstanceEntity);
createAsyncJob((Task) planItemInstanceEntity.getPlanItem().getPlanItemDefinition());
}
protected void createAsyncJob(Task task) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
JobService jobService = cmmnEngineConfiguration.getJobServiceConfiguration().getJobService();
JobEntity job = JobUtil.createJob(planItemInstanceEntity, task, AsyncActivatePlanItemInstanceJobHandler.TYPE, cmmnEngineConfiguration);
job.setJobHandlerConfiguration(entryCriterionId);
jobService.createAsyncJob(job, task.isExclusive());
jobService.scheduleAsyncJob(job);
if (cmmnEngineConfiguration.isLoggingSessionEnabled()) {
CmmnLoggingSessionUtil.addAsyncActivityLoggingData("Created async job for " + planItemInstanceEntity.getPlanItemDefinitionId() + ", with job id " + job.getId(),
CmmnLoggingSessionConstants.TYPE_SERVICE_TASK_ASYNC_JOB, job, planItemInstanceEntity.getPlanItemDefinition(),
planItemInstanceEntity, cmmnEngineConfiguration.getObjectMapper()); | }
}
@Override
public String toString() {
PlanItem planItem = planItemInstanceEntity.getPlanItem();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[Async activate PlanItem] ");
stringBuilder.append(planItem);
if (entryCriterionId != null) {
stringBuilder.append(" via entry criterion ").append(entryCriterionId);
}
return stringBuilder.toString();
}
@Override
public String getOperationName() {
return "[Async activate plan item]";
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\ActivateAsyncPlanItemInstanceOperation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MainApplication {
private static final Logger logger = Logger.getLogger(MainApplication.class.getName());
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean | public ApplicationRunner init() {
return args -> {
bookstoreService.insertBook();
BookReview bookReview = new BookReview();
bookReview.setContent("Very good book!");
bookReview.setEmail("marinv@gmail.com");
bookReview.setStatus(CHECK);
String response = bookstoreService.postReview(bookReview);
logger.info(() -> "Response: " + response);
};
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\MainApplication.java | 2 |
请完成以下Java代码 | public HU getResult()
{
assume(huStack.isEmpty(), "In the end, huStack needs to be empty");
final HU root = currentIdAndBuilder.getRight().build();
return root;
}
}
@ToString
private static class HUStack
{
private final ArrayList<HuId> huIds = new ArrayList<>();
private final HashMap<HuId, HUBuilder> hus = new HashMap<>();
void push(@NonNull final IPair<HuId, HUBuilder> idWithHuBuilder)
{
this.huIds.add(idWithHuBuilder.getLeft());
this.hus.put(idWithHuBuilder.getLeft(), idWithHuBuilder.getRight());
}
public boolean isEmpty()
{
return huIds.isEmpty();
} | public IPair<HuId, HUBuilder> peek()
{
final HuId huId = this.huIds.get(huIds.size() - 1);
final HUBuilder huBuilder = this.hus.get(huId);
return ImmutablePair.of(huId, huBuilder);
}
final IPair<HuId, HUBuilder> pop()
{
final HuId huId = this.huIds.remove(huIds.size() - 1);
final HUBuilder huBuilder = this.hus.remove(huId);
return ImmutablePair.of(huId, huBuilder);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\generichumodel\HURepository.java | 1 |
请完成以下Java代码 | public class SecurityContextHolderFilter extends GenericFilterBean {
private static final String FILTER_APPLIED = SecurityContextHolderFilter.class.getName() + ".APPLIED";
private final SecurityContextRepository securityContextRepository;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
/**
* Creates a new instance.
* @param securityContextRepository the repository to use. Cannot be null.
*/
public SecurityContextHolderFilter(SecurityContextRepository securityContextRepository) {
Assert.notNull(securityContextRepository, "securityContextRepository cannot be null");
this.securityContextRepository = securityContextRepository;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
if (request.getAttribute(FILTER_APPLIED) != null) {
chain.doFilter(request, response);
return;
}
request.setAttribute(FILTER_APPLIED, Boolean.TRUE); | Supplier<SecurityContext> deferredContext = this.securityContextRepository.loadDeferredContext(request);
try {
this.securityContextHolderStrategy.setDeferredContext(deferredContext);
chain.doFilter(request, response);
}
finally {
this.securityContextHolderStrategy.clearContext();
request.removeAttribute(FILTER_APPLIED);
}
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\SecurityContextHolderFilter.java | 1 |
请完成以下Java代码 | public void setSAP_GLJournal_ID (final int SAP_GLJournal_ID)
{
if (SAP_GLJournal_ID < 1)
set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SAP_GLJournal_ID, SAP_GLJournal_ID);
}
@Override
public int getSAP_GLJournal_ID()
{
return get_ValueAsInt(COLUMNNAME_SAP_GLJournal_ID);
}
@Override
public void setTotalCr (final BigDecimal TotalCr)
{
set_ValueNoCheck (COLUMNNAME_TotalCr, TotalCr);
}
@Override
public BigDecimal getTotalCr()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalCr); | return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTotalDr (final BigDecimal TotalDr)
{
set_ValueNoCheck (COLUMNNAME_TotalDr, TotalDr);
}
@Override
public BigDecimal getTotalDr()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalDr);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_SAP_GLJournal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
} | public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
// prettier-ignore
@Override
public String toString() {
return "AdminUserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\service\dto\AdminUserDTO.java | 2 |
请完成以下Java代码 | public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) { | this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java | 1 |
请完成以下Java代码 | public boolean isPickingSlotRow()
{
return pickingSlotRowId.isPickingSlotRow();
}
public PickingSlotId getPickingSlotId()
{
return getPickingSlotRowId().getPickingSlotId();
}
public HuId getHuId()
{
return pickingSlotRowId.getHuId();
}
/**
* @return {@code true} is this row represents an HU that is assigned to a picking slot
*/
public boolean isPickedHURow()
{
return pickingSlotRowId.isPickedHURow();
}
public boolean isTopLevelHU()
{
return huTopLevel;
}
public boolean isTopLevelTU()
{
return isTU() && isTopLevelHU();
}
public boolean isLU()
{
return isPickedHURow() && getType().isLU();
}
public boolean isTU()
{
return isPickedHURow() && getType().isTU();
}
public boolean isCU()
{
return isPickedHURow() && getType().isCU();
}
public boolean isCUOrStorage()
{
return isPickedHURow() && getType().isCUOrStorage();
}
/**
*
* @return {@code true} if this row represents an HU that is a source-HU for fine-picking.
*/
public boolean isPickingSourceHURow()
{
return pickingSlotRowId.isPickingSourceHURow();
}
public WarehouseId getPickingSlotWarehouseId()
{
return pickingSlotWarehouse != null ? WarehouseId.ofRepoId(pickingSlotWarehouse.getIdAsInt()) : null;
}
public BigDecimal getHuQtyCU()
{
return huQtyCU;
}
public ProductId getHuProductId()
{ | return huProduct != null ? ProductId.ofRepoId(huProduct.getKeyAsInt()) : null;
}
@Override
public ViewId getIncludedViewId()
{
return includedViewId;
}
public LocatorId getPickingSlotLocatorId()
{
return pickingSlotLocatorId;
}
public int getBPartnerId()
{
return pickingSlotBPartner != null ? pickingSlotBPartner.getIdAsInt() : -1;
}
public int getBPartnerLocationId()
{
return pickingSlotBPLocation != null ? pickingSlotBPLocation.getIdAsInt() : -1;
}
@NonNull
public Optional<PickingSlotRow> findRowMatching(@NonNull final Predicate<PickingSlotRow> predicate)
{
return streamThisRowAndIncludedRowsRecursivelly()
.filter(predicate)
.findFirst();
}
public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId)
{
final HuId huId = getHuId();
if (huId == null)
{
throw new AdempiereException("Not a PickedHURow!")
.appendParametersToMessage()
.setParameter("PickingSlotRow", this);
}
final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId);
if (hasOpenPickingForOrderId)
{
return true;
}
if (isLU())
{
return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId))
.isPresent();
}
return false;
}
@NonNull
private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId)
{
return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId))
.orElse(ImmutableSet.of());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java | 1 |
请完成以下Java代码 | public int getAD_Client_ID()
{
return ad_Client_ID;
}
@Override
public final void initialize(final ModelValidationEngine engine, final MClient client)
{
if (client != null)
{
ad_Client_ID = client.getAD_Client_ID();
}
engine.addModelChange(I_C_InvoiceLine.Table_Name, this);
// register this service for callouts and model validators
Services.registerService(IInvoiceLineBL.class, new InvoiceLineBL());
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing to do
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
// nothing to do
return null;
}
@Override
public String modelChange(final PO po, int type)
{
assert po instanceof MInvoiceLine : po;
if (type == TYPE_BEFORE_CHANGE || type == TYPE_BEFORE_NEW)
{
final IInvoiceLineBL invoiceLineBL = Services.get(IInvoiceLineBL.class);
final I_C_InvoiceLine il = InterfaceWrapperHelper.create(po, I_C_InvoiceLine.class);
if (!il.isProcessed())
{
logger.debug("Reevaluating tax for " + il);
invoiceLineBL.setTaxBasedOnShipment(il, po.get_TrxName());
logger.debug("Setting TaxAmtInfo for " + il);
invoiceLineBL.setTaxAmtInfo(po.getCtx(), il, po.get_TrxName());
}
// Introduced by US1184, because having the same price on Order and Invoice is enforced by German Law
if (invoiceLineBL.isPriceLocked(il))
{ | assertOrderInvoicePricesMatch(il);
}
}
else if (type == TYPE_BEFORE_DELETE)
{
final I_C_InvoiceLine il = InterfaceWrapperHelper.create(po, I_C_InvoiceLine.class);
beforeDelete(il);
}
return null;
}
void beforeDelete(final org.compiere.model.I_C_InvoiceLine invoiceLine)
{
final IInvoiceDAO invoiceDAO = Services.get(IInvoiceDAO.class);
final InvoiceAndLineId invoiceAndLineId = InvoiceAndLineId.ofRepoId(invoiceLine.getC_Invoice_ID(), invoiceLine.getC_InvoiceLine_ID());
for (final I_C_InvoiceLine refInvoiceLine : invoiceDAO.retrieveReferringLines(invoiceAndLineId))
{
refInvoiceLine.setRef_InvoiceLine_ID(0);
invoiceDAO.save(refInvoiceLine);
}
}
public static void assertOrderInvoicePricesMatch(final I_C_InvoiceLine invoiceLine)
{
final I_C_OrderLine oline = invoiceLine.getC_OrderLine();
if (invoiceLine.getPriceActual().compareTo(oline.getPriceActual()) != 0)
{
throw new OrderInvoicePricesNotMatchException(I_C_InvoiceLine.COLUMNNAME_PriceActual, oline.getPriceActual(), invoiceLine.getPriceActual());
}
if (invoiceLine.getPriceList().compareTo(oline.getPriceList()) != 0)
{
throw new OrderInvoicePricesNotMatchException(I_C_InvoiceLine.COLUMNNAME_PriceList, oline.getPriceList(), invoiceLine.getPriceList());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\InvoiceLine.java | 1 |
请完成以下Java代码 | public @Nullable List<String> get(String headerName) {
validateAllowedHeaderName(headerName);
List<String> headerValues = super.get(headerName);
if (headerValues == null) {
return headerValues;
}
for (String headerValue : headerValues) {
validateAllowedHeaderValue(headerName, headerValue);
}
return headerValues;
}
@Override
public Set<String> headerNames() {
Set<String> headerNames = super.headerNames();
for (String headerName : headerNames) {
validateAllowedHeaderName(headerName);
}
return headerNames;
}
}
private final class StrictFirewallBuilder implements Builder {
private final Builder delegate;
private StrictFirewallBuilder(Builder delegate) {
this.delegate = delegate;
}
@Override
public Builder method(HttpMethod httpMethod) {
return new StrictFirewallBuilder(this.delegate.method(httpMethod));
}
@Override
public Builder uri(URI uri) {
return new StrictFirewallBuilder(this.delegate.uri(uri));
}
@Override
public Builder path(String path) {
return new StrictFirewallBuilder(this.delegate.path(path));
}
@Override
public Builder contextPath(String contextPath) {
return new StrictFirewallBuilder(this.delegate.contextPath(contextPath));
}
@Override | public Builder header(String headerName, String... headerValues) {
return new StrictFirewallBuilder(this.delegate.header(headerName, headerValues));
}
@Override
public Builder headers(Consumer<HttpHeaders> headersConsumer) {
return new StrictFirewallBuilder(this.delegate.headers(headersConsumer));
}
@Override
public Builder sslInfo(SslInfo sslInfo) {
return new StrictFirewallBuilder(this.delegate.sslInfo(sslInfo));
}
@Override
public Builder remoteAddress(InetSocketAddress remoteAddress) {
return new StrictFirewallBuilder(this.delegate.remoteAddress(remoteAddress));
}
@Override
public Builder localAddress(InetSocketAddress localAddress) {
return new StrictFirewallBuilder(this.delegate.localAddress(localAddress));
}
@Override
public ServerHttpRequest build() {
return new StrictFirewallHttpRequest(this.delegate.build());
}
}
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\firewall\StrictServerWebExchangeFirewall.java | 1 |
请完成以下Java代码 | private static byte[] toPngData(final BufferedImage image, final int width)
{
if (image == null)
{
return null;
}
BufferedImage imageScaled;
final int widthOrig = image.getWidth();
final int heightOrig = image.getHeight();
if (width > 0 && widthOrig > 0)
{
final double scale = (double)width / (double)widthOrig;
final int height = (int)(heightOrig * scale);
imageScaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
final AffineTransform at = new AffineTransform();
at.scale(scale, scale);
final AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
imageScaled = scaleOp.filter(image, imageScaled); | }
else
{
imageScaled = image;
}
final ByteArrayOutputStream pngBuf = new ByteArrayOutputStream();
try
{
ImageIO.write(imageScaled, "png", pngBuf);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
return pngBuf.toByteArray();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ImagesServlet.java | 1 |
请完成以下Java代码 | public void performDataAuditForRequest(final GenericDataExportAuditRequest genericDataExportAuditRequest)
{
if (!isHandled(genericDataExportAuditRequest))
{
return;
}
final Object exportedObject = genericDataExportAuditRequest.getExportedObject();
final Optional<JsonExternalReferenceLookupResponse> jsonExternalReferenceLookupResponse = JsonMapperUtil.tryDeserializeToType(exportedObject, JsonExternalReferenceLookupResponse.class);
final ExternalSystemParentConfigId externalSystemParentConfigId = genericDataExportAuditRequest.getExternalSystemParentConfigId();
final PInstanceId pInstanceId = genericDataExportAuditRequest.getPInstanceId();
jsonExternalReferenceLookupResponse.ifPresent(lookupResponse -> lookupResponse.getItems()
.forEach(item -> auditExternalReference(item, externalSystemParentConfigId, pInstanceId)));
}
@Override
public boolean isHandled(final GenericDataExportAuditRequest genericDataExportAuditRequest)
{
final AntPathMatcher antPathMatcher = new AntPathMatcher();
return antPathMatcher.match(EXTERNAL_REFERENCE_RESOURCE, genericDataExportAuditRequest.getRequestURI());
}
private void auditExternalReference( | @NonNull final JsonExternalReferenceItem jsonExternalReferenceItem,
@Nullable final ExternalSystemParentConfigId externalSystemParentConfigId,
@Nullable final PInstanceId pInstanceId)
{
if (jsonExternalReferenceItem.getExternalReferenceId() == null)
{
return;
}
final DataExportAuditRequest jsonExternalReferenceItemRequest = DataExportAuditRequest.builder()
.tableRecordReference(TableRecordReference.of(I_S_ExternalReference.Table_Name, jsonExternalReferenceItem.getExternalReferenceId().getValue()))
.action(Action.Standalone)
.externalSystemConfigId(externalSystemParentConfigId)
.adPInstanceId(pInstanceId)
.build();
dataExportAuditService.createExportAudit(jsonExternalReferenceItemRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\audit\ExternalReferenceAuditService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private final void assertCanAddPart(final PackingItemPart part)
{
if (parts.isEmpty())
{
return;
}
if (!PackingItemGroupingKey.equals(groupingKey, computeGroupingKey(part)))
{
throw new AdempiereException(part + " can't be added to " + this);
}
}
@Override
public final PackingItemGroupingKey getGroupingKey()
{
return groupingKey;
}
@Override
public final ProductId getProductId()
{
return groupingKey.getProductId();
}
@Override
public final I_C_UOM getC_UOM()
{
return uom;
}
@Override
public boolean isSameAs(final IPackingItem item)
{
return Util.same(this, item);
}
@Override
public BPartnerId getBPartnerId()
{
return getBPartnerLocationId().getBpartnerId();
}
@Override
public BPartnerLocationId getBPartnerLocationId()
{
return groupingKey.getBpartnerLocationId();
}
@Override
public HUPIItemProductId getPackingMaterialId()
{
return groupingKey.getPackingMaterialId();
} | @Override
public Set<WarehouseId> getWarehouseIds()
{
return parts.map(PackingItemPart::getWarehouseId).collect(ImmutableSet.toImmutableSet());
}
@Override
public Set<ShipmentScheduleId> getShipmentScheduleIds()
{
return parts.map(PackingItemPart::getShipmentScheduleId).collect(ImmutableSet.toImmutableSet());
}
@Override
public IPackingItem subtractToPackingItem(
@NonNull final Quantity subtrahent,
@Nullable final Predicate<PackingItemPart> acceptPartPredicate)
{
final PackingItemParts subtractedParts = subtract(subtrahent, acceptPartPredicate);
return PackingItems.newPackingItem(subtractedParts);
}
@Override
public PackingItem copy()
{
return new PackingItem(this);
}
@Override
public String toString()
{
return "FreshPackingItem ["
+ "qtySum=" + getQtySum()
+ ", productId=" + getProductId()
+ ", uom=" + getC_UOM() + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItem.java | 2 |
请完成以下Java代码 | public Segment enableNumberQuantifierRecognize(boolean enable)
{
config.numberQuantifierRecognize = enable;
return this;
}
/**
* 是否启用所有的命名实体识别
*
* @param enable
* @return
*/
public Segment enableAllNamedEntityRecognize(boolean enable)
{
config.nameRecognize = enable;
config.japaneseNameRecognize = enable;
config.translatedNameRecognize = enable;
config.placeRecognize = enable;
config.organizationRecognize = enable;
config.updateNerConfig();
return this;
}
class WorkThread extends Thread
{
String[] sentenceArray;
List<Term>[] termListArray;
int from;
int to;
public WorkThread(String[] sentenceArray, List<Term>[] termListArray, int from, int to)
{
this.sentenceArray = sentenceArray;
this.termListArray = termListArray;
this.from = from;
this.to = to;
}
@Override
public void run()
{
for (int i = from; i < to; ++i)
{ | termListArray[i] = segSentence(sentenceArray[i].toCharArray());
}
}
}
/**
* 开启多线程
*
* @param enable true表示开启[系统CPU核心数]个线程,false表示单线程
* @return
*/
public Segment enableMultithreading(boolean enable)
{
if (enable) config.threadNumber = Runtime.getRuntime().availableProcessors();
else config.threadNumber = 1;
return this;
}
/**
* 开启多线程
*
* @param threadNumber 线程数量
* @return
*/
public Segment enableMultithreading(int threadNumber)
{
config.threadNumber = threadNumber;
return this;
}
/**
* 是否执行字符正规化(繁体->简体,全角->半角,大写->小写),切换配置后必须删CustomDictionary.txt.bin缓存
*/
public Segment enableNormalization(boolean normalization)
{
config.normalization = normalization;
return this;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Segment.java | 1 |
请完成以下Java代码 | private boolean isOrderPaySelectionLine(@NonNull final I_C_PaySelectionLine line)
{
return paySelectionBL.extractType(line) == PaySelectionLineType.Order;
}
private boolean isInvoicePaySelectionLine(@NonNull final I_C_PaySelectionLine line)
{
return paySelectionBL.extractType(line) == PaySelectionLineType.Invoice;
}
private static @Nullable String toNullOrRemoveSpaces(@Nullable final String from)
{
final String fromNorm = StringUtils.trimBlankToNull(from);
return fromNorm != null ? fromNorm.replace(" ", "") : null;
}
@NonNull
private static String extractIBAN(@NonNull final BankAccount bpBankAccount)
{
final String iban = coalesceSuppliers(
() -> toNullOrRemoveSpaces(bpBankAccount.getIBAN()),
() -> toNullOrRemoveSpaces(bpBankAccount.getQR_IBAN())
);
if (Check.isBlank(iban))
{
throw new AdempiereException(ERR_C_BP_BankAccount_IBANNotSet, bpBankAccount);
}
return iban;
}
@NonNull
private CreateSEPAExportFromPaySelectionCommand.InvoicePaySelectionLinesAggregationKey extractPaySelectionLinesKey(@NonNull final I_C_PaySelectionLine paySelectionLine)
{
final BankAccountId bankAccountId = BankAccountId.ofRepoId(paySelectionLine.getC_BP_BankAccount_ID());
final BankAccount bpBankAccount = bankAccountDAO.getById(bankAccountId);
return InvoicePaySelectionLinesAggregationKey.builder()
.orgId(OrgId.ofRepoId(paySelectionLine.getAD_Org_ID()))
.partnerId(BPartnerId.ofRepoId(paySelectionLine.getC_BPartner_ID()))
.bankAccountId(bankAccountId)
.currencyId(bpBankAccount.getCurrencyId())
.iban(extractIBAN(bpBankAccount))
.swiftCode(extractSwiftCode(bpBankAccount))
.build();
} | private @Nullable String extractSwiftCode(@NonNull final BankAccount bpBankAccount)
{
return Optional.ofNullable(bpBankAccount.getBankId())
.map(bankRepo::getById)
.map(bank -> toNullOrRemoveSpaces(bank.getSwiftCode()))
.orElse(null);
}
@Value
@Builder
private static class InvoicePaySelectionLinesAggregationKey
{
@NonNull OrgId orgId;
@NonNull BPartnerId partnerId;
@NonNull BankAccountId bankAccountId;
@NonNull CurrencyId currencyId;
@NonNull String iban;
@Nullable String swiftCode;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\api\impl\CreateSEPAExportFromPaySelectionCommand.java | 1 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UPC/EAN.
@param UPC
Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number)
*/
@Override
public void setUPC (java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC); | }
/** Get UPC/EAN.
@return Produktidentifikation (Barcode) durch Universal Product Code oder European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
/** Set Verwendet für Kunden.
@param UsedForCustomer Verwendet für Kunden */
@Override
public void setUsedForCustomer (boolean UsedForCustomer)
{
set_Value (COLUMNNAME_UsedForCustomer, Boolean.valueOf(UsedForCustomer));
}
/** Get Verwendet für Kunden.
@return Verwendet für Kunden */
@Override
public boolean isUsedForCustomer ()
{
Object oo = get_Value(COLUMNNAME_UsedForCustomer);
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.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_EDI_M_Product_Lookup_UPC_v.java | 1 |
请完成以下Java代码 | public class IntermediateThrowSignalEventActivityBehavior extends AbstractBpmnActivityBehavior {
private static final long serialVersionUID = 1L;
protected final SignalEventDefinition signalEventDefinition;
protected String signalEventName;
protected String signalExpression;
protected boolean processInstanceScope;
public IntermediateThrowSignalEventActivityBehavior(SignalEventDefinition signalEventDefinition, Signal signal) {
if (signal != null) {
signalEventName = signal.getName();
if (Signal.SCOPE_PROCESS_INSTANCE.equals(signal.getScope())) {
this.processInstanceScope = true;
}
} else if (StringUtils.isNotEmpty(signalEventDefinition.getSignalRef())) {
signalEventName = signalEventDefinition.getSignalRef();
} else {
signalExpression = signalEventDefinition.getSignalExpression();
}
this.signalEventDefinition = signalEventDefinition;
}
public void execute(DelegateExecution execution) {
CommandContext commandContext = Context.getCommandContext();
String eventSubscriptionName = null;
if (signalEventName != null) {
eventSubscriptionName = signalEventName;
} else {
Expression expressionObject = commandContext
.getProcessEngineConfiguration()
.getExpressionManager()
.createExpression(signalExpression);
eventSubscriptionName = expressionObject.getValue(execution).toString();
}
EventSubscriptionEntityManager eventSubscriptionEntityManager =
commandContext.getEventSubscriptionEntityManager();
List<SignalEventSubscriptionEntity> subscriptionEntities = null;
if (processInstanceScope) {
subscriptionEntities =
eventSubscriptionEntityManager.findSignalEventSubscriptionsByProcessInstanceAndEventName( | execution.getProcessInstanceId(),
eventSubscriptionName
);
} else {
subscriptionEntities = eventSubscriptionEntityManager.findSignalEventSubscriptionsByEventName(
eventSubscriptionName,
execution.getTenantId()
);
}
for (SignalEventSubscriptionEntity signalEventSubscriptionEntity : subscriptionEntities) {
Map<String, Object> signalVariables = Optional.ofNullable(execution.getVariables())
.filter(it -> !it.isEmpty())
.orElse(null);
eventSubscriptionEntityManager.eventReceived(
signalEventSubscriptionEntity,
signalVariables,
signalEventDefinition.isAsync()
);
}
Context.getAgenda().planTakeOutgoingSequenceFlowsOperation((ExecutionEntity) execution, true);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\IntermediateThrowSignalEventActivityBehavior.java | 1 |
请完成以下Java代码 | public static String getMoneyIntoWords(String input) {
MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
return converter.asWords(new BigDecimal(input));
}
public static String getMoneyIntoWords(final double money) {
long dollar = (long) money;
long cents = Math.round((money - dollar) * 100);
if (money == 0D) {
return "";
}
if (money < 0) {
return INVALID_INPUT_GIVEN;
}
String dollarPart = "";
if (dollar > 0) {
dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
}
String centsPart = "";
if (cents > 0) {
if (dollarPart.length() > 0) {
centsPart = " and ";
}
centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
}
return dollarPart + centsPart;
}
private static String convert(final long n) {
if (n < 0) {
return INVALID_INPUT_GIVEN;
} | if (n < 20) {
return ones[(int) n];
}
if (n < 100) {
return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
}
if (n < 1000) {
return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 1_000_000) {
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 1_000_000_000) {
return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
}
return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\numberwordconverter\NumberWordConverter.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.