instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public void setBankAccountNumber(String value) {
this.bankAccountNumber = value;
}
/**
* Gets the value of the bankAccountHolder property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankAccountHolder() {
return bankAccountHolder;
}
/**
* Sets the value of the bankAccountHolder property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankAccountHolder(String value) {
this.bankAccountHolder = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIban() {
return iban;
}
/** | * Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIban(String value) {
this.iban = value;
}
/**
* Gets the value of the bic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBic() {
return bic;
}
/**
* Sets the value of the bic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBic(String value) {
this.bic = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Cod.java | 2 |
请完成以下Java代码 | public class CycleBusinessCalendar extends BusinessCalendarImpl {
public static String NAME = "cycle";
public CycleBusinessCalendar(ClockReader clockReader) {
super(clockReader);
}
public Date resolveDuedate(String duedateDescription, int maxIterations) {
try {
if (duedateDescription != null && duedateDescription.startsWith("R")) {
return new DurationHelper(duedateDescription, maxIterations, clockReader).getDateAfter();
} else {
CronExpression ce = new CronExpression(duedateDescription, clockReader);
return ce.getTimeAfter(clockReader.getCurrentTime());
}
} catch (Exception e) {
throw new ActivitiException("Failed to parse cron expression: " + duedateDescription, e);
} | }
public Boolean validateDuedate(String duedateDescription, int maxIterations, Date endDate, Date newTimer) {
if (endDate != null) {
return super.validateDuedate(duedateDescription, maxIterations, endDate, newTimer);
}
// end date could be part of the chron expression
try {
if (duedateDescription != null && duedateDescription.startsWith("R")) {
return new DurationHelper(duedateDescription, maxIterations, clockReader).isValidDate(newTimer);
} else {
return true;
}
} catch (Exception e) {
throw new ActivitiException("Failed to parse cron expression: " + duedateDescription, e);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\calendar\CycleBusinessCalendar.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class GsonHttpConvertersCustomizer
implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer {
private final GsonHttpMessageConverter converter;
GsonHttpConvertersCustomizer(Gson gson) {
this.converter = new GsonHttpMessageConverter(gson);
}
@Override
public void customize(ClientBuilder builder) {
builder.withJsonConverter(this.converter);
}
@Override
public void customize(ServerBuilder builder) {
builder.withJsonConverter(this.converter);
}
}
private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition {
PreferGsonOrJacksonAndJsonbUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "gson")
static class GsonPreferred {
}
@Conditional(JacksonAndJsonbUnavailableCondition.class)
static class JacksonJsonbUnavailable {
}
}
private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions {
JacksonAndJsonbUnavailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
} | @ConditionalOnBean(JacksonHttpMessageConvertersConfiguration.JacksonJsonHttpMessageConvertersCustomizer.class)
static class JacksonAvailable {
}
@SuppressWarnings("removal")
@ConditionalOnBean(Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class)
static class Jackson2Available {
}
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jsonb")
static class JsonbPreferred {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\GsonHttpMessageConvertersConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CmmnDeployer implements EngineDeployer {
private static final Logger LOGGER = LoggerFactory.getLogger(CmmnDeployer.class);
public static final int CMMN_DEFAULT_UNDEPLOY_ORDER = EngineDeployer.DEFAULT_UNDEPLOY_ORDER - 200;
@Override
public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) {
if (!deployment.isNew()) {
return;
}
LOGGER.debug("CmmnDeployer: processing deployment {}", deployment.getName());
CmmnDeploymentBuilder cmmnDeploymentBuilder = null;
Map<String, EngineResource> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
if (org.flowable.cmmn.engine.impl.deployer.CmmnDeployer.isCmmnResource(resourceName)) {
LOGGER.info("CmmnDeployer: processing resource {}", resourceName);
if (cmmnDeploymentBuilder == null) {
CmmnRepositoryService cmmnRepositoryService = CommandContextUtil.getCmmnRepositoryService();
cmmnDeploymentBuilder = cmmnRepositoryService.createDeployment().name(deployment.getName());
}
cmmnDeploymentBuilder.addBytes(resourceName, resources.get(resourceName).getBytes());
}
}
if (cmmnDeploymentBuilder != null) {
cmmnDeploymentBuilder.parentDeploymentId(deployment.getId());
cmmnDeploymentBuilder.key(deployment.getKey());
if (deployment.getTenantId() != null && deployment.getTenantId().length() > 0) {
cmmnDeploymentBuilder.tenantId(deployment.getTenantId());
} | cmmnDeploymentBuilder.deploy();
}
}
@Override
public void undeploy(EngineDeployment parentDeployment, boolean cascade) {
CmmnRepositoryService repositoryService = CommandContextUtil.getCmmnRepositoryService();
List<CmmnDeployment> deployments = repositoryService
.createDeploymentQuery()
.parentDeploymentId(parentDeployment.getId())
.list();
for (CmmnDeployment deployment : deployments) {
repositoryService.deleteDeployment(deployment.getId(), cascade);
}
}
@Override
public int getUndeployOrder() {
return CMMN_DEFAULT_UNDEPLOY_ORDER;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine-configurator\src\main\java\org\flowable\cmmn\engine\configurator\impl\deployer\CmmnDeployer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CreateRemittanceAdviceRequest
{
@NonNull
OrgId orgId;
@NonNull
ClientId clientId;
@NonNull
BPartnerId sourceBPartnerId;
@NonNull
BPartnerBankAccountId sourceBPartnerBankAccountId;
@NonNull
BPartnerId destinationBPartnerId;
@NonNull
BPartnerBankAccountId destinationBPartnerBankAccountId;
@NonNull
String documentNumber;
@NonNull
String externalDocumentNumber;
@NonNull
Instant documentDate;
@NonNull
DocTypeId docTypeId;
@NonNull | BigDecimal remittedAmountSum;
@NonNull
CurrencyId remittedAmountCurrencyId;
@NonNull
DocTypeId targetPaymentDocTypeId;
@Nullable
Instant sendDate;
@Nullable
BigDecimal serviceFeeAmount;
@Nullable
CurrencyId serviceFeeCurrencyId;
@Nullable
BigDecimal paymentDiscountAmountSum;
@Nullable
String additionalNotes;
boolean isImported;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\CreateRemittanceAdviceRequest.java | 2 |
请完成以下Java代码 | public class TerminateEventDefinition extends EventDefinition {
/**
* When true, this event will terminate all parent process instances (in the case of using call activity),
* thus ending the whole process instance.
*
* By default false (BPMN spec compliant): the parent scope is terminated (subprocess: embedded or call activity)
*/
protected boolean terminateAll;
/**
* When true (and used within a multi instance), this event will terminate all multi instance instances
* of the embedded subprocess/call activity this event is used in.
*
* In case of nested multi instance, only the first parent multi instance structure will be destroyed.
* In case of 'true' and not being in a multi instance construction: executes the default behavior.
*
* Note: if terminate all is set to true, this will have precedence over this.
*/
protected boolean terminateMultiInstance;
public TerminateEventDefinition clone() {
TerminateEventDefinition clone = new TerminateEventDefinition();
clone.setValues(this);
return clone;
}
public void setValues(TerminateEventDefinition otherDefinition) {
super.setValues(otherDefinition); | this.terminateAll = otherDefinition.isTerminateAll();
this.terminateMultiInstance = otherDefinition.isTerminateMultiInstance();
}
public boolean isTerminateAll() {
return terminateAll;
}
public void setTerminateAll(boolean terminateAll) {
this.terminateAll = terminateAll;
}
public boolean isTerminateMultiInstance() {
return terminateMultiInstance;
}
public void setTerminateMultiInstance(boolean terminateMultiInstance) {
this.terminateMultiInstance = terminateMultiInstance;
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\TerminateEventDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class ModelColumn<MT, CMT>
{
/**
* Model class.
* e.g. if we are talking about C_Invoice.C_BPartner_ID field then this method will return I_C_Invoice.class
*/
private final Class<MT> modelClass;
/**
* Column Name.
* e.g. if we are talking about C_Invoice.C_BPartner_ID field then this method will return "C_BPartner_ID"
*/
private final String columnName;
/**
* Column's model class or null.
* e.g. if we are talking about C_Invoice.C_BPartner_ID field then this method will return I_C_BPartner.class
*/
private final Class<CMT> columnModelType;
@NonFinal
private transient String _modelTableName = null; // lazy loaded on demand
public ModelColumn(
@NonNull final Class<MT> modelClass,
@NonNull final String columnName,
@Nullable final Class<CMT> columnModelType)
{
this.modelClass = modelClass;
this.columnName = columnName;
this.columnModelType = columnModelType;
}
/**
* Gets model table name.
* e.g. if we are talking about I_C_Invoice model class then this method will return "C_Invoice" (i.e. I_C_Invoice.Table_Name)
*/
public String getTableName()
{
String modelTableName = _modelTableName;
if (modelTableName == null)
{
modelTableName = _modelTableName = InterfaceWrapperHelper.getTableName(modelClass);
}
return modelTableName;
}
/**
* @return function which gets the column value from model.
*/
public final <ValueType> Function<MT, ValueType> asValueFunction()
{ | // NOTE: we are returning a new instance each time, because this method is not used so offen
// and because storing an instace for each ModelColumn will consume way more memory.
final Function<MT, Object> valueFunction = new ValueFunction();
@SuppressWarnings("unchecked")
final Function<MT, ValueType> valueFunctionCasted = (Function<MT, ValueType>)valueFunction;
return valueFunctionCasted;
}
/**
* Function which gets the Value of this model column.
*
* @author tsa
*/
private final class ValueFunction implements Function<MT, Object>
{
@Override
public Object apply(final MT model)
{
final Object value = InterfaceWrapperHelper.getValue(model, columnName).orElse(null);
return value;
}
@Override
public String toString()
{
return "ValueFunction[" + modelClass + " -> " + columnName + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\model\ModelColumn.java | 2 |
请完成以下Java代码 | public class UpdateInvalidShipmentSchedulesWorkpackageProcessor extends WorkpackageProcessorAdapter
{
private static final Logger logger = LogManager.getLogger(UpdateInvalidShipmentSchedulesWorkpackageProcessor.class);
public static void schedule()
{
final IContextAware contextAwareWithThreadInherit = PlainContextAware.newWithThreadInheritedTrx();
final ShipmentSchedulesUpdateSchedulerRequest request = ShipmentSchedulesUpdateSchedulerRequest.builder()
.ctx(contextAwareWithThreadInherit.getCtx())
.trxName(contextAwareWithThreadInherit.getTrxName())
.build();
_schedule(request);
}
public static void schedule(@NonNull final ShipmentSchedulesUpdateSchedulerRequest request)
{
_schedule(request);
}
private static void _schedule(@NonNull final ShipmentSchedulesUpdateSchedulerRequest request)
{
SCHEDULER.schedule(request);
}
private static final UpdateInvalidShipmentSchedulesScheduler //
SCHEDULER = new UpdateInvalidShipmentSchedulesScheduler(true /*createOneWorkpackagePerAsyncBatch*/);
// services
private final transient IShipmentScheduleUpdater shipmentScheduleUpdater = Services.get(IShipmentScheduleUpdater.class);
@Override
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName_NOTUSED)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG); | final PInstanceId selectionId = Services.get(IADPInstanceDAO.class).createSelectionId();
loggable.addLog("Using revalidation ID: {}", selectionId);
try (final MDCCloseable ignored = ShipmentSchedulesMDC.putRevalidationId(selectionId))
{
final ShipmentScheduleUpdateInvalidRequest request = ShipmentScheduleUpdateInvalidRequest.builder()
.ctx(InterfaceWrapperHelper.getCtx(workpackage))
.selectionId(selectionId)
.createMissingShipmentSchedules(false) // don't create missing schedules; for that we have CreateMissingShipmentSchedulesWorkpackageProcessor
.build();
loggable.addLog("Starting revalidation for {}", request);
final int updatedCount = shipmentScheduleUpdater.updateShipmentSchedules(request);
loggable.addLog("Updated {} shipment schedule entries for {}", updatedCount, request);
return Result.SUCCESS;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\async\UpdateInvalidShipmentSchedulesWorkpackageProcessor.java | 1 |
请完成以下Java代码 | public class SAP_GLJournal_GenerateTaxLines extends JavaProcess implements IProcessPrecondition
{
private final SAPGLJournalService glJournalService = SpringContextHolder.instance.getBean(SAPGLJournalService.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(context.getSingleSelectedRecordId());
final DocStatus docStatus = glJournalService.getDocStatus(glJournalId);
if (!docStatus.isDraftedOrInProgress()) | {
return ProcessPreconditionsResolution.rejectWithInternalReason("Not drafted");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final SAPGLJournalId glJournalId = SAPGLJournalId.ofRepoId(getRecord_ID());
glJournalService.regenerateTaxLines(glJournalId);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\process\SAP_GLJournal_GenerateTaxLines.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HazardSymbolId implements RepoIdAware
{
int repoId;
@JsonCreator
public static HazardSymbolId ofRepoId(final int repoId)
{
return new HazardSymbolId(repoId);
}
@Nullable
public static HazardSymbolId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new HazardSymbolId(repoId) : null;
}
@Nullable
public static HazardSymbolId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new HazardSymbolId(repoId) : null;
}
public static int toRepoId(@Nullable final HazardSymbolId HazardSymbolId)
{
return HazardSymbolId != null ? HazardSymbolId.getRepoId() : -1;
} | public static boolean equals(@Nullable final HazardSymbolId o1, @Nullable final HazardSymbolId o2)
{
return Objects.equals(o1, o2);
}
private HazardSymbolId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HazardSymbol_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\hazard_symbol\HazardSymbolId.java | 2 |
请完成以下Java代码 | protected InvoiceRows getRowsData()
{
return InvoiceRows.cast(super.getRowsData());
}
public void addInvoice(@NonNull final InvoiceId invoiceId)
{
final InvoiceRows invoiceRows = getRowsData();
invoiceRows.addInvoice(invoiceId);
}
@Override
public LookupValuesPage getFieldTypeahead(final RowEditingContext ctx, final String fieldName, final String query)
{
throw new UnsupportedOperationException();
} | @Override
public LookupValuesList getFieldDropdown(final RowEditingContext ctx, final String fieldName)
{
throw new UnsupportedOperationException();
}
public void markPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
getRowsData().markPreparedForAllocation(rowIds);
invalidateAll();
}
public void unmarkPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
getRowsData().unmarkPreparedForAllocation(rowIds);
invalidateAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoicesView.java | 1 |
请完成以下Java代码 | public class RestLoginProcessingFilter extends AbstractAuthenticationProcessingFilter {
private final AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new RestAuthenticationDetailsSource();
private final AuthenticationSuccessHandler successHandler;
private final AuthenticationFailureHandler failureHandler;
public RestLoginProcessingFilter(String defaultProcessUrl, AuthenticationSuccessHandler successHandler,
AuthenticationFailureHandler failureHandler) {
super(defaultProcessUrl);
this.successHandler = successHandler;
this.failureHandler = failureHandler;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
if (!HttpMethod.POST.name().equals(request.getMethod())) {
if(log.isDebugEnabled()) {
log.debug("Authentication method not supported. Request method: " + request.getMethod());
}
throw new AuthMethodNotSupportedException("Authentication method not supported");
}
LoginRequest loginRequest;
try {
loginRequest = JacksonUtil.fromReader(request.getReader(), LoginRequest.class);
} catch (Exception e) {
throw new AuthenticationServiceException("Invalid login request payload");
} | if (StringUtils.isBlank(loginRequest.getUsername()) || StringUtils.isEmpty(loginRequest.getPassword())) {
throw new AuthenticationServiceException("Username or Password not provided");
}
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, loginRequest.getUsername());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal, loginRequest.getPassword());
token.setDetails(authenticationDetailsSource.buildDetails(request));
return this.getAuthenticationManager().authenticate(token);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
successHandler.onAuthenticationSuccess(request, response, authResult);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
SecurityContextHolder.clearContext();
failureHandler.onAuthenticationFailure(request, response, failed);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\rest\RestLoginProcessingFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ADProcessName
{
String value;
String classname;
String missing;
public static ADProcessName missing(@NonNull final AdProcessId adProcessId)
{
return builder().missing("<" + adProcessId.getRepoId() + ">").build();
}
@Override
public String toString() {return toShortString();}
public String toShortString()
{
if (missing != null) | {
return missing;
}
else
{
final StringBuilder sb = new StringBuilder();
sb.append(value);
if (!Check.isBlank(classname))
{
sb.append("(").append(classname).append(")");
}
return sb.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\names\ADProcessName.java | 2 |
请完成以下Java代码 | public abstract class AbstractElResolverDelegate extends ELResolver {
protected abstract ELResolver getElResolverDelegate();
public Class<?> getCommonPropertyType(ELContext context, Object base) {
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.getCommonPropertyType(context, base);
}
}
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return Collections.<FeatureDescriptor>emptySet().iterator();
} else {
return delegate.getFeatureDescriptors(context, base);
}
}
public Class<?> getType(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.getType(context, base, property);
}
}
public Object getValue(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.getValue(context, base, property);
}
}
public boolean isReadOnly(ELContext context, Object base, Object property) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return true;
} else {
return delegate.isReadOnly(context, base, property); | }
}
public void setValue(ELContext context, Object base, Object property, Object value) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate != null) {
delegate.setValue(context, base, property, value);
}
}
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) {
context.setPropertyResolved(false);
ELResolver delegate = getElResolverDelegate();
if(delegate == null) {
return null;
} else {
return delegate.invoke(context, base, method, paramTypes, params);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\AbstractElResolverDelegate.java | 1 |
请完成以下Java代码 | public final int compareTo(Object o)
{
return compare(this, o);
} // compareTo
/**
* Comparable Interface (based on toString value)
*
* @param o the Object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
public final int compareTo(NamePair o)
{
return compare(this, o);
} // compareTo
/**
* To String - returns name
*/
@Override | public String toString()
{
return m_name;
}
/**
* To String - detail
*
* @return String in format ID=Name
*/
public final String toStringX()
{
StringBuilder sb = new StringBuilder(getID());
sb.append("=").append(m_name);
return sb.toString();
} // toStringX
} // NamePair | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\NamePair.java | 1 |
请完成以下Java代码 | public static <T> SynchronizedMutable<T> empty()
{
return new SynchronizedMutable<>(null);
}
@Nullable
private T value;
private SynchronizedMutable(@Nullable final T value)
{
this.value = value;
}
@Nullable
@Override
public synchronized T getValue()
{
return value;
}
@Override
public synchronized void setValue(@Nullable final T value)
{
this.value = value;
}
@Nullable
public synchronized T setValueAndReturnPrevious(final T value)
{
final T previousValue = this.value;
this.value = value;
return previousValue;
}
@Override
public synchronized T compute(@NonNull final UnaryOperator<T> remappingFunction)
{
this.value = remappingFunction.apply(this.value);
return this.value;
}
@SuppressWarnings("unused")
public synchronized OldAndNewValues<T> computeReturningOldAndNew(@NonNull final UnaryOperator<T> remappingFunction)
{
final T oldValue = this.value;
final T newValue = this.value = remappingFunction.apply(oldValue);
return OldAndNewValues.<T>builder()
.oldValue(oldValue)
.newValue(newValue)
.build();
}
@Override
public synchronized T computeIfNull(@NonNull final Supplier<T> supplier)
{ | if (value == null)
{
this.value = supplier.get();
}
return this.value;
}
@Nullable
public synchronized T computeIfNotNull(@NonNull final UnaryOperator<T> remappingFunction)
{
if (value != null)
{
this.value = remappingFunction.apply(this.value);
}
return this.value;
}
public synchronized OldAndNewValues<T> computeIfNotNullReturningOldAndNew(@NonNull final UnaryOperator<T> remappingFunction)
{
if (value != null)
{
final T oldValue = this.value;
this.value = remappingFunction.apply(oldValue);
return OldAndNewValues.<T>builder()
.oldValue(oldValue)
.newValue(this.value)
.build();
}
else
{
return OldAndNewValues.nullValues();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\SynchronizedMutable.java | 1 |
请完成以下Java代码 | public OrderCostAddInOutResult addInOutCost(@NonNull OrderCostAddInOutRequest request)
{
final OrderCostDetail detail = getDetailByOrderLineId(request.getOrderLineId());
final Quantity qty = request.getQty();
final Money amt = request.getCostAmount();
detail.addInOutCost(amt, qty);
return OrderCostAddInOutResult.builder()
.orderCostDetailId(Check.assumeNotNull(detail.getId(), "detail is saved"))
.costAmount(amt)
.qty(qty)
.build();
}
public Money computeInOutCostAmountForQty(
@NonNull final OrderLineId orderLineId,
@NonNull final Quantity qty,
@NonNull final CurrencyPrecision precision)
{
final OrderCostDetail detail = getDetailByOrderLineId(orderLineId);
final Percent percentage = qty.percentageOf(detail.getQtyOrdered());
final Money maxCostAmount = detail.getCostAmount().subtract(detail.getInoutCostAmount()).toZeroIfNegative();
final Money costAmount = detail.getCostAmount().multiply(percentage, precision);
return costAmount.min(maxCostAmount);
}
public Optional<OrderCostDetail> getDetailByOrderLineIdIfExists(final OrderLineId orderLineId)
{
return details.stream()
.filter(detail -> OrderLineId.equals(detail.getOrderLineId(), orderLineId))
.findFirst();
}
public OrderCostDetail getDetailByOrderLineId(final OrderLineId orderLineId)
{
return getDetailByOrderLineIdIfExists(orderLineId)
.orElseThrow(() -> new AdempiereException("No cost detail found for " + orderLineId));
} | public void setCreatedOrderLineId(@Nullable final OrderLineId createdOrderLineId)
{
this.createdOrderLineId = createdOrderLineId;
}
public OrderCost copy(@NonNull final OrderCostCloneMapper mapper)
{
return toBuilder()
.id(null)
.orderId(mapper.getTargetOrderId(orderId))
.createdOrderLineId(createdOrderLineId != null ? mapper.getTargetOrderLineId(createdOrderLineId) : null)
.details(details.stream()
.map(detail -> detail.copy(mapper))
.collect(ImmutableList.toImmutableList()))
.build();
}
public void updateOrderLineInfoIfApplies(
final OrderCostDetailOrderLinePart orderLineInfo,
@NonNull final Function<CurrencyId, CurrencyPrecision> currencyPrecisionProvider,
@NonNull final QuantityUOMConverter uomConverter)
{
final OrderCostDetail detail = getDetailByOrderLineIdIfExists(orderLineInfo.getOrderLineId()).orElse(null);
if (detail == null)
{
return;
}
detail.setOrderLineInfo(orderLineInfo);
updateCostAmount(currencyPrecisionProvider, uomConverter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCost.java | 1 |
请完成以下Java代码 | public long getExpirationSecondTime() {
return expirationSecondTime;
}
/**
* 获取RedisCacheKey
*
* @param key
* @return
*/
public RedisCacheKey getRedisCacheKey(Object key) {
return new RedisCacheKey(key).usePrefix(this.prefix)
.withKeySerializer(redisOperations.getKeySerializer());
}
/** | * 获取RedisCacheKey
*
* @param key
* @return
*/
public String getCacheKey(Object key) {
return new String(getRedisCacheKey(key).getKeyBytes());
}
/**
* 是否强制刷新(走数据库),默认是false
*
* @return
*/
public boolean getForceRefresh() {
return forceRefresh;
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\redis\cache\CustomizedRedisCache.java | 1 |
请完成以下Java代码 | public void setQuoteType (java.lang.String QuoteType)
{
set_ValueNoCheck (COLUMNNAME_QuoteType, QuoteType);
}
/** Get RfQ Type.
@return Request for Quotation Type
*/
@Override
public java.lang.String getQuoteType ()
{
return (java.lang.String)get_Value(COLUMNNAME_QuoteType);
}
@Override
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setSalesRep(org.compiere.model.I_AD_User SalesRep)
{
set_ValueFromPO(COLUMNNAME_SalesRep_ID, org.compiere.model.I_AD_User.class, SalesRep);
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); | else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
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.rfq\src\main\java-gen\de\metas\rfq\model\X_RV_C_RfQ_UnAnswered.java | 1 |
请完成以下Java代码 | protected boolean resolveExclusive(S context) {
return exclusive;
}
protected int resolveRetries(S context) {
return Context.getProcessEngineConfiguration().getDefaultNumberOfRetries();
}
public Date resolveDueDate(S context) {
ProcessEngineConfiguration processEngineConfiguration = Context.getProcessEngineConfiguration();
if (processEngineConfiguration != null && (processEngineConfiguration.isJobExecutorAcquireByDueDate() || processEngineConfiguration.isEnsureJobDueDateNotNull())) {
return ClockUtil.getCurrentTime();
}
else {
return null;
}
}
public boolean isExclusive() {
return exclusive;
}
public void setExclusive(boolean exclusive) {
this.exclusive = exclusive;
}
public String getActivityId() {
if (activity != null) {
return activity.getId();
}
else {
return null;
}
}
public ActivityImpl getActivity() {
return activity; | }
public void setActivity(ActivityImpl activity) {
this.activity = activity;
}
public ProcessDefinitionImpl getProcessDefinition() {
if (activity != null) {
return activity.getProcessDefinition();
}
else {
return null;
}
}
public String getJobConfiguration() {
return jobConfiguration;
}
public void setJobConfiguration(String jobConfiguration) {
this.jobConfiguration = jobConfiguration;
}
public ParameterValueProvider getJobPriorityProvider() {
return jobPriorityProvider;
}
public void setJobPriorityProvider(ParameterValueProvider jobPriorityProvider) {
this.jobPriorityProvider = jobPriorityProvider;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobDeclaration.java | 1 |
请完成以下Java代码 | public ClassBasedFacetCollectorFactory<ModelType> registerFacetCollectorClass(final Class<? extends IFacetCollector<ModelType>> facetCollectorClass)
{
Check.assumeNotNull(facetCollectorClass, "facetCollectorClass not null");
facetCollectorClasses.addIfAbsent(facetCollectorClass);
return this;
}
@SafeVarargs
public final ClassBasedFacetCollectorFactory<ModelType> registerFacetCollectorClasses(final Class<? extends IFacetCollector<ModelType>>... facetCollectorClasses)
{
if (facetCollectorClasses == null || facetCollectorClasses.length == 0)
{
return this;
}
for (final Class<? extends IFacetCollector<ModelType>> facetCollectorClass : facetCollectorClasses)
{
registerFacetCollectorClass(facetCollectorClass);
}
return this;
}
public IFacetCollector<ModelType> createFacetCollectors()
{
final CompositeFacetCollector<ModelType> collectors = new CompositeFacetCollector<>();
for (final Class<? extends IFacetCollector<ModelType>> collectorClass : facetCollectorClasses)
{
try
{
final IFacetCollector<ModelType> collector = collectorClass.newInstance(); | collectors.addFacetCollector(collector);
}
catch (final Exception e)
{
logger.warn("Failed to instantiate collector " + collectorClass + ". Skip it.", e);
}
}
if (!collectors.hasCollectors())
{
throw new IllegalStateException("No valid facet collector classes were defined");
}
return collectors;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\ClassBasedFacetCollectorFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getBatchType() {
return batchType;
}
@Override
public void setBatchType(String batchType) {
this.batchType = batchType;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date time) {
this.createTime = time;
}
@Override
public Date getCompleteTime() {
return completeTime;
}
@Override
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
@Override
public String getBatchSearchKey() {
return batchSearchKey;
}
@Override
public void setBatchSearchKey(String batchSearchKey) {
this.batchSearchKey = batchSearchKey;
}
@Override
public String getBatchSearchKey2() {
return batchSearchKey2;
}
@Override
public void setBatchSearchKey2(String batchSearchKey2) {
this.batchSearchKey2 = batchSearchKey2;
}
@Override
public String getStatus() {
return status;
}
@Override
public void setStatus(String status) {
this.status = status;
}
@Override
public ByteArrayRef getBatchDocRefId() {
return batchDocRefId;
}
public void setBatchDocRefId(ByteArrayRef batchDocRefId) {
this.batchDocRefId = batchDocRefId;
} | @Override
public String getBatchDocumentJson(String engineType) {
if (batchDocRefId != null) {
byte[] bytes = batchDocRefId.getBytes(engineType);
if (bytes != null) {
return new String(bytes, StandardCharsets.UTF_8);
}
}
return null;
}
@Override
public void setBatchDocumentJson(String batchDocumentJson, String engineType) {
this.batchDocRefId = setByteArrayRef(this.batchDocRefId, BATCH_DOCUMENT_JSON_LABEL, batchDocumentJson, engineType);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
protected static ByteArrayRef setByteArrayRef(ByteArrayRef byteArrayRef, String name, String value, String engineType) {
if (byteArrayRef == null) {
byteArrayRef = new ByteArrayRef();
}
byte[] bytes = null;
if (value != null) {
bytes = value.getBytes(StandardCharsets.UTF_8);
}
byteArrayRef.setValue(name, bytes, engineType);
return byteArrayRef;
}
} | repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchEntityImpl.java | 2 |
请完成以下Java代码 | public OrderFactory poReference(@Nullable final String poReference)
{
assertNotBuilt();
order.setPOReference(poReference);
return this;
}
public OrderFactory salesRepId(@Nullable final UserId salesRepId)
{
assertNotBuilt();
order.setSalesRep_ID(UserId.toRepoId(salesRepId));
return this;
}
public OrderFactory projectId(@Nullable final ProjectId projectId)
{
assertNotBuilt();
order.setC_Project_ID(ProjectId.toRepoId(projectId));
return this;
}
public OrderFactory campaignId(final int campaignId) | {
assertNotBuilt();
order.setC_Campaign_ID(campaignId);
return this;
}
public DocTypeId getDocTypeTargetId()
{
return docTypeTargetId;
}
public void setDocTypeTargetId(final DocTypeId docTypeTargetId)
{
this.docTypeTargetId = docTypeTargetId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommandLineRunner loadData(CustomerRepository repository) {
return (args) -> {
// save a couple of customers
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
// fetch all customers
log.info("Customers found with findAll():");
log.info("-------------------------------");
for (Customer customer : repository.findAll()) {
log.info(customer.toString());
}
log.info("");
// fetch an individual customer by ID | Customer customer = repository.findById(1L).get();
log.info("Customer found with findOne(1L):");
log.info("--------------------------------");
log.info(customer.toString());
log.info("");
// fetch customers by last name
log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
log.info("--------------------------------------------");
for (Customer bauer : repository
.findByLastNameStartsWithIgnoreCase("Bauer")) {
log.info(bauer.toString());
}
log.info("");
};
}
} | repos\springboot-demo-master\vaadin\src\main\java\com\et\vaadin\DemoApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class KeyStore {
//name of the keystore in the classpath
private String name = "config/tls/keystore.p12";
//password used to access the key
private String password = "password";
//name of the alias to fetch
private String alias = "selfsigned";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
}
public static class WebClientConfiguration {
//validity of the short-lived access token in secs (min: 60), don't make it too long
private int accessTokenValidityInSeconds = 5 * 60;
//validity of the refresh token in secs (defines the duration of "remember me")
private int refreshTokenValidityInSecondsForRememberMe = 7 * 24 * 60 * 60;
private String clientId = "web_app";
private String secret = "changeit";
public int getAccessTokenValidityInSeconds() {
return accessTokenValidityInSeconds;
}
public void setAccessTokenValidityInSeconds(int accessTokenValidityInSeconds) {
this.accessTokenValidityInSeconds = accessTokenValidityInSeconds;
}
public int getRefreshTokenValidityInSecondsForRememberMe() {
return refreshTokenValidityInSecondsForRememberMe; | }
public void setRefreshTokenValidityInSecondsForRememberMe(int refreshTokenValidityInSecondsForRememberMe) {
this.refreshTokenValidityInSecondsForRememberMe = refreshTokenValidityInSecondsForRememberMe;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\config\UaaProperties.java | 2 |
请完成以下Java代码 | public void setM_TourVersion_ID (int M_TourVersion_ID)
{
if (M_TourVersion_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_TourVersion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_TourVersion_ID, Integer.valueOf(M_TourVersion_ID));
}
/** Get Tour Version.
@return Tour Version */
@Override
public int getM_TourVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Tour Version Line.
@param M_TourVersionLine_ID Tour Version Line */
@Override
public void setM_TourVersionLine_ID (int M_TourVersionLine_ID)
{
if (M_TourVersionLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_TourVersionLine_ID, Integer.valueOf(M_TourVersionLine_ID));
}
/** Get Tour Version Line. | @return Tour Version Line */
@Override
public int getM_TourVersionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_TourVersionLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersionLine.java | 1 |
请完成以下Java代码 | public IncidentQuery orderByCauseIncidentId() {
orderBy(IncidentQueryProperty.CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByRootCauseIncidentId() {
orderBy(IncidentQueryProperty.ROOT_CAUSE_INCIDENT_ID);
return this;
}
public IncidentQuery orderByConfiguration() {
orderBy(IncidentQueryProperty.CONFIGURATION);
return this;
}
public IncidentQuery orderByTenantId() {
return orderBy(IncidentQueryProperty.TENANT_ID);
}
@Override
public IncidentQuery orderByIncidentMessage() {
return orderBy(IncidentQueryProperty.INCIDENT_MESSAGE);
} | //results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentCountByQueryCriteria(this);
}
@Override
public List<Incident> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentByQueryCriteria(this, page);
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IncidentQueryImpl.java | 1 |
请完成以下Java代码 | protected void addTargetConnectionFactory(Object key, ConnectionFactory connectionFactory) {
this.targetConnectionFactories.put(key, connectionFactory);
for (ConnectionListener listener : this.connectionListeners) {
connectionFactory.addConnectionListener(listener);
}
checkConfirmsAndReturns(connectionFactory);
}
/**
* Removes the {@link ConnectionFactory} associated with the given lookup key and returns it.
* @param key the lookup key
* @return the {@link ConnectionFactory} that was removed
*/
protected ConnectionFactory removeTargetConnectionFactory(Object key) {
return this.targetConnectionFactories.remove(key);
}
/**
* Determine the current lookup key. This will typically be implemented to check a thread-bound context.
*
* @return The lookup key. | */
protected abstract @Nullable Object determineCurrentLookupKey();
@Override
public void destroy() {
resetConnection();
}
@Override
public void resetConnection() {
this.targetConnectionFactories.values().forEach(ConnectionFactory::resetConnection);
if (this.defaultTargetConnectionFactory != null) {
this.defaultTargetConnectionFactory.resetConnection();
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\AbstractRoutingConnectionFactory.java | 1 |
请完成以下Java代码 | default SqlDocumentFilterConvertersList getFilterConverters()
{
return SqlDocumentFilterConverters.emptyList();
}
default Optional<SqlDocumentFilterConverterDecorator> getFilterConverterDecorator()
{
return Optional.empty();
}
default String replaceTableNameWithTableAlias(final String sql)
{
final String tableName = getTableName();
final String tableAlias = getTableAlias();
return replaceTableNameWithTableAlias(sql, tableName, tableAlias);
}
default String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableAlias)
{
final String tableName = getTableName();
return replaceTableNameWithTableAlias(sql, tableName, tableAlias);
}
default SqlAndParams replaceTableNameWithTableAlias(final SqlAndParams sql, @NonNull final String tableAlias)
{
return SqlAndParams.of( | replaceTableNameWithTableAlias(sql.getSql(), tableAlias),
sql.getSqlParams());
}
static String replaceTableNameWithTableAlias(final String sql, @NonNull final String tableName, @NonNull final String tableAlias)
{
if (sql == null || sql.isEmpty())
{
return sql;
}
final String matchTableNameIgnoringCase = "(?i)" + Pattern.quote(tableName + ".");
final String sqlFixed = sql.replaceAll(matchTableNameIgnoringCase, tableAlias + ".");
return sqlFixed;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlEntityBinding.java | 1 |
请完成以下Java代码 | public void processParameterValueChanges(final List<JSONDocumentChangedEvent> events, final ReasonSupplier reason)
{
parameters.processValueChanges(events, reason);
}
public void setCopies(final int copies)
{
parameters.processValueChange(PARAM_Copies, copies, ReasonSupplier.NONE, DocumentFieldLogicExpressionResultRevaluator.ALWAYS_RETURN_FALSE);
}
public PrintCopies getCopies()
{
return PrintCopies.ofInt(parameters.getFieldView(PARAM_Copies).getValueAsInt(0));
}
public AdProcessId getJasperProcess_ID()
{
final IDocumentFieldView field = parameters.getFieldViewOrNull(PARAM_AD_Process_ID);
if (field != null)
{
final int processId = field.getValueAsInt(0);
if (processId > 0) | {
return AdProcessId.ofRepoId(processId);
}
}
return null;
}
public boolean isPrintPreview()
{
final IDocumentFieldView field = parameters.getFieldViewOrNull(PARAM_IsPrintPreview);
if (field != null)
{
return field.getValueAsBoolean();
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\HUReportProcessInstance.java | 1 |
请完成以下Java代码 | public void setM_Allergen(final org.compiere.model.I_M_Allergen M_Allergen)
{
set_ValueFromPO(COLUMNNAME_M_Allergen_ID, org.compiere.model.I_M_Allergen.class, M_Allergen);
}
@Override
public void setM_Allergen_ID (final int M_Allergen_ID)
{
if (M_Allergen_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Allergen_ID, M_Allergen_ID);
}
@Override
public int getM_Allergen_ID() | {
return get_ValueAsInt(COLUMNNAME_M_Allergen_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SecurityConfiguration {
@Bean
MvcRequestMatcher.Builder mvc(HandlerMappingIntrospector introspector) {
return new MvcRequestMatcher.Builder(introspector);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, MvcRequestMatcher.Builder mvc) throws Exception {
http.httpBasic(Customizer.withDefaults());
http.securityMatcher(EndpointRequest.toAnyEndpoint());
http.authorizeHttpRequests(authz -> {
authz.requestMatchers(mvc.pattern("/actuator/**"))
.hasRole("ADMIN")
.anyRequest()
.authenticated();
});
return http.build();
} | @Bean
public InMemoryUserDetailsManager userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
UserDetails admin = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\java\com\baeldung\endpoints\enabling\SecurityConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CamelRouteUtil
{
@NonNull
public JacksonDataFormat setupJacksonDataFormatFor(
@NonNull final CamelContext context,
@NonNull final Class<?> unmarshalType)
{
final ObjectMapper objectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
final JacksonDataFormat jacksonDataFormat = new JacksonDataFormat();
jacksonDataFormat.setCamelContext(context);
jacksonDataFormat.setObjectMapper(objectMapper);
jacksonDataFormat.setUnmarshalType(unmarshalType);
return jacksonDataFormat;
}
public void setupProperties(@NonNull final CamelContext context)
{
final PropertiesComponent pc = new PropertiesComponent();
pc.setEncoding("UTF-8");
pc.setLocation("classpath:application.properties");
context.setPropertiesComponent(pc);
}
@NonNull
public String resolveProperty(
@NonNull final CamelContext context, | @NonNull final String property,
@Nullable final String defaultValue)
{
final var propertyOpt = context
.getPropertiesComponent()
.resolveProperty(property);
if (defaultValue != null)
{
return propertyOpt.orElse(defaultValue);
}
else
{
return propertyOpt.orElseThrow(() -> new RuntimeCamelException("Missing property " + property));
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\common\src\main\java\de\metas\camel\externalsystems\common\CamelRouteUtil.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
// Make sure at least one receipt schedule is open
final boolean someSchedsAreStillOpen = context.streamSelectedModels(I_M_ReceiptSchedule.class)
.anyMatch(receiptSchedule -> !receiptScheduleBL.isClosed(receiptSchedule));
if (!someSchedsAreStillOpen)
{
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_RECEIPT_SCHEDULES_ALL_CLOSED));
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final IQueryFilter<I_M_ReceiptSchedule> selectedSchedsFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false));
final Iterator<I_M_ReceiptSchedule> scheds = queryBL.createQueryBuilder(I_M_ReceiptSchedule.class)
.addOnlyActiveRecordsFilter()
.filter(selectedSchedsFilter)
.create()
.iterate(I_M_ReceiptSchedule.class); | int counter = 0;
for (final I_M_ReceiptSchedule receiptSchedule : IteratorUtils.asIterable(scheds))
{
if (receiptScheduleBL.isClosed(receiptSchedule))
{
addLog(msgBL.getMsg(getCtx(), MSG_SKIP_CLOSED_1P, new Object[] { receiptSchedule.getM_ReceiptSchedule_ID() }));
continue;
}
closeInTrx(receiptSchedule);
counter++;
}
return "@Processed@: " + counter;
}
private void closeInTrx(final I_M_ReceiptSchedule receiptSchedule)
{
Services.get(ITrxManager.class)
.runInNewTrx((TrxRunnable)localTrxName -> {
InterfaceWrapperHelper.setThreadInheritedTrxName(receiptSchedule);
receiptScheduleBL.close(receiptSchedule);
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_Close.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean saveCategory(String categoryName) {
/**
* 查询是否已存在
*/
NewsCategory temp = newsCategoryMapper.selectByCategoryName(categoryName);
if (temp == null) {
NewsCategory newsCategory = new NewsCategory();
newsCategory.setCategoryName(categoryName);
return newsCategoryMapper.insertSelective(newsCategory) > 0;
}
return false;
}
@Override
public Boolean updateCategory(Long categoryId, String categoryName) {
NewsCategory newsCategory = newsCategoryMapper.selectByPrimaryKey(categoryId);
if (newsCategory != null) { | newsCategory.setCategoryName(categoryName);
return newsCategoryMapper.updateByPrimaryKeySelective(newsCategory) > 0;
}
return false;
}
@Override
public Boolean deleteBatchByIds(Integer[] ids) {
if (ids.length < 1) {
return false;
}
//删除分类数据
return newsCategoryMapper.deleteBatch(ids) > 0;
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\service\impl\CategoryServiceImpl.java | 2 |
请完成以下Java代码 | public class Start {
private static final Logger logger = LoggerFactory.getLogger(Start.class);
private static final int DEFAULT_PORT = 8080;
private static final String CONTEXT_PATH = "/";
private static final String CONFIG_LOCATION = AppConfig.class.getName();
private static final String MAPPING_URL = "/*";
/*
* This application runs a Jetty webcontainer that runs the
* Spring Dispatcher Servlet.
*/
public static void main(String[] args) throws Exception {
new Start().startJetty(getPortFromArgs(args));
}
private static int getPortFromArgs(String[] args) {
if (args.length > 0) {
try {
return Integer.parseInt(args[0]);
} catch (NumberFormatException ignore) {
}
}
logger.info("No server port configured, falling back to {}", DEFAULT_PORT);
return DEFAULT_PORT;
}
private void startJetty(int port) throws Exception {
logger.info("Starting server at port {}", port);
Server server = new Server(port);
server.setHandler(getServletContextHandler(getContext()));
server.start();
logger.info("Server started at port {}", port);
server.join(); | }
private static ServletContextHandler getServletContextHandler(WebApplicationContext context) {
ServletContextHandler contextHandler = new ServletContextHandler();
contextHandler.setErrorHandler(null);
contextHandler.setContextPath(CONTEXT_PATH);
contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
contextHandler.addEventListener(new ContextLoaderListener(context));
return contextHandler;
}
private static WebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(CONFIG_LOCATION);
return context;
}
} | repos\tutorials-master\spring-actuator\src\main\java\com\baeldung\spring\actuator\Start.java | 1 |
请完成以下Java代码 | public BigDecimal getQtyTU()
{
return orderLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
orderLine.setQtyEnteredTU(qtyPacks);
values.setQtyTU(qtyPacks);
}
@Override
public void setQtyCUsPerTU(final BigDecimal qtyCUsPerTU)
{
orderLine.setQtyItemCapacity(qtyCUsPerTU);
values.setQtyCUsPerTU(qtyCUsPerTU);
}
@Override
public Optional<BigDecimal> getQtyCUsPerTU()
{
return Optional.of(orderLine.getQtyItemCapacity());
}
@Override
public int getC_BPartner_ID()
{
return orderLine.getC_BPartner_ID();
}
@Override
public void setC_BPartner_ID(final int bpartnerId)
{
orderLine.setC_BPartner_ID(bpartnerId);
values.setC_BPartner_ID(bpartnerId);
}
public void setQtyLU(@NonNull final BigDecimal qtyLU)
{
orderLine.setQtyLU(qtyLU);
}
public BigDecimal getQtyLU()
{ | return orderLine.getQtyLU();
}
@Override
public void setLuId(@Nullable final HuPackingInstructionsId luId)
{
orderLine.setM_LU_HU_PI_ID(HuPackingInstructionsId.toRepoId(luId));
}
@Override
public HuPackingInstructionsId getLuId()
{
return HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID());
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
@Override
public String toString()
{
return String
.format("OrderLineHUPackingAware [orderLine=%s, getM_Product_ID()=%s, getM_Product()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, qtyLU()=%s, luId()=%s, isInDispute()=%s]",
orderLine, getM_Product_ID(), getM_Product_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQtyTU(), getC_BPartner_ID(),
getM_HU_PI_Item_Product_ID(), getQtyLU(), getLuId(), isInDispute());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingAware.java | 1 |
请完成以下Java代码 | public LookupDataSourceContext.Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builder(tableName)
.putFilterById(IdsToFilter.ofSingleValue(id));
}
@Override
public LookupValue retrieveLookupValueById(final @NonNull LookupDataSourceContext evalCtx)
{
final Object id = evalCtx.getSingleIdToFilterAsObject();
if (id == null)
{
throw new IllegalStateException("No ID provided in " + evalCtx);
}
return labelsValuesLookupDataSource.findById(id);
}
@Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return LookupDataSourceContext.builder(tableName)
.setRequiredParameters(parameters)
.requiresAD_Language()
.requiresUserRolePermissionsKey();
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final String filter = evalCtx.getFilter();
return labelsValuesLookupDataSource.findEntities(evalCtx, filter);
}
public Set<Object> normalizeStringIds(final Set<String> stringIds)
{
if (stringIds.isEmpty())
{
return ImmutableSet.of();
} | if (isLabelsValuesUseNumericKey())
{
return stringIds.stream()
.map(LabelsLookup::convertToInt)
.collect(ImmutableSet.toImmutableSet());
}
else
{
return ImmutableSet.copyOf(stringIds);
}
}
private static int convertToInt(final String stringId)
{
try
{
return Integer.parseInt(stringId);
}
catch (final Exception ex)
{
throw new AdempiereException("Failed converting `" + stringId + "` to int.", ex);
}
}
public ColumnSql getSqlForFetchingValueIdsByLinkId(@NonNull final String tableNameOrAlias)
{
final String sql = "SELECT array_agg(" + labelsValueColumnName + ")"
+ " FROM " + labelsTableName
+ " WHERE " + labelsLinkColumnName + "=" + tableNameOrAlias + "." + linkColumnName
+ " AND IsActive='Y'";
return ColumnSql.ofSql(sql, tableNameOrAlias);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LabelsLookup.java | 1 |
请完成以下Java代码 | public void setC_LicenseFeeSettings_ID (final int C_LicenseFeeSettings_ID)
{
if (C_LicenseFeeSettings_ID < 1)
set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, null);
else
set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, C_LicenseFeeSettings_ID);
}
@Override
public int getC_LicenseFeeSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID);
}
@Override
public void setC_LicenseFeeSettingsLine_ID (final int C_LicenseFeeSettingsLine_ID)
{
if (C_LicenseFeeSettingsLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, C_LicenseFeeSettingsLine_ID);
}
@Override
public int getC_LicenseFeeSettingsLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettingsLine_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override | public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@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.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettingsLine.java | 1 |
请完成以下Java代码 | public Object getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof LongDataEntry)) return false;
if (!super.equals(o)) return false;
LongDataEntry that = (LongDataEntry) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() { | return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "LongDataEntry{" +
"value=" + value +
"} " + super.toString();
}
@Override
public String getValueAsString() {
return Long.toString(value);
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\LongDataEntry.java | 1 |
请完成以下Java代码 | public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
/**
* 判断是否有相同字段
*
* @param fieldString
* @return
*/
public boolean existSameField(String fieldString) {
String[] controlFields = fieldString.split(",");
for (String sqlField : fields) {
for (String controlField : controlFields) {
if (sqlField.equals(controlField)) {
// 非常明确的列直接比较
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true;
} else {
// 使用表达式的列 只能判读字符串包含了
String aliasColumn = controlField;
if (StringUtils.isNotBlank(alias)) {
aliasColumn = alias + "." + controlField;
}
if (sqlField.indexOf(aliasColumn) != -1) {
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询"); | return true;
}
}
}
}
return false;
}
@Override
public String toString() {
return "QueryTable{" +
"name='" + name + '\'' +
", alias='" + alias + '\'' +
", fields=" + fields +
", all=" + all +
'}';
}
}
public String getError(){
// TODO
return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!";
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\AbstractQueryBlackListHandler.java | 1 |
请完成以下Java代码 | public Integer getReplayCount() {
return replayCount;
}
public void setReplayCount(Integer replayCount) {
this.replayCount = replayCount;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", memberNickName=").append(memberNickName);
sb.append(", productName=").append(productName);
sb.append(", star=").append(star); | sb.append(", memberIp=").append(memberIp);
sb.append(", createTime=").append(createTime);
sb.append(", showStatus=").append(showStatus);
sb.append(", productAttribute=").append(productAttribute);
sb.append(", collectCouont=").append(collectCouont);
sb.append(", readCount=").append(readCount);
sb.append(", pics=").append(pics);
sb.append(", memberIcon=").append(memberIcon);
sb.append(", replayCount=").append(replayCount);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsComment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AD_Table_Process
{
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_DELETE })
public void logSqlMigrationContextInfo(final I_AD_Table_Process record)
{
if (MigrationScriptFileLoggerHolder.isDisabled())
{
return;
}
final AdProcessId adProcessId = AdProcessId.ofRepoId(record.getAD_Process_ID());
final ADProcessName processName = Names.ADProcessName_Loader.retrieve(adProcessId);
MigrationScriptFileLoggerHolder.logComment("Process: " + processName.toShortString());
final AdTableId adTableId = AdTableId.ofRepoId(record.getAD_Table_ID());
final ADTableName tableName = Names.ADTableName_Loader.retrieve(adTableId);
MigrationScriptFileLoggerHolder.logComment("Table: " + tableName.toShortString()); | final AdTabId adTabId = AdTabId.ofRepoIdOrNull(record.getAD_Tab_ID());
if (adTabId != null)
{
final ADTabNameFQ tabNameFQ = Names.ADTabNameFQ_Loader.retrieve(adTabId);
MigrationScriptFileLoggerHolder.logComment("Tab: " + tabNameFQ.toShortString());
}
final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(record.getAD_Window_ID());
if (adWindowId != null)
{
final ADWindowName windowName = Names.ADWindowName_Loader.retrieve(adWindowId);
MigrationScriptFileLoggerHolder.logComment("Window: " + windowName.toShortString());
}
MigrationScriptFileLoggerHolder.logComment("EntityType: " + record.getEntityType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\interceptor\AD_Table_Process.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PostDto createPost(@RequestBody PostDto postDto) throws ParseException {
Post post = convertToEntity(postDto);
Post postCreated = postService.createPost(post);
return convertToDto(postCreated);
}
@GetMapping(value = "/{id}")
@ResponseBody
public PostDto getPost(@PathVariable("id") Long id) {
return convertToDto(postService.getPostById(id));
}
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void updatePost(@PathVariable("id") Long id, @RequestBody PostDto postDto) throws ParseException {
if(!Objects.equals(id, postDto.getId())){
throw new IllegalArgumentException("IDs don't match");
}
Post post = convertToEntity(postDto);
postService.updatePost(post);
} | private PostDto convertToDto(Post post) {
PostDto postDto = modelMapper.map(post, PostDto.class);
postDto.setSubmissionDate(post.getSubmissionDate(),
userService.getCurrentUser().getPreference().getTimezone());
return postDto;
}
private Post convertToEntity(PostDto postDto) throws ParseException {
Post post = modelMapper.map(postDto, Post.class);
post.setSubmissionDate(postDto.getSubmissionDateConverted(
userService.getCurrentUser().getPreference().getTimezone()));
if (postDto.getId() != null) {
Post oldPost = postService.getPostById(postDto.getId());
post.setRedditID(oldPost.getRedditID());
post.setSent(oldPost.isSent());
}
return post;
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\controller\PostRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Researcher {
@Id
private Long id;
private String name;
private boolean active;
public Researcher() {
}
public Researcher(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-3\src\main\java\com\baeldung\hibernate\union\model\Researcher.java | 2 |
请完成以下Java代码 | public static AttachmentEntryCreateRequest fromDataSource(final DataSource dataSource)
{
final String filename = dataSource.getName();
final String contentType = dataSource.getContentType();
final byte[] data;
try
{
data = Util.readBytes(dataSource.getInputStream());
}
catch (final IOException e)
{
throw new AdempiereException("Failed reading data from " + dataSource);
}
return builder()
.type(AttachmentEntryType.Data)
.filename(filename)
.contentType(contentType)
.data(data)
.build();
}
public static Collection<AttachmentEntryCreateRequest> fromResources(@NonNull final Collection<Resource> resources)
{
return resources
.stream()
.map(AttachmentEntryCreateRequest::fromResource)
.collect(ImmutableList.toImmutableList());
}
public static AttachmentEntryCreateRequest fromResource(@NonNull final Resource resource)
{
final String filename = resource.getFilename();
final String contentType = MimeType.getMimeType(filename);
final byte[] data;
try
{
data = Util.readBytes(resource.getInputStream());
}
catch (final IOException e)
{
throw new AdempiereException("Failed reading data from " + resource);
}
return builder()
.type(AttachmentEntryType.Data)
.filename(filename)
.contentType(contentType)
.data(data)
.build();
}
public static Collection<AttachmentEntryCreateRequest> fromFiles(@NonNull final Collection<File> files)
{
return files
.stream()
.map(AttachmentEntryCreateRequest::fromFile)
.collect(ImmutableList.toImmutableList()); | }
public static AttachmentEntryCreateRequest fromFile(@NonNull final File file)
{
final String filename = file.getName();
final String contentType = MimeType.getMimeType(filename);
final byte[] data = Util.readBytes(file);
return builder()
.type(AttachmentEntryType.Data)
.filename(filename)
.contentType(contentType)
.data(data)
.build();
}
@NonNull
AttachmentEntryType type;
String filename;
String contentType;
byte[] data;
URI url;
AttachmentTags tags;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryCreateRequest.java | 1 |
请完成以下Java代码 | public static Object convertToPOValue(@Nullable final Object value, @NonNull final Class<?> targetClass, final int displayType,@NonNull final ZoneId zoneId)
{
if (value == null)
{
return null;
}
final Class<?> valueClass = value.getClass();
if (targetClass.isAssignableFrom(valueClass))
{
return value;
}
else if (Integer.class.equals(targetClass))
{
if (String.class.equals(valueClass))
{
return new BigDecimal((String)value).intValue();
}
else if (RepoIdAware.class.isAssignableFrom(valueClass))
{
final RepoIdAware repoIdAware = (RepoIdAware)value;
return repoIdAware.getRepoId();
}
}
else if (String.class.equals(targetClass))
{
return String.valueOf(value);
}
else if (Timestamp.class.equals(targetClass))
{
final Object valueDate = DateTimeConverters.fromObject(value, displayType, zoneId); | return TimeUtil.asTimestamp(valueDate);
}
else if (Boolean.class.equals(targetClass))
{
if (String.class.equals(valueClass))
{
return StringUtils.toBoolean(value);
}
}
else if (BigDecimal.class.equals(targetClass))
{
if (Double.class.equals(valueClass))
{
return BigDecimal.valueOf((Double)value);
}
else if (Float.class.equals(valueClass))
{
return BigDecimal.valueOf((Float)value);
}
else if (String.class.equals(valueClass))
{
return new BigDecimal((String)value);
}
else if (Integer.class.equals(valueClass))
{
return BigDecimal.valueOf((Integer)value);
}
}
throw new RuntimeException("TargetClass " + targetClass + " does not match any supported classes!");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\POValueConverters.java | 1 |
请完成以下Java代码 | private static void delayedServiceTask(Integer delayInSeconds) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(Delay::someTask1, delayInSeconds, TimeUnit.SECONDS);
executorService.shutdown();
}
private static void fixedRateServiceTask(Integer delayInSeconds) {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> sf = executorService.scheduleAtFixedRate(Delay::someTask2, 0, delayInSeconds,
TimeUnit.SECONDS);
try {
TimeUnit.SECONDS.sleep(20); | } catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
sf.cancel(true);
executorService.shutdown();
}
private static void someTask1() {
System.out.println("Task 1 completed.");
}
private static void someTask2() {
System.out.println("Task 2 completed.");
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-basic\src\main\java\com\baeldung\concurrent\delay\Delay.java | 1 |
请完成以下Java代码 | public String getElctrncAdr() {
return elctrncAdr;
}
/**
* Sets the value of the elctrncAdr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setElctrncAdr(String value) {
this.elctrncAdr = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
* possible object is | * {@link NameAndAddress10 }
*
*/
public NameAndAddress10 getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link NameAndAddress10 }
*
*/
public void setPstlAdr(NameAndAddress10 value) {
this.pstlAdr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\RemittanceLocationDetails1.java | 1 |
请完成以下Java代码 | public class ProductImpl implements Product {
protected String name;
protected String version;
protected String edition;
protected InternalsImpl internals;
public ProductImpl(String name, String version, String edition, InternalsImpl internals) {
this.name = name;
this.version = version;
this.edition = edition;
this.internals = internals;
}
public ProductImpl(ProductImpl other) {
this(other.name, other.version, other.edition, new InternalsImpl(other.internals));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
} | public void setVersion(String version) {
this.version = version;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public InternalsImpl getInternals() {
return internals;
}
public void setInternals(InternalsImpl internals) {
this.internals = internals;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\ProductImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Rfq getRfqByUUID(@NonNull final String rfq_uuid)
{
return rfqRepo.findByUuid(rfq_uuid);
}
private void saveRecursivelyAndPush(@NonNull final Rfq rfq)
{
saveRecursively(rfq);
pushToMetasfresh(rfq);
}
@Override
public void saveRecursively(@NonNull final Rfq rfq)
{
//rfqQuantityRepo.saveAll(rfq.getQuantities()); // not needed
rfqRepo.save(rfq);
}
private void pushToMetasfresh(@NonNull final Rfq rfq)
{
final ISyncAfterCommitCollector syncAfterCommitCollector = senderToMetasfreshService.syncAfterCommit();
syncAfterCommitCollector.add(rfq);
}
@Override
@Transactional
public Rfq changeActiveRfq(
@NonNull final JsonChangeRfqRequest request,
@NonNull final User loggedUser)
{
final Rfq rfq = getUserActiveRfq(
loggedUser,
Long.parseLong(request.getRfqId()));
for (final JsonChangeRfqQtyRequest qtyChangeRequest : request.getQuantities())
{
rfq.setQtyPromised(qtyChangeRequest.getDate(), qtyChangeRequest.getQtyPromised());
}
if (request.getPrice() != null) | {
rfq.setPricePromisedUserEntered(request.getPrice());
}
saveRecursively(rfq);
return rfq;
}
@Override
public long getCountUnconfirmed(@NonNull final User user)
{
return rfqRepo.countUnconfirmed(user.getBpartner());
}
@Override
@Transactional
public void confirmUserEntries(@NonNull final User user)
{
final BPartner bpartner = user.getBpartner();
final List<Rfq> rfqs = rfqRepo.findUnconfirmed(bpartner);
for (final Rfq rfq : rfqs)
{
rfq.confirmByUser();
saveRecursivelyAndPush(rfq);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\RfQService.java | 2 |
请完成以下Java代码 | public void setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds)
{
adValRuleIdByScope.clear();
adValRuleIdByScope.putAll(adValRuleIds);
}
public void setLookupTableName(final TableName lookupTableName)
{
assertNotBuilt();
this.lookupTableName = lookupTableName;
}
public void setCtxTableName(final String ctxTableName)
{
assertNotBuilt();
this.ctxTableName = ctxTableName;
}
public void setCtxColumnName(final String ctxColumnName)
{
assertNotBuilt();
this.ctxColumnName = ctxColumnName;
}
public void setDisplayType(final int displayType)
{
assertNotBuilt();
this.displayType = displayType;
}
public void addFilter(@NonNull final Collection<IValidationRule> validationRules, @Nullable LookupDescriptorProvider.LookupScope scope)
{ | for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRules))
{
addFilter(SqlLookupFilter.of(valRule, scope));
}
}
public void addFilter(@Nullable final IValidationRule validationRule, @Nullable LookupDescriptorProvider.LookupScope scope)
{
for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRule))
{
addFilter(SqlLookupFilter.of(valRule, scope));
}
}
private void addFilter(@NonNull final SqlLookupFilter filter)
{
assertNotBuilt();
filters.add(filter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilterBuilder.java | 1 |
请完成以下Java代码 | public SqlDocumentQueryBuilder setPage(final int firstRow, final int pageLength)
{
this.firstRow = firstRow;
this.pageLength = pageLength;
return this;
}
private int getFirstRow()
{
return firstRow;
}
private int getPageLength()
{
return pageLength;
}
public static SqlComposedKey extractComposedKey(
final DocumentId recordId,
final List<? extends SqlEntityFieldBinding> keyFields)
{
final int count = keyFields.size();
if (count < 1)
{
throw new AdempiereException("Invalid composed key: " + keyFields);
}
final List<Object> composedKeyParts = recordId.toComposedKeyParts();
if (composedKeyParts.size() != count)
{
throw new AdempiereException("Invalid composed key '" + recordId + "'. Expected " + count + " parts but it has " + composedKeyParts.size());
} | final ImmutableSet.Builder<String> keyColumnNames = ImmutableSet.builder();
final ImmutableMap.Builder<String, Object> values = ImmutableMap.builder();
for (int i = 0; i < count; i++)
{
final SqlEntityFieldBinding keyField = keyFields.get(i);
final String keyColumnName = keyField.getColumnName();
keyColumnNames.add(keyColumnName);
final Object valueObj = composedKeyParts.get(i);
@Nullable final Object valueConv = DataTypes.convertToValueClass(
keyColumnName,
valueObj,
keyField.getWidgetType(),
keyField.getSqlValueClass(),
null);
if (!JSONNullValue.isNull(valueConv))
{
values.put(keyColumnName, valueConv);
}
}
return SqlComposedKey.of(keyColumnNames.build(), values.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\sql\SqlDocumentQueryBuilder.java | 1 |
请完成以下Java代码 | protected final boolean isPickerProfile()
{
return getViewProfileId() == null;
}
protected final boolean isReviewProfile()
{
return PickingConstantsV2.PROFILE_ID_ProductsToPickView_Review.equals(getViewProfileId());
}
@Override
protected final ProductsToPickView getView()
{
return ProductsToPickView.cast(super.getView());
}
protected final List<ProductsToPickRow> getSelectedRows()
{
final DocumentIdsSelection rowIds = getSelectedRowIds();
return getView()
.streamByIds(rowIds)
.collect(ImmutableList.toImmutableList());
}
protected final List<ProductsToPickRow> getAllRows()
{
return streamAllRows()
.collect(ImmutableList.toImmutableList()); | }
protected Stream<ProductsToPickRow> streamAllRows()
{
return getView()
.streamByIds(DocumentIdsSelection.ALL);
}
protected void updateViewRowFromPickingCandidate(@NonNull final DocumentId rowId, @NonNull final PickingCandidate pickingCandidate)
{
getView().updateViewRowFromPickingCandidate(rowId, pickingCandidate);
}
protected void updateViewRowFromPickingCandidate(@NonNull final ImmutableList<WebuiPickHUResult> pickHUResults)
{
pickHUResults.forEach(r -> updateViewRowFromPickingCandidate(r.getDocumentId(), r.getPickingCandidate()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\productsToPick\process\ProductsToPickViewBasedProcess.java | 1 |
请完成以下Java代码 | public void setIsPublic (boolean IsPublic)
{
set_Value (COLUMNNAME_IsPublic, Boolean.valueOf(IsPublic));
}
/** Get Public.
@return Public can read entry
*/
public boolean isPublic ()
{
Object oo = get_Value(COLUMNNAME_IsPublic);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Entry Comment.
@param K_Comment_ID
Knowledge Entry Comment
*/
public void setK_Comment_ID (int K_Comment_ID)
{
if (K_Comment_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Comment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Comment_ID, Integer.valueOf(K_Comment_ID));
}
/** Get Entry Comment.
@return Knowledge Entry Comment
*/
public int getK_Comment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Comment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_Comment_ID()));
}
public I_K_Entry getK_Entry() throws RuntimeException
{
return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name)
.getPO(getK_Entry_ID(), get_TrxName()); }
/** Set Entry.
@param K_Entry_ID
Knowledge Entry
*/
public void setK_Entry_ID (int K_Entry_ID)
{
if (K_Entry_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID));
}
/** Get Entry.
@return Knowledge Entry
*/
public int getK_Entry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); | if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Comment.java | 1 |
请完成以下Java代码 | public I_M_HU getById(HuId huId) {return handlingUnitsBL.getById(huId);}
public HUProductStorages getProductStorages(final I_M_HU hu)
{
final List<IHUProductStorage> productStorages = handlingUnitsBL.getStorageFactory().getProductStorages(hu);
return new HUProductStorages(productStorages);
}
public Quantity getQty(final HuId huId, final ProductId productId)
{
final I_M_HU hu = getById(huId);
return getProductStorages(hu).getQty(productId);
}
public Attributes getImmutableAttributeSet(final I_M_HU hu) {return Attributes.of(handlingUnitsBL.getImmutableAttributeSet(hu));} | public IHUQRCode parse(final @NonNull ScannedCode scannedCode)
{
return huQRCodesService.parse(scannedCode);
}
public HuId getHuIdByQRCode(final @NonNull HUQRCode huQRCode)
{
return huQRCodesService.getHuIdByQRCode(huQRCode);
}
public String getDisplayName(final I_M_HU hu)
{
return handlingUnitsBL.getDisplayName(hu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\handlingunits\HandlingUnitsService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductIdProperties {
private UUID smartphone;
private UUID wirelessHeadphones;
private UUID laptop;
public UUID getSmartphone() {
return smartphone;
}
public void setSmartphone(UUID smartphone) {
this.smartphone = smartphone;
}
public UUID getWirelessHeadphones() { | return wirelessHeadphones;
}
public void setWirelessHeadphones(UUID wirelessHeadphones) {
this.wirelessHeadphones = wirelessHeadphones;
}
public UUID getLaptop() {
return laptop;
}
public void setLaptop(UUID laptop) {
this.laptop = laptop;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\sqs\acknowledgement\configuration\ProductIdProperties.java | 2 |
请完成以下Java代码 | protected void onUpdate(AjaxRequestTarget target) {
String name = (String) cafeDropdown.getDefaultModel().getObject();
address.setAddress(cafeNamesAndAddresses.get(name).getAddress());
target.add(addressLabel);
}
});
add(addressLabel);
add(cafeDropdown);
}
private void initCafes() {
this.cafeNamesAndAddresses.put("Linda's Cafe", new Address("35 Bower St."));
this.cafeNamesAndAddresses.put("Old Tree", new Address("2 Edgware Rd."));
} | class Address implements Serializable {
private String sAddress = "";
public Address(String address) {
this.sAddress = address;
}
String getAddress() {
return this.sAddress;
}
void setAddress(String address) {
this.sAddress = address;
}
}
} | repos\tutorials-master\web-modules\wicket\src\main\java\com\baeldung\wicket\examples\cafeaddress\CafeAddress.java | 1 |
请完成以下Java代码 | public final class SqlDocumentFilterConvertersList
{
/* package */static Builder builder()
{
return new Builder();
}
/* package */static final SqlDocumentFilterConvertersList EMPTY = new SqlDocumentFilterConvertersList(ImmutableList.of());
private final ImmutableList<SqlDocumentFilterConverter> converters;
private SqlDocumentFilterConvertersList(@NonNull final ImmutableList<SqlDocumentFilterConverter> converters)
{
this.converters = converters;
}
public SqlDocumentFilterConverter getConverterOrDefault(final String filterId, final SqlDocumentFilterConverter defaultConverter)
{
for (final SqlDocumentFilterConverter converter : converters)
{
if (converter.canConvert(filterId))
{
return converter;
}
}
return defaultConverter;
}
public SqlDocumentFilterConverter withFallback(@NonNull final SqlDocumentFilterConverter fallback)
{
return SqlDocumentFilterConvertersListWithFallback.newInstance(this, fallback);
}
//
//
//
//
//
public static class Builder
{
private ImmutableList.Builder<SqlDocumentFilterConverter> converters = null;
private Builder()
{
}
public SqlDocumentFilterConvertersList build()
{
if (converters == null)
{
return EMPTY;
}
final ImmutableList<SqlDocumentFilterConverter> converters = this.converters.build();
if (converters.isEmpty())
{ | return EMPTY;
}
return new SqlDocumentFilterConvertersList(converters);
}
public Builder converter(@NonNull final SqlDocumentFilterConverter converter)
{
if (converters == null)
{
converters = ImmutableList.builder();
}
converters.add(converter);
return this;
}
public Builder converters(@NonNull final Collection<SqlDocumentFilterConverter> converters)
{
if (converters.isEmpty())
{
return this;
}
if (this.converters == null)
{
this.converters = ImmutableList.builder();
}
this.converters.addAll(converters);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDocumentFilterConvertersList.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_R_CategoryUpdates[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{ | if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_R_Category getR_Category() throws RuntimeException
{
return (I_R_Category)MTable.get(getCtx(), I_R_Category.Table_Name)
.getPO(getR_Category_ID(), get_TrxName()); }
/** Set Category.
@param R_Category_ID
Request Category
*/
public void setR_Category_ID (int R_Category_ID)
{
if (R_Category_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_Category_ID, Integer.valueOf(R_Category_ID));
}
/** Get Category.
@return Request Category
*/
public int getR_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_Category_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_R_CategoryUpdates.java | 1 |
请完成以下Java代码 | public void setMeta_Author (String Meta_Author)
{
set_Value (COLUMNNAME_Meta_Author, Meta_Author);
}
/** Get Meta Author.
@return Author of the content
*/
public String getMeta_Author ()
{
return (String)get_Value(COLUMNNAME_Meta_Author);
}
/** Set Meta Content Type.
@param Meta_Content
Defines the type of content i.e. "text/html; charset=UTF-8"
*/
public void setMeta_Content (String Meta_Content)
{
set_Value (COLUMNNAME_Meta_Content, Meta_Content);
}
/** Get Meta Content Type.
@return Defines the type of content i.e. "text/html; charset=UTF-8"
*/
public String getMeta_Content ()
{
return (String)get_Value(COLUMNNAME_Meta_Content);
}
/** Set Meta Copyright.
@param Meta_Copyright
Contains Copyright information for the content
*/
public void setMeta_Copyright (String Meta_Copyright)
{
set_Value (COLUMNNAME_Meta_Copyright, Meta_Copyright);
}
/** Get Meta Copyright.
@return Contains Copyright information for the content
*/
public String getMeta_Copyright ()
{
return (String)get_Value(COLUMNNAME_Meta_Copyright);
}
/** Set Meta Publisher.
@param Meta_Publisher
Meta Publisher defines the publisher of the content
*/
public void setMeta_Publisher (String Meta_Publisher)
{
set_Value (COLUMNNAME_Meta_Publisher, Meta_Publisher);
}
/** Get Meta Publisher.
@return Meta Publisher defines the publisher of the content
*/
public String getMeta_Publisher ()
{ | return (String)get_Value(COLUMNNAME_Meta_Publisher);
}
/** Set Meta RobotsTag.
@param Meta_RobotsTag
RobotsTag defines how search robots should handle this content
*/
public void setMeta_RobotsTag (String Meta_RobotsTag)
{
set_Value (COLUMNNAME_Meta_RobotsTag, Meta_RobotsTag);
}
/** Get Meta RobotsTag.
@return RobotsTag defines how search robots should handle this content
*/
public String getMeta_RobotsTag ()
{
return (String)get_Value(COLUMNNAME_Meta_RobotsTag);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_WebProject.java | 1 |
请完成以下Java代码 | public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
} | public byte getState() {
return state;
}
public void setState(byte state) {
this.state = state;
}
public List<SysRole> getRoleList() {
return roleList;
}
public void setRoleList(List<SysRole> roleList) {
this.roleList = roleList;
}
/**
* Salt
* @return
*/
public String getCredentialsSalt(){
return this.username+this.salt;
}
} | repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\UserInfo.java | 1 |
请完成以下Java代码 | public class ProcessInstanceStartedEventHandler extends AbstractDatabaseEventLoggerEventHandler {
private static final String TYPE = "PROCESSINSTANCE_START";
@Override
public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) {
ActivitiEntityWithVariablesEvent eventWithVariables = (ActivitiEntityWithVariablesEvent) event;
ExecutionEntity processInstanceEntity = (ExecutionEntity) eventWithVariables.getEntity();
Map<String, Object> data = new HashMap<String, Object>();
putInMapIfNotNull(data, Fields.ID, processInstanceEntity.getId());
putInMapIfNotNull(data, Fields.BUSINESS_KEY, processInstanceEntity.getBusinessKey());
putInMapIfNotNull(data, Fields.PROCESS_DEFINITION_ID, processInstanceEntity.getProcessDefinitionId());
putInMapIfNotNull(data, Fields.NAME, processInstanceEntity.getName());
putInMapIfNotNull(data, Fields.CREATE_TIME, timeStamp);
if (eventWithVariables.getVariables() != null && !eventWithVariables.getVariables().isEmpty()) {
Map<String, Object> variableMap = new HashMap<String, Object>();
for (Object variableName : eventWithVariables.getVariables().keySet()) {
putInMapIfNotNull(
variableMap, | (String) variableName,
eventWithVariables.getVariables().get(variableName)
);
}
putInMapIfNotNull(data, Fields.VARIABLES, variableMap);
}
return createEventLogEntry(
TYPE,
processInstanceEntity.getProcessDefinitionId(),
processInstanceEntity.getId(),
null,
null,
data
);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\handler\ProcessInstanceStartedEventHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CreateProductUpsertReqProcessor implements Processor
{
protected Logger log = LoggerFactory.getLogger(getClass());
@Override
public void process(final Exchange exchange) throws Exception
{
final EbayImportOrdersRouteContext importOrdersRouteContext = getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_ORDERS_CONTEXT, EbayImportOrdersRouteContext.class);
final Order ebayOrder = importOrdersRouteContext.getOrderNotNull();
final ProductUpsertRequestProducer productUpsertRequestProducer = ProductUpsertRequestProducer.builder()
.orgCode(importOrdersRouteContext.getOrgCode())
.articles(ebayOrder.getLineItems())
.build();
final Optional<ProductRequestProducerResult> productRequestProducerResult = productUpsertRequestProducer.run(); | if (productRequestProducerResult.isPresent())
{
final ProductUpsertCamelRequest productUpsertCamelRequest = ProductUpsertCamelRequest.builder()
.jsonRequestProductUpsert(productRequestProducerResult.get().getJsonRequestProductUpsert())
.orgCode(importOrdersRouteContext.getOrgCode())
.build();
exchange.getIn().setBody(productUpsertCamelRequest);
}
else
{
exchange.getIn().setBody(null);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\processor\product\CreateProductUpsertReqProcessor.java | 2 |
请完成以下Java代码 | public Double getCount() {
return count;
}
public void setCount(Double count) {
this.count = count;
}
public Integer getTimeWindow() {
return timeWindow;
}
public void setTimeWindow(Integer timeWindow) {
this.timeWindow = timeWindow;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
} | public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public DegradeRule toRule() {
DegradeRule rule = new DegradeRule();
rule.setResource(resource);
rule.setLimitApp(limitApp);
rule.setCount(count);
rule.setTimeWindow(timeWindow);
rule.setGrade(grade);
return rule;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\DegradeRuleEntity.java | 1 |
请完成以下Java代码 | private Result computeNewResult()
{
final UserDashboardDataProvider dataProvider = dashboardDataService
.getData(getUserDashboardKey())
.orElse(null);
// no user dashboard was found.
// might be that the user dashboard was deactivated in meantime.
if (dataProvider == null)
{
return Result.EMPTY;
}
final UserDashboardDataResponse data = dataProvider
.getAllItems(UserDashboardDataRequest.builder()
.context(kpiDataContext)
.build());
return Result.ofCollection(data.getItems());
}
private static KPIJsonOptions newKpiJsonOptions(final JSONOptions jsonOpts)
{
return KPIJsonOptions.builder()
.adLanguage(jsonOpts.getAdLanguage())
.zoneId(jsonOpts.getZoneId())
.prettyValues(true)
.build();
}
//
//
//
//
//
@ToString
private static class Result
{
public static Result ofMap(@NonNull final Map<UserDashboardItemId, UserDashboardItemDataResponse> map)
{
return !map.isEmpty() ? new Result(map) : EMPTY;
}
public static Result ofCollection(@NonNull final Collection<UserDashboardItemDataResponse> itemDataList)
{
return ofMap(Maps.uniqueIndex(itemDataList, UserDashboardItemDataResponse::getItemId));
}
private static final Result EMPTY = new Result(ImmutableMap.of());
private final ImmutableMap<UserDashboardItemId, UserDashboardItemDataResponse> map;
private Result(final Map<UserDashboardItemId, UserDashboardItemDataResponse> map)
{
this.map = ImmutableMap.copyOf(map);
} | public ImmutableList<UserDashboardItemDataResponse> getChangesFromOldVersion(@Nullable final Result oldResult)
{
if (oldResult == null)
{
return toList();
}
final ImmutableList.Builder<UserDashboardItemDataResponse> resultEffective = ImmutableList.builder();
for (final Map.Entry<UserDashboardItemId, UserDashboardItemDataResponse> e : map.entrySet())
{
final UserDashboardItemId itemId = e.getKey();
final UserDashboardItemDataResponse newValue = e.getValue();
final UserDashboardItemDataResponse oldValue = oldResult.get(itemId);
if (oldValue == null || !newValue.isSameDataAs(oldValue))
{
resultEffective.add(newValue);
}
}
return resultEffective.build();
}
@Nullable
private UserDashboardItemDataResponse get(final UserDashboardItemId itemId)
{
return map.get(itemId);
}
public ImmutableList<UserDashboardItemDataResponse> toList()
{
return ImmutableList.copyOf(map.values());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketProducer.java | 1 |
请完成以下Java代码 | private static <T, S, K> ImmutableList<T> syncLists0(
@NonNull final Iterable<T> target,
@NonNull final Iterable<S> source,
@NonNull final Function<T, K> targetKeyExtractor,
@NonNull final Function<S, K> sourceKeyExtractor,
@NonNull final BiFunction<T, S, T> mergeFunction
)
{
final ImmutableMap<K, T> targetByKey = Maps.uniqueIndex(target, targetKeyExtractor::apply);
final ImmutableList.Builder<T> result = ImmutableList.builder();
for (final S sourceItem : source)
{
final K key = sourceKeyExtractor.apply(sourceItem);
T targetItem = targetByKey.get(key);
final T resultItem = mergeFunction.apply(targetItem, sourceItem);
result.add(resultItem);
}
return result.build();
}
public static <K, V> Map<K, V> fillMissingKeys(@NonNull final Map<K, V> map, @NonNull final Collection<K> keys, @NonNull final V defaultValue)
{
if (keys.isEmpty())
{
return map;
}
LinkedHashMap<K, V> result = null;
for (K key : keys)
{
if (!map.containsKey(key))
{
if (result == null)
{
result = new LinkedHashMap<>(map.size() + keys.size());
result.putAll(map);
}
result.put(key, defaultValue);
}
}
return result == null ? map : result;
}
public <K, V> ImmutableMap<K, V> merge(@NonNull final ImmutableMap<K, V> map, K key, V value, BinaryOperator<V> remappingFunction)
{
if (map.isEmpty())
{
return ImmutableMap.of(key, value);
}
final ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder();
boolean added = false;
boolean changed = false;
for (Map.Entry<K, V> entry : map.entrySet())
{
if (!added && Objects.equals(key, entry.getKey()))
{
final V valueOld = entry.getValue();
final V valueNew = remappingFunction.apply(valueOld, value);
mapBuilder.put(key, valueNew);
added = true;
if (!Objects.equals(valueOld, valueNew))
{
changed = true;
} | }
else
{
mapBuilder.put(entry.getKey(), entry.getValue());
}
}
if (!added)
{
mapBuilder.put(key, value);
changed = true;
}
if (!changed)
{
return map;
}
return mapBuilder.build();
}
public static <T> ImmutableList<T> removeIf(@NonNull ImmutableList<T> list, @NonNull Predicate<T> predicate)
{
if (list.isEmpty()) {return list;}
final ImmutableList<T> result = list.stream()
.filter(item -> !predicate.test(item))
.collect(ImmutableList.toImmutableList());
return list.size() == result.size() ? list : result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\CollectionUtils.java | 1 |
请完成以下Java代码 | public static Point getWindowLocation(final int AD_Window_ID)
{
final String key = "WindowLoc" + AD_Window_ID;
final String value = (String)s_prop.get(key);
if (value == null || value.length() == 0)
{
return null;
}
final int index = value.indexOf('|');
if (index == -1)
{
return null;
}
try
{
final String x = value.substring(0, index);
final String y = value.substring(index + 1);
return new Point(Integer.parseInt(x), Integer.parseInt(y));
}
catch (final Exception ignored)
{
}
return null;
} // getWindowLocation
/**
* Set Window Location
*
* @param windowLocation location - null to remove
*/
public static void setWindowLocation(final int AD_Window_ID, final Point windowLocation)
{
final String key = "WindowLoc" + AD_Window_ID;
if (windowLocation != null)
{
final String value = windowLocation.x + "|" + windowLocation.y;
s_prop.put(key, value);
}
else
s_prop.remove(key);
} // setWindowLocation
/**
* Get Divider Location
*
* @return location or 400
*/
public static int getDividerLocation()
{
final int defaultValue = 400;
final String key = "Divider";
final String value = (String)s_prop.get(key);
if (value == null || value.length() == 0)
return defaultValue;
int valueInt = defaultValue;
try
{
valueInt = Integer.parseInt(value);
}
catch (final Exception ignored)
{
}
return valueInt <= 0 ? defaultValue : valueInt;
} // getDividerLocation
/** | * Set Divider Location
*
* @param dividerLocation location
*/
public static void setDividerLocation(final int dividerLocation)
{
final String key = "Divider";
final String value = String.valueOf(dividerLocation);
s_prop.put(key, value);
} // setDividerLocation
/**
* Get Available Encoding Charsets
*
* @return array of available encoding charsets
* @since 3.1.4
*/
public static Charset[] getAvailableCharsets()
{
final Collection<Charset> col = Charset.availableCharsets().values();
final Charset[] arr = new Charset[col.size()];
col.toArray(arr);
return arr;
}
/**
* Get current charset
*
* @return current charset
* @since 3.1.4
*/
public static Charset getCharset()
{
final String charsetName = getProperty(P_CHARSET);
if (Check.isBlank(charsetName))
{
return Charset.defaultCharset();
}
try
{
return Charset.forName(charsetName);
}
catch (final Exception ignored)
{
}
return Charset.defaultCharset();
}
public static String getPropertyFileName()
{
return s_propertyFileName;
}
// public static class IsNotSwingClient implements Condition
// {
// @Override
// public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)
// {
// return Ini.getRunMode() != RunMode.SWING_CLIENT;
// }
// }
} // Ini | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Ini.java | 1 |
请完成以下Java代码 | public String getF_END() {
return F_END;
}
public void setF_END(String f_END) {
F_END = f_END;
}
public String getF_SHAREDIREC() {
return F_SHAREDIREC;
}
public void setF_SHAREDIREC(String f_SHAREDIREC) {
F_SHAREDIREC = f_SHAREDIREC;
}
public String getF_HISTORYID() {
return F_HISTORYID;
}
public void setF_HISTORYID(String f_HISTORYID) {
F_HISTORYID = f_HISTORYID;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_VERSION() {
return F_VERSION;
}
public void setF_VERSION(String f_VERSION) {
F_VERSION = f_VERSION;
}
public String getF_ISSTD() {
return F_ISSTD;
} | public void setF_ISSTD(String f_ISSTD) {
F_ISSTD = f_ISSTD;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public String getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(String f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISENTERPRISES() {
return F_ISENTERPRISES;
}
public void setF_ISENTERPRISES(String f_ISENTERPRISES) {
F_ISENTERPRISES = f_ISENTERPRISES;
}
public String getF_ISCLEAR() {
return F_ISCLEAR;
}
public void setF_ISCLEAR(String f_ISCLEAR) {
F_ISCLEAR = f_ISCLEAR;
}
public String getF_PARENTID() {
return F_PARENTID;
}
public void setF_PARENTID(String f_PARENTID) {
F_PARENTID = f_PARENTID;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object regionGetEntryAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return RegionEntryWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionSelectValuePointcut()")
public Object regionSelectValueAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return PdxInstanceWrapper.from(joinPoint.proceed());
}
@Around("regionPointcut() && regionValuesPointcut()")
public Object regionValuesAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
return asCollection(joinPoint.proceed()).stream()
.map(PdxInstanceWrapper::from)
.collect(Collectors.toList());
}
public static class RegionEntryWrapper<K, V> implements Region.Entry<K, V> {
@SuppressWarnings("unchecked")
public static <T, K, V> T from(T value) {
return value instanceof Region.Entry
? (T) new RegionEntryWrapper<>((Region.Entry<K, V>) value)
: value;
}
private final Region.Entry<K, V> delegate;
protected RegionEntryWrapper(@NonNull Region.Entry<K, V> regionEntry) {
Assert.notNull(regionEntry, "Region.Entry must not be null");
this.delegate = regionEntry;
}
protected @NonNull Region.Entry<K, V> getDelegate() {
return this.delegate;
}
@Override
public boolean isDestroyed() {
return getDelegate().isDestroyed();
}
@Override
public boolean isLocal() {
return getDelegate().isLocal();
}
@Override
public K getKey() {
return getDelegate().getKey();
} | @Override
public Region<K, V> getRegion() {
return getDelegate().getRegion();
}
@Override
public CacheStatistics getStatistics() {
return getDelegate().getStatistics();
}
@Override
public Object setUserAttribute(Object userAttribute) {
return getDelegate().setUserAttribute(userAttribute);
}
@Override
public Object getUserAttribute() {
return getDelegate().getUserAttribute();
}
@Override
public V setValue(V value) {
return getDelegate().setValue(value);
}
@Override
@SuppressWarnings("unchecked")
public V getValue() {
return (V) PdxInstanceWrapper.from(getDelegate().getValue());
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java | 2 |
请完成以下Java代码 | public class M_InventoryLine_MarkAsCounted extends JavaProcess
{
@Override
protected String doIt() throws Exception
{
getSelectedInventoryLines()
.stream()
.forEach(inventoryLine -> markAsCounted(inventoryLine));
return MSG_OK;
}
private void markAsCounted(final I_M_InventoryLine inventoryLine)
{
if (!inventoryLine.isCounted())
{
inventoryLine.setIsCounted(true);
save(inventoryLine);
}
} | private List<I_M_InventoryLine> getSelectedInventoryLines()
{
final IQueryFilter<I_M_InventoryLine> selectedInventoryLines = getProcessInfo().getQueryFilterOrElseFalse();
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_M_InventoryLine> queryBuilder = queryBL.createQueryBuilder(I_M_InventoryLine.class);
return queryBuilder
.filter(selectedInventoryLines)
.addOnlyActiveRecordsFilter()
.orderBy().addColumn(I_M_InventoryLine.COLUMNNAME_M_Locator_ID).endOrderBy()
.create()
.list(I_M_InventoryLine.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inventory\process\M_InventoryLine_MarkAsCounted.java | 1 |
请完成以下Java代码 | public String onAD_Table_ID(Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
I_EXP_Format format = InterfaceWrapperHelper.create(mTab, I_EXP_Format.class);
if (format.getAD_Table_ID() > 0)
{
String tableName = Services.get(IADTableDAO.class).retrieveTableName(format.getAD_Table_ID());
format.setValue(tableName);
format.setName(tableName);
}
return "";
}
public String setLineValueName(Properties ctx, int WindowNo, GridTab mTab, GridField mField, Object value)
{
I_EXP_FormatLine line = InterfaceWrapperHelper.create(mTab, I_EXP_FormatLine.class);
if (line.getEXP_EmbeddedFormat_ID() > 0
&& X_EXP_FormatLine.TYPE_EmbeddedEXPFormat.equals(line.getType()))
{
I_EXP_Format format = line.getEXP_EmbeddedFormat();
line.setValue(format.getValue()); | line.setName(format.getName());
}
else if (line.getAD_Column_ID() > 0)
{
MColumn column = MColumn.get(ctx, line.getAD_Column_ID());
String columnName = column.getColumnName();
line.setValue(columnName);
line.setName(columnName);
if (column.isMandatory())
{
line.setIsMandatory(true);
}
}
return "";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\CalloutEXP_Format.java | 1 |
请完成以下Java代码 | public void closeAll() {
for (Channel channel : this.channels) {
try {
if (channel != ConsumerChannelRegistry.getConsumerChannel()) { // NOSONAR
channel.close();
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping close of consumer channel: " + channel.toString());
}
}
}
catch (Exception ex) {
logger.debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
}
for (Connection con : this.connections) { //NOSONAR
RabbitUtils.closeConnection(con);
}
this.connections.clear();
this.channels.clear();
this.channelsPerConnection.clear();
}
public void addDeliveryTag(Channel channel, long deliveryTag) {
this.deliveryTags.add(channel, deliveryTag);
}
public void rollbackAll() {
for (Channel channel : this.channels) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back messages to channel: " + channel);
} | RabbitUtils.rollbackIfNecessary(channel);
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
try {
channel.basicReject(deliveryTag, this.requeueOnRollback);
}
catch (IOException ex) {
throw new AmqpIOException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitResourceHolder.java | 1 |
请完成以下Java代码 | public static <T extends Message> void broadcast(String type, T message) {
// 创建消息
String messageText = buildTextMessage(type, message);
// 遍历 SESSION_USER_MAP ,进行逐个发送
for (Session session : SESSION_USER_MAP.keySet()) {
sendTextMessage(session, messageText);
}
}
/**
* 发送消息给单个用户的 Session
*
* @param session Session
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
*/
public static <T extends Message> void send(Session session, String type, T message) {
// 创建消息
String messageText = buildTextMessage(type, message);
// 遍历给单个 Session ,进行逐个发送
sendTextMessage(session, messageText);
}
/**
* 发送消息给指定用户
*
* @param user 指定用户
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
* @return 发送是否成功你那个
*/
public static <T extends Message> boolean send(String user, String type, T message) {
// 获得用户对应的 Session
Session session = USER_SESSION_MAP.get(user);
if (session == null) {
LOGGER.error("[send][user({}) 不存在对应的 session]", user);
return false;
}
// 发送消息
send(session, type, message);
return true;
}
/**
* 构建完整的消息
*
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
* @return 消息
*/
private static <T extends Message> String buildTextMessage(String type, T message) { | JSONObject messageObject = new JSONObject();
messageObject.put("type", type);
messageObject.put("body", message);
return messageObject.toString();
}
/**
* 真正发送消息
*
* @param session Session
* @param messageText 消息
*/
private static void sendTextMessage(Session session, String messageText) {
if (session == null) {
LOGGER.error("[sendTextMessage][session 为 null]");
return;
}
RemoteEndpoint.Basic basic = session.getBasicRemote();
if (basic == null) {
LOGGER.error("[sendTextMessage][session 的 为 null]");
return;
}
try {
basic.sendText(messageText);
} catch (IOException e) {
LOGGER.error("[sendTextMessage][session({}) 发送消息{}) 发生异常",
session, messageText, e);
}
}
} | repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\util\WebSocketUtil.java | 1 |
请完成以下Java代码 | public class PageParam {
private int beginLine; //起始行
private Integer pageSize = 3;
private Integer currentPage=0; // 当前页
public int getBeginLine() {
return pageSize*currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCurrentPage() { | return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
@Override
public String toString() {
return "PageParam{" +
"beginLine=" + beginLine +
", pageSize=" + pageSize +
", currentPage=" + currentPage +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-mybatis-xml\src\main\java\com\neo\param\PageParam.java | 1 |
请完成以下Java代码 | public String getTaskId() {
Task task = getTask();
return task != null ? task.getId() : null;
}
/**
* Returns the currently associated {@link Task} or 'null'
*
* @throws ProcessEngineCdiException
* if no {@link Task} is associated. Use {@link #isTaskAssociated()}
* to check whether an association exists.
*
*/
public Task getTask() {
return associationManager.getTask();
}
/**
* Returns the currently associated execution or 'null'
*/
public Execution getExecution() {
return associationManager.getExecution();
}
/**
* @see #getExecution()
*/
public String getExecutionId() {
Execution e = getExecution();
return e != null ? e.getId() : null;
}
/**
* Returns the {@link ProcessInstance} currently associated or 'null'
*
* @throws ProcessEngineCdiException
* if no {@link Execution} is associated. Use | * {@link #isAssociated()} to check whether an association exists.
*/
public ProcessInstance getProcessInstance() {
Execution execution = getExecution();
if(execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))){
return processEngine
.getRuntimeService()
.createProcessInstanceQuery()
.processInstanceId(execution.getProcessInstanceId())
.singleResult();
}
return (ProcessInstance) execution;
}
// internal implementation //////////////////////////////////////////////////////////
protected void assertExecutionAssociated() {
if (associationManager.getExecution() == null) {
throw new ProcessEngineCdiException("No execution associated. Call busniessProcess.associateExecutionById() or businessProcess.startTask() first.");
}
}
protected void assertTaskAssociated() {
if (associationManager.getTask() == null) {
throw new ProcessEngineCdiException("No task associated. Call businessProcess.startTask() first.");
}
}
protected void assertCommandContextNotActive() {
if(Context.getCommandContext() != null) {
throw new ProcessEngineCdiException("Cannot use this method of the BusinessProcess bean from an active command context.");
}
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\BusinessProcess.java | 1 |
请完成以下Java代码 | public Stream<EmailAttachment> streamEmailAttachments(@NonNull final TableRecordReference recordRef, @Nullable final String tagName)
{
return attachmentEntryRepository.getByReferencedRecord(recordRef)
.stream()
.filter(attachmentEntry -> Check.isBlank(tagName) || attachmentEntry.getTags().hasTag(tagName))
.map(attachmentEntry -> EmailAttachment.builder()
.filename(attachmentEntry.getFilename())
.attachmentDataSupplier(() -> retrieveData(attachmentEntry.getId()))
.build());
}
/**
* Persist the given {@code attachmentEntry} as-is.
* Warning: e.g. tags or referenced records that are persisted before this method is called, but are not part of the given {@code attachmentEntry} are dropped.
*/
public void save(@NonNull final AttachmentEntry attachmentEntry)
{
attachmentEntryRepository.save(attachmentEntry);
}
@Value
public static class AttachmentEntryQuery
{
List<String> tagsSetToTrue;
List<String> tagsSetToAnyValue;
Object referencedRecord;
String mimeType; | @Builder
private AttachmentEntryQuery(
@Singular("tagSetToTrue") final List<String> tagsSetToTrue,
@Singular("tagSetToAnyValue") final List<String> tagsSetToAnyValue,
@Nullable final String mimeType,
@NonNull final Object referencedRecord)
{
this.referencedRecord = referencedRecord;
this.mimeType = mimeType;
this.tagsSetToTrue = tagsSetToTrue;
this.tagsSetToAnyValue = tagsSetToAnyValue;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryService.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Column getAD_Column()
{
return get_ValueAsPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class);
}
@Override
public void setAD_Column(final org.compiere.model.I_AD_Column AD_Column)
{
set_ValueFromPO(COLUMNNAME_AD_Column_ID, org.compiere.model.I_AD_Column.class, AD_Column);
}
@Override
public void setAD_Column_ID (final int AD_Column_ID)
{
if (AD_Column_ID < 1)
set_Value (COLUMNNAME_AD_Column_ID, null);
else
set_Value (COLUMNNAME_AD_Column_ID, AD_Column_ID);
}
@Override
public int getAD_Column_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Column_ID);
}
@Override
public de.metas.elasticsearch.model.I_ES_FTS_Config_Field getES_FTS_Config_Field()
{
return get_ValueAsPO(COLUMNNAME_ES_FTS_Config_Field_ID, de.metas.elasticsearch.model.I_ES_FTS_Config_Field.class);
}
@Override
public void setES_FTS_Config_Field(final de.metas.elasticsearch.model.I_ES_FTS_Config_Field ES_FTS_Config_Field)
{
set_ValueFromPO(COLUMNNAME_ES_FTS_Config_Field_ID, de.metas.elasticsearch.model.I_ES_FTS_Config_Field.class, ES_FTS_Config_Field);
}
@Override
public void setES_FTS_Config_Field_ID (final int ES_FTS_Config_Field_ID)
{
if (ES_FTS_Config_Field_ID < 1)
set_Value (COLUMNNAME_ES_FTS_Config_Field_ID, null);
else
set_Value (COLUMNNAME_ES_FTS_Config_Field_ID, ES_FTS_Config_Field_ID);
}
@Override
public int getES_FTS_Config_Field_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_Field_ID);
}
@Override
public de.metas.elasticsearch.model.I_ES_FTS_Filter getES_FTS_Filter()
{
return get_ValueAsPO(COLUMNNAME_ES_FTS_Filter_ID, de.metas.elasticsearch.model.I_ES_FTS_Filter.class);
}
@Override
public void setES_FTS_Filter(final de.metas.elasticsearch.model.I_ES_FTS_Filter ES_FTS_Filter)
{
set_ValueFromPO(COLUMNNAME_ES_FTS_Filter_ID, de.metas.elasticsearch.model.I_ES_FTS_Filter.class, ES_FTS_Filter);
} | @Override
public void setES_FTS_Filter_ID (final int ES_FTS_Filter_ID)
{
if (ES_FTS_Filter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, ES_FTS_Filter_ID);
}
@Override
public int getES_FTS_Filter_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_ID);
}
@Override
public void setES_FTS_Filter_JoinColumn_ID (final int ES_FTS_Filter_JoinColumn_ID)
{
if (ES_FTS_Filter_JoinColumn_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, ES_FTS_Filter_JoinColumn_ID);
}
@Override
public int getES_FTS_Filter_JoinColumn_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_JoinColumn_ID);
}
@Override
public void setIsNullable (final boolean IsNullable)
{
set_Value (COLUMNNAME_IsNullable, IsNullable);
}
@Override
public boolean isNullable()
{
return get_ValueAsBoolean(COLUMNNAME_IsNullable);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Filter_JoinColumn.java | 1 |
请完成以下Java代码 | public static void capitalize() throws Exception {
String inputTopic = "flink_input";
String outputTopic = "flink_output";
String consumerGroup = "baeldung";
String address = "localhost:9092";
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
FlinkKafkaConsumer<String> flinkKafkaConsumer = createStringConsumerForTopic(inputTopic, address, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
DataStream<String> stringInputStream = environment.addSource(flinkKafkaConsumer);
FlinkKafkaProducer<String> flinkKafkaProducer = createStringProducer(outputTopic, address);
stringInputStream.map(new WordsCapitalizer())
.addSink(flinkKafkaProducer);
environment.execute();
}
public static void createBackup() throws Exception {
String inputTopic = "flink_input";
String outputTopic = "flink_output";
String consumerGroup = "baeldung";
String kafkaAddress = "localhost:9092";
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment(); | environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
FlinkKafkaConsumer<InputMessage> flinkKafkaConsumer = createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
flinkKafkaConsumer.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner());
FlinkKafkaProducer<Backup> flinkKafkaProducer = createBackupProducer(outputTopic, kafkaAddress);
DataStream<InputMessage> inputMessagesStream = environment.addSource(flinkKafkaConsumer);
inputMessagesStream.timeWindowAll(Time.hours(24))
.aggregate(new BackupAggregator())
.addSink(flinkKafkaProducer);
environment.execute();
}
public static void main(String[] args) throws Exception {
createBackup();
}
} | repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\flink\FlinkDataPipeline.java | 1 |
请完成以下Java代码 | public class SetProcessDefinitionCategoryCmd implements Command<Void> {
protected String processDefinitionId;
protected String category;
public SetProcessDefinitionCategoryCmd(String processDefinitionId, String category) {
this.processDefinitionId = processDefinitionId;
this.category = category;
}
@Override
public Void execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new ActivitiIllegalArgumentException("Process definition id is null");
}
ProcessDefinitionEntity processDefinition = commandContext
.getProcessDefinitionEntityManager()
.findProcessDefinitionById(processDefinitionId);
if (processDefinition == null) {
throw new ActivitiObjectNotFoundException("No process definition found for id = '" + processDefinitionId + "'", ProcessDefinition.class);
}
// Update category
processDefinition.setCategory(category);
// Remove process definition from cache, it will be refetched later
DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = commandContext.getProcessEngineConfiguration().getProcessDefinitionCache();
if (processDefinitionCache != null) {
processDefinitionCache.remove(processDefinitionId);
}
if (commandContext.getEventDispatcher().isEnabled()) {
commandContext.getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, processDefinition),
EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
} | return null;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\SetProcessDefinitionCategoryCmd.java | 1 |
请完成以下Java代码 | public class User {
private Long id;
private String name;
private String email;
private String department;
public User() {
}
public User(Long id, String name, String email, String department) {
this.id = id;
this.name = name;
this.email = email;
this.department = department;
}
// Getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
} | public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
} | repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\parametrizedtypereference\User.java | 1 |
请完成以下Java代码 | public I_M_PackagingTreeItem getRef_M_PackagingTreeItem() throws RuntimeException
{
return (I_M_PackagingTreeItem)MTable.get(getCtx(), I_M_PackagingTreeItem.Table_Name)
.getPO(getRef_M_PackagingTreeItem_ID(), get_TrxName()); }
/** Set Ref Packaging Tree Item.
@param Ref_M_PackagingTreeItem_ID Ref Packaging Tree Item */
@Override
public void setRef_M_PackagingTreeItem_ID (int Ref_M_PackagingTreeItem_ID)
{
if (Ref_M_PackagingTreeItem_ID < 1)
set_Value (COLUMNNAME_Ref_M_PackagingTreeItem_ID, null);
else
set_Value (COLUMNNAME_Ref_M_PackagingTreeItem_ID, Integer.valueOf(Ref_M_PackagingTreeItem_ID));
}
/** Get Ref Packaging Tree Item.
@return Ref Packaging Tree Item */
@Override
public int getRef_M_PackagingTreeItem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_M_PackagingTreeItem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Status AD_Reference_ID=540165 */
public static final int STATUS_AD_Reference_ID=540165;
/** Ready = R */
public static final String STATUS_Ready = "R";
/** Packed = P */
public static final String STATUS_Packed = "P";
/** Partially Packed = PP */
public static final String STATUS_PartiallyPacked = "PP";
/** UnPacked = UP */
public static final String STATUS_UnPacked = "UP";
/** Open = O */
public static final String STATUS_Open = "O";
/** Set Status.
@param Status Status */
@Override
public void setStatus (String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public String getStatus ()
{
return (String)get_Value(COLUMNNAME_Status);
}
/** Type AD_Reference_ID=540166 */
public static final int TYPE_AD_Reference_ID=540166;
/** Box = B */
public static final String TYPE_Box = "B"; | /** PackedItem = PI */
public static final String TYPE_PackedItem = "PI";
/** UnPackedItem = UI */
public static final String TYPE_UnPackedItem = "UI";
/** AvailableBox = AB */
public static final String TYPE_AvailableBox = "AB";
/** NonItem = NI */
public static final String TYPE_NonItem = "NI";
/** Set Art.
@param Type Art */
@Override
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
/** Set Gewicht.
@param Weight
Gewicht eines Produktes
*/
@Override
public void setWeight (BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
/** Get Gewicht.
@return Gewicht eines Produktes
*/
@Override
public BigDecimal getWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Weight);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackagingTreeItem.java | 1 |
请完成以下Java代码 | public class CorrelationKey {
protected String value;
protected Collection<EventPayloadInstance> parameterInstances;
public CorrelationKey(String value, Collection<EventPayloadInstance> parameterInstances) {
this.value = value;
this.parameterInstances = parameterInstances;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Collection<EventPayloadInstance> getParameterInstances() {
return parameterInstances;
}
public void setParameterInstances(Collection<EventPayloadInstance> parameterInstances) { | this.parameterInstances = parameterInstances;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CorrelationKey that = (CorrelationKey) o;
return Objects.equals(value, that.value) && Objects.equals(parameterInstances, that.parameterInstances);
}
@Override
public int hashCode() {
return value.hashCode(); // The value is determined by the parameterInstance, so no need to use them in the hashcode
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\consumer\CorrelationKey.java | 1 |
请完成以下Java代码 | public static int getKthElementSorted(int[] list1, int[] list2, int k) {
int length1 = list1.length, length2 = list2.length;
int[] combinedArray = new int[length1 + length2];
System.arraycopy(list1, 0, combinedArray, 0, list1.length);
System.arraycopy(list2, 0, combinedArray, list1.length, list2.length);
Arrays.sort(combinedArray);
return combinedArray[k-1];
}
public static int getKthElementMerge(int[] list1, int[] list2, int k) {
int i1 = 0, i2 = 0;
while(i1 < list1.length && i2 < list2.length && (i1 + i2) < k) {
if(list1[i1] < list2[i2]) { | i1++;
} else {
i2++;
}
}
if((i1 + i2) < k) {
return i1 < list1.length ? list1[k - i2 - 1] : list2[k - i1 - 1];
} else if(i1 > 0 && i2 > 0) {
return Math.max(list1[i1-1], list2[i2-1]);
} else {
return i1 == 0 ? list2[i2-1] : list1[i1-1];
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\kthsmallest\KthSmallest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public BookstoreService(AuthorRepository authorRepository,
BookRepository bookRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
}
public List<Book> fetchBooksOfAuthor(String name) {
return bookRepository.booksOfAuthor(name);
}
@Transactional
public void updateBooksOfAuthor(String name, List<Book> detachedBooks) {
Author author = authorRepository.authorAndBooks(name);
System.out.println("-------------------------------------------------");
// Remove the existing database rows that are no
// longer found in the incoming collection (detachedBooks)
List<Book> booksToRemove = author.getBooks().stream()
.filter(b -> !detachedBooks.contains(b)) | .collect(Collectors.toList());
booksToRemove .forEach(b -> author.removeBook(b));
// Update the existing database rows which can be found
// in the incoming collection (detachedBooks)
List<Book> newBooks = detachedBooks.stream()
.filter(b -> !author.getBooks().contains(b))
.collect(Collectors.toList());
detachedBooks.stream()
.filter(b -> !newBooks.contains(b))
.forEach((b) -> {
b.setAuthor(author);
Book mergedBook = bookRepository.save(b);
author.getBooks().set(
author.getBooks().indexOf(mergedBook), mergedBook);
});
// Add the rows found in the incoming collection,
// which cannot be found in the current database snapshot
newBooks.forEach(b -> author.addBook(b));
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootMergeCollections\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OrgTypeId implements RepoIdAware
{
@JsonCreator
public static OrgTypeId ofRepoId(final int repoId)
{
return new OrgTypeId(repoId);
}
public static OrgTypeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(final OrgTypeId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private OrgTypeId(final int repoId)
{ | this.repoId = Check.assumeGreaterThanZero(repoId, "AD_OrgType_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(final OrgTypeId id1, final OrgTypeId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\OrgTypeId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void stop() {
log.warn("debeziumEngine 监听实例关闭!");
debeziumEngine.close();
Thread.sleep(2000);
log.warn(ThreadPoolEnum.SQL_SERVER_LISTENER_POOL + "线程池关闭!");
executor.shutdown();
}
@Override
public boolean isRunning() {
return false;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(debeziumEngine, "DebeZiumEngine 不能为空!");
}
public enum ThreadPoolEnum {
/**
* 实例
*/
INSTANCE;
public static final String SQL_SERVER_LISTENER_POOL = "sql-server-listener-pool";
/**
* 线程池单例
*/
private final ExecutorService es;
/** | * 枚举 (构造器默认为私有)
*/
ThreadPoolEnum() {
final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(SQL_SERVER_LISTENER_POOL + "-%d").build();
es = new ThreadPoolExecutor(8, 16, 60,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(256),
threadFactory, new ThreadPoolExecutor.DiscardPolicy());
}
/**
* 公有方法
*
* @return ExecutorService
*/
public ExecutorService getInstance() {
return es;
}
}
}
} | repos\springboot-demo-master\debezium\src\main\java\com\et\debezium\config\ChangeEventConfig.java | 2 |
请完成以下Java代码 | public class PostalCodeImportProcess extends SimpleImportProcessTemplate<I_I_Postal>
{
@Override
public Class<I_I_Postal> getImportModelClass()
{
return I_I_Postal.class;
}
@Override
public String getImportTableName()
{
return I_I_Postal.Table_Name;
}
@Override
protected String getTargetTableName()
{
return I_C_Postal.Table_Name;
}
@Override
protected void updateAndValidateImportRecordsImpl()
{
}
@Override
protected String getImportOrderBySql()
{
return I_I_Postal.COLUMNNAME_Postal;
}
@Override
public I_I_Postal retrieveImportRecord(final Properties ctx, final ResultSet rs)
{
return new X_I_Postal(ctx, rs, ITrx.TRXNAME_ThreadInherited);
}
@Override
protected ImportRecordResult importRecord(
@NonNull final IMutable<Object> state_NOTUSED,
@NonNull final I_I_Postal importRecord, | final boolean isInsertOnly_NOTUSED)
{
return importPostalCode(importRecord);
}
private ImportRecordResult importPostalCode(@NonNull final I_I_Postal importRecord)
{
// the current handling for duplicates (postal code + country) is nonexistent.
// we blindly try to insert in db, and if there are unique constraints failing the records will automatically be marked as failed.
//noinspection UnusedAssignment
ImportRecordResult importResult = ImportRecordResult.Nothing;
final I_C_Postal cPostal = createNewCPostalCode(importRecord);
importResult = ImportRecordResult.Inserted;
importRecord.setC_Postal_ID(cPostal.getC_Postal_ID());
InterfaceWrapperHelper.save(importRecord);
return importResult;
}
private I_C_Postal createNewCPostalCode(final I_I_Postal importRecord)
{
final I_C_Postal cPostal = InterfaceWrapperHelper.create(getCtx(), I_C_Postal.class, ITrx.TRXNAME_ThreadInherited);
cPostal.setC_Country(Services.get(ICountryDAO.class).retrieveCountryByCountryCode(importRecord.getCountryCode()));
cPostal.setCity(importRecord.getCity());
cPostal.setPostal(importRecord.getPostal());
cPostal.setRegionName(importRecord.getRegionName());
// these 2 are not yet used
// importRecord.getValidFrom()
// importRecord.getValidTo()
InterfaceWrapperHelper.save(cPostal);
return cPostal;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\impexp\PostalCodeImportProcess.java | 1 |
请完成以下Java代码 | public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotionSession.java | 1 |
请完成以下Java代码 | public List<String> getAuthorities() {
return userService.getAuthorities();
}
/**
* GET /users/:login : get the "login" user.
*
* @param login the login of the user to find
* @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found)
*/
@GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
public ResponseEntity<UserDTO> getUser(@PathVariable String login) {
log.debug("REST request to get User : {}", login);
return ResponseUtil.wrapOrNotFound(
userService.getUserWithAuthoritiesByLogin(login)
.map(UserDTO::new));
} | /**
* DELETE /users/:login : delete the "login" User.
*
* @param login the login of the user to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
log.debug("REST request to delete User: {}", login);
userService.deleteUser(login);
return ResponseEntity.ok().headers(HeaderUtil.createAlert( "A user is deleted with identifier " + login, login)).build();
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\UserResource.java | 1 |
请完成以下Java代码 | private static ITranslatableString buildMessage(
@Nullable final IPricingContext pricingCtx,
final int documentLineNo,
final ProductId productId)
{
final TranslatableStringBuilder sb = TranslatableStrings.builder();
if (documentLineNo > 0)
{
if (!sb.isEmpty())
{
sb.append(", ");
}
sb.appendADElement("Line").append(": ").append(documentLineNo);
}
ProductId productIdEffective = null;
if (productId != null)
{
productIdEffective = productId;
}
else if (pricingCtx != null)
{
productIdEffective = pricingCtx.getProductId();
}
if (productIdEffective != null)
{
final String productName = Services.get(IProductBL.class).getProductValueAndName(productIdEffective);
if (!sb.isEmpty())
{
sb.append(", ");
}
sb.appendADElement("M_Product_ID").append(": ").append(productName);
}
final PricingSystemId pricingSystemId = pricingCtx == null ? null : pricingCtx.getPricingSystemId();
final PriceListId priceListId = pricingCtx == null ? null : pricingCtx.getPriceListId();
if (priceListId != null)
{
final String priceListName = Services.get(IPriceListDAO.class).getPriceListName(priceListId);
if (!sb.isEmpty())
{
sb.append(", ");
}
sb.appendADElement("M_PriceList_ID").append(": ").append(priceListName);
}
else if (pricingSystemId != null)
{
final String pricingSystemName = Services.get(IPriceListDAO.class).getPricingSystemName(pricingSystemId);
if (!sb.isEmpty())
{
sb.append(", ");
}
sb.appendADElement("M_PricingSystem_ID").append(": ").append(pricingSystemName);
}
final BPartnerId bpartnerId = pricingCtx == null ? null : pricingCtx.getBPartnerId();
if (bpartnerId != null)
{
String bpartnerName = Services.get(IBPartnerBL.class).getBPartnerValueAndName(bpartnerId);
if (!sb.isEmpty()) | {
sb.append(", ");
}
sb.appendADElement("C_BPartner_ID").append(": ").append(bpartnerName);
}
final CountryId countryId = pricingCtx == null ? null : pricingCtx.getCountryId();
if (countryId != null)
{
final ITranslatableString countryName = Services.get(ICountryDAO.class).getCountryNameById(countryId);
if (!sb.isEmpty())
{
sb.append(", ");
}
sb.appendADElement("C_Country_ID").append(": ").append(countryName);
}
final LocalDate priceDate = pricingCtx == null ? null : pricingCtx.getPriceDate();
if (priceDate != null)
{
if (!sb.isEmpty())
{
sb.append(", ");
}
sb.appendADElement("Date").append(": ").appendDate(priceDate);
}
//
sb.insertFirst(" - ");
sb.insertFirstADMessage(AD_Message);
return sb.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\exceptions\ProductNotOnPriceListException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public I_C_UOM getC_UOM()
{
return getDelegate().getC_UOM();
}
@Override
public PackingItemGroupingKey getGroupingKey()
{
return getDelegate().getGroupingKey();
}
@Override
public BPartnerId getBPartnerId()
{
return getDelegate().getBPartnerId();
}
@Override
public BPartnerLocationId getBPartnerLocationId()
{
return getDelegate().getBPartnerLocationId();
}
@Override
public void setPartsFrom(final IPackingItem packingItem)
{
getDelegate().setPartsFrom(packingItem);
}
@Override
public HUPIItemProductId getPackingMaterialId()
{
return getDelegate().getPackingMaterialId();
}
@Override
public void addParts(final IPackingItem packingItem)
{
getDelegate().addParts(packingItem);
}
public final IPackingItem addPartsAndReturn(final IPackingItem packingItem)
{
return getDelegate().addPartsAndReturn(packingItem);
}
@Override
public void addParts(final PackingItemParts toAdd) | {
getDelegate().addParts(toAdd);
}
@Override
public Set<WarehouseId> getWarehouseIds()
{
return getDelegate().getWarehouseIds();
}
@Override
public Set<ShipmentScheduleId> getShipmentScheduleIds()
{
return getDelegate().getShipmentScheduleIds();
}
@Override
public IPackingItem subtractToPackingItem(
final Quantity subtrahent,
final Predicate<PackingItemPart> acceptPartPredicate)
{
return getDelegate().subtractToPackingItem(subtrahent, acceptPartPredicate);
}
@Override
public PackingItemParts subtract(final Quantity subtrahent)
{
return getDelegate().subtract(subtrahent);
}
@Override
public PackingItemParts getParts()
{
return getDelegate().getParts();
}
@Override
public ProductId getProductId()
{
return getDelegate().getProductId();
}
@Override
public Quantity getQtySum()
{
return getDelegate().getQtySum();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\ForwardingPackingItem.java | 2 |
请完成以下Java代码 | public String getContentId() {
return contentId;
}
public void setContentId(String contentId) {
this.contentId = contentId;
}
public ByteArrayEntity getContent() {
return content;
}
public void setContent(ByteArrayEntity content) {
this.content = content;
} | public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityImpl.java | 1 |
请完成以下Java代码 | public Optional<NotificationTemplate> findNotificationTemplateByTenantIdAndType(TenantId tenantId, NotificationType notificationType) {
return findNotificationTemplatesByTenantIdAndNotificationTypes(tenantId, List.of(notificationType), new PageLink(1)).getData()
.stream().findFirst();
}
@Override
public int countNotificationTemplatesByTenantIdAndNotificationTypes(TenantId tenantId, Collection<NotificationType> notificationTypes) {
return notificationTemplateDao.countByTenantIdAndNotificationTypes(tenantId, notificationTypes);
}
@Override
public void deleteNotificationTemplateById(TenantId tenantId, NotificationTemplateId id) {
deleteEntity(tenantId, id, false);
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
if (!force) {
if (notificationRequestDao.existsByTenantIdAndStatusAndTemplateId(tenantId, NotificationRequestStatus.SCHEDULED, (NotificationTemplateId) id)) {
throw new IllegalArgumentException("Notification template is referenced by scheduled notification request");
}
if (tenantId.isSysTenantId()) {
NotificationTemplate notificationTemplate = findNotificationTemplateById(tenantId, (NotificationTemplateId) id);
if (notificationTemplate.getNotificationType().isSystem()) {
throw new IllegalArgumentException("System notification template cannot be deleted");
}
}
}
try {
notificationTemplateDao.removeById(tenantId, id.getId());
} catch (Exception e) {
checkConstraintViolation(e, Map.of(
"fk_notification_rule_template_id", "Notification template is referenced by notification rule"
));
throw e;
}
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build());
}
@Override
public void deleteNotificationTemplatesByTenantId(TenantId tenantId) {
notificationTemplateDao.removeByTenantId(tenantId);
}
@Override
public void deleteByTenantId(TenantId tenantId) { | deleteNotificationTemplatesByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findNotificationTemplateById(tenantId, new NotificationTemplateId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(notificationTemplateDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_TEMPLATE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationTemplateService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | CorrelationScopeCustomizer correlationFieldsCorrelationScopeCustomizer() {
return (builder) -> {
Correlation correlationProperties = this.tracingProperties.getBaggage().getCorrelation();
for (String field : correlationProperties.getFields()) {
BaggageField baggageField = BaggageField.create(field);
SingleCorrelationField correlationField = SingleCorrelationField.newBuilder(baggageField)
.flushOnUpdate()
.build();
builder.add(correlationField);
}
};
}
@Bean
@ConditionalOnMissingBean(CorrelationScopeDecorator.class)
ScopeDecorator correlationScopeDecorator(CorrelationScopeDecorator.Builder builder) {
return builder.build();
} | }
/**
* Propagates neither traces nor baggage.
*/
@Configuration(proxyBeanMethods = false)
static class NoPropagation {
@Bean
@ConditionalOnMissingBean(Factory.class)
CompositePropagationFactory noopPropagationFactory() {
return CompositePropagationFactory.noop();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-brave\src\main\java\org\springframework\boot\micrometer\tracing\brave\autoconfigure\BravePropagationConfigurations.java | 2 |
请完成以下Java代码 | protected OrderingProperty getLastConfiguredProperty() {
return !orderingProperties.isEmpty() ? orderingProperties.get(orderingProperties.size() - 1) : null;
}
/**
* The field to sort by.
*/
public enum SortingField {
CREATE_TIME("createTime");
private final String name;
SortingField(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
/**
* The direction of createTime.
*/
public enum Direction {
ASC, DESC;
public String asString() {
return super.name().toLowerCase();
}
}
/**
* Static Class that encapsulates an ordering property with a field and its direction.
*/
public static class OrderingProperty {
protected SortingField field;
protected Direction direction;
/**
* Static factory method to create {@link OrderingProperty} out of a field and its corresponding {@link Direction}.
*/
public static OrderingProperty of(SortingField field, Direction direction) {
OrderingProperty result = new OrderingProperty(); | result.setField(field);
result.setDirection(direction);
return result;
}
public void setField(SortingField field) {
this.field = field;
}
public SortingField getField() {
return this.field;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
public Direction getDirection() {
return this.direction;
}
}
} | repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\OrderingConfig.java | 1 |
请完成以下Java代码 | public boolean seeksAfterHandling() {
return this.recordErrorHandler.seeksAfterHandling();
}
@Override
public boolean deliveryAttemptHeader() {
return this.recordErrorHandler.deliveryAttemptHeader();
}
@Override
public void handleOtherException(Exception thrownException, Consumer<?, ?> consumer,
MessageListenerContainer container, boolean batchListener) {
if (batchListener) {
this.batchErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
else {
this.recordErrorHandler.handleOtherException(thrownException, consumer, container, batchListener);
}
}
@Override
public boolean handleOne(Exception thrownException, ConsumerRecord<?, ?> record, Consumer<?, ?> consumer,
MessageListenerContainer container) {
return this.recordErrorHandler.handleOne(thrownException, record, consumer, container);
}
@Override
public void handleRemaining(Exception thrownException, List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer,
MessageListenerContainer container) {
this.recordErrorHandler.handleRemaining(thrownException, records, consumer, container);
}
@Override
public void handleBatch(Exception thrownException, ConsumerRecords<?, ?> data, Consumer<?, ?> consumer,
MessageListenerContainer container, Runnable invokeListener) { | this.batchErrorHandler.handleBatch(thrownException, data, consumer, container, invokeListener);
}
@Override
public int deliveryAttempt(TopicPartitionOffset topicPartitionOffset) {
return this.recordErrorHandler.deliveryAttempt(topicPartitionOffset);
}
@Override
public void clearThreadState() {
this.batchErrorHandler.clearThreadState();
this.recordErrorHandler.clearThreadState();
}
@Override
public boolean isAckAfterHandle() {
return this.recordErrorHandler.isAckAfterHandle();
}
@Override
public void setAckAfterHandle(boolean ack) {
this.batchErrorHandler.setAckAfterHandle(ack);
this.recordErrorHandler.setAckAfterHandle(ack);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\CommonMixedErrorHandler.java | 1 |
请完成以下Java代码 | public Set<String> getFieldNames()
{
return elementBuilders
.stream()
.flatMap(element -> element.getFieldNames().stream())
.collect(GuavaCollectors.toImmutableSet());
}
public Builder setIdFieldName(final String idFieldName)
{
this.idFieldName = idFieldName;
return this;
}
private String getIdFieldName()
{
return idFieldName;
}
public Builder setHasAttributesSupport(final boolean hasAttributesSupport)
{
this.hasAttributesSupport = hasAttributesSupport;
return this;
}
public Builder setIncludedViewLayout(final IncludedViewLayout includedViewLayout)
{
this.includedViewLayout = includedViewLayout;
return this;
}
public Builder clearViewCloseActions()
{
allowedViewCloseActions = new LinkedHashSet<>();
return this;
}
public Builder allowViewCloseAction(@NonNull final ViewCloseAction viewCloseAction)
{
if (allowedViewCloseActions == null)
{
allowedViewCloseActions = new LinkedHashSet<>();
}
allowedViewCloseActions.add(viewCloseAction);
return this; | }
private ImmutableSet<ViewCloseAction> getAllowedViewCloseActions()
{
return allowedViewCloseActions != null
? ImmutableSet.copyOf(allowedViewCloseActions)
: DEFAULT_allowedViewCloseActions;
}
public Builder setHasTreeSupport(final boolean hasTreeSupport)
{
this.hasTreeSupport = hasTreeSupport;
return this;
}
public Builder setTreeCollapsible(final boolean treeCollapsible)
{
this.treeCollapsible = treeCollapsible;
return this;
}
public Builder setTreeExpandedDepth(final int treeExpandedDepth)
{
this.treeExpandedDepth = treeExpandedDepth;
return this;
}
public Builder setAllowOpeningRowDetails(final boolean allowOpeningRowDetails)
{
this.allowOpeningRowDetails = allowOpeningRowDetails;
return this;
}
public Builder setFocusOnFieldName(final String focusOnFieldName)
{
this.focusOnFieldName = focusOnFieldName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\ViewLayout.java | 1 |
请完成以下Java代码 | public class QuantityUOMConverters
{
public static QuantityUOMConverter noConversion()
{
return NoConversion.instance;
}
private static class NoConversion implements QuantityUOMConverter
{
public static final transient QuantityUOMConverters.NoConversion instance = new QuantityUOMConverters.NoConversion();
@Override
public Quantity convertQuantityTo(
@NonNull final Quantity qty,
@Nullable final ProductId productId,
@NonNull final UomId targetUOMId)
{ | if (UomId.equals(qty.getUomId(), targetUOMId))
{
return qty;
}
if (UomId.equals(qty.getSourceUomId(), targetUOMId))
{
return qty.switchToSource();
}
else
{
throw new QuantitiesUOMNotMatchingExpection("Cannot convert " + qty + " to " + targetUOMId);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\QuantityUOMConverters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommonSecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public IgnoreUrlsConfig ignoreUrlsConfig() {
return new IgnoreUrlsConfig();
}
@Bean
public JwtTokenUtil jwtTokenUtil() {
return new JwtTokenUtil();
}
@Bean
public RestfulAccessDeniedHandler restfulAccessDeniedHandler() {
return new RestfulAccessDeniedHandler();
}
@Bean
public RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
return new RestAuthenticationEntryPoint();
}
@Bean
public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
return new JwtAuthenticationTokenFilter();
} | @ConditionalOnBean(name = "dynamicSecurityService")
@Bean
public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
return new DynamicAccessDecisionManager();
}
@ConditionalOnBean(name = "dynamicSecurityService")
@Bean
public DynamicSecurityMetadataSource dynamicSecurityMetadataSource() {
return new DynamicSecurityMetadataSource();
}
@ConditionalOnBean(name = "dynamicSecurityService")
@Bean
public DynamicSecurityFilter dynamicSecurityFilter(){
return new DynamicSecurityFilter();
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\config\CommonSecurityConfig.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.