instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
|
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Review) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Review{" + "id=" + id + ", content=" + content + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Review.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setPersonRepository(PersonRepository repo) {
this.repo = repo;
}
public Optional<Person> findOne(String id) {
return repo.findById(id);
}
public List<Person> findAll() {
List<Person> people = new ArrayList<>();
Iterator<Person> it = repo.findAll().iterator();
while (it.hasNext()) {
people.add(it.next());
}
return people;
}
public List<Person> findByFirstName(String firstName) {
return repo.findByFirstName(firstName);
}
public List<Person> findByLastName(String lastName) {
|
return repo.findByLastName(lastName);
}
public void create(Person person) {
person.setCreated(DateTime.now());
repo.save(person);
}
public void update(Person person) {
person.setUpdated(DateTime.now());
repo.save(person);
}
public void delete(Person person) {
repo.delete(person);
}
}
|
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\PersonRepositoryService.java
| 2
|
请完成以下Java代码
|
public AdminSettingsId getId() {
return super.getId();
}
@Schema(description = "Timestamp of the settings creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY)
@Override
public long getCreatedTime() {
return super.getCreatedTime();
}
@Schema(description = "JSON object with Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY)
public TenantId getTenantId() {
return tenantId;
}
public void setTenantId(TenantId tenantId) {
this.tenantId = tenantId;
}
@Schema(description = "The Administration Settings key, (e.g. 'general' or 'mail')", example = "mail")
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Schema(description = "JSON representation of the Administration Settings value")
public JsonNode getJsonValue() {
return jsonValue;
}
public void setJsonValue(JsonNode jsonValue) {
this.jsonValue = jsonValue;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((jsonValue == null) ? 0 : jsonValue.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
|
return false;
if (getClass() != obj.getClass())
return false;
AdminSettings other = (AdminSettings) obj;
if (jsonValue == null) {
if (other.jsonValue != null)
return false;
} else if (!jsonValue.equals(other.jsonValue))
return false;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("AdminSettings [key=");
builder.append(key);
builder.append(", jsonValue=");
builder.append(jsonValue);
builder.append(", createdTime=");
builder.append(createdTime);
builder.append(", id=");
builder.append(id);
builder.append("]");
return builder.toString();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\AdminSettings.java
| 1
|
请完成以下Java代码
|
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 处理 ServiceException 异常
*/
@ResponseBody
@ExceptionHandler(value = ServiceException.class)
public CommonResult serviceExceptionHandler(HttpServletRequest req, ServiceException ex) {
logger.debug("[serviceExceptionHandler]", ex);
// 包装 CommonResult 结果
return CommonResult.error(ex.getCode(), ex.getMessage());
}
/**
* 处理 MissingServletRequestParameterException 异常
*
* SpringMVC 参数不正确
*/
@ResponseBody
@ExceptionHandler(value = MissingServletRequestParameterException.class)
public CommonResult missingServletRequestParameterExceptionHandler(HttpServletRequest req, MissingServletRequestParameterException ex) {
logger.debug("[missingServletRequestParameterExceptionHandler]", ex);
// 包装 CommonResult 结果
return CommonResult.error(ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getCode(),
|
ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getMessage());
}
/**
* 处理其它 Exception 异常
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(HttpServletRequest req, Exception e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 返回 ERROR CommonResult
return CommonResult.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
ServiceExceptionEnum.SYS_ERROR.getMessage());
}
}
|
repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-02\src\main\java\cn\iocoder\springboot\lab23\springmvc\core\web\GlobalExceptionHandler.java
| 1
|
请完成以下Java代码
|
public List<MetricsIntervalResultDto> interval(UriInfo uriInfo) {
MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
final String name = queryParameters.getFirst(QUERY_PARAM_NAME);
MetricsQuery query = getProcessEngine().getManagementService()
.createMetricsQuery()
.name(name)
.reporter(queryParameters.getFirst(QUERY_PARAM_REPORTER));
applyQueryParams(query, queryParameters);
List<MetricIntervalValue> metrics;
LongConverter longConverter = new LongConverter();
longConverter.setObjectMapper(objectMapper);
if (queryParameters.getFirst(QUERY_PARAM_INTERVAL) != null) {
long interval = longConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_INTERVAL));
metrics = query.interval(interval);
} else {
metrics = query.interval();
}
final List<MetricsIntervalResultDto> dtoList = convertToDtos(metrics);
if (name != null) {
dtoList.forEach(dto -> dto.setName(name));
}
return dtoList;
}
@Override
public Response deleteTaskMetrics(String dateString) {
Date date = dateConverter.convertQueryParameterToType(dateString);
getProcessEngine().getManagementService().deleteTaskMetrics(date);
// return no content (204) since resource is deleted
return Response.noContent().build();
}
protected void applyQueryParams(MetricsQuery query, MultivaluedMap<String, String> queryParameters) {
if(queryParameters.getFirst(QUERY_PARAM_START_DATE) != null) {
Date startDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_START_DATE));
query.startDate(startDate);
}
|
if(queryParameters.getFirst(QUERY_PARAM_END_DATE) != null) {
Date endDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_END_DATE));
query.endDate(endDate);
}
IntegerConverter intConverter = new IntegerConverter();
intConverter.setObjectMapper(objectMapper);
if (queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT) != null) {
int firstResult = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT));
query.offset(firstResult);
}
if (queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS) != null) {
int maxResults = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS));
query.limit(maxResults);
}
if(queryParameters.getFirst(QUERY_PARAM_AGG_BY_REPORTER) != null) {
query.aggregateByReporter();
}
}
protected List<MetricsIntervalResultDto> convertToDtos(List<MetricIntervalValue> metrics) {
List<MetricsIntervalResultDto> intervalMetrics = new ArrayList<>();
for (MetricIntervalValue m : metrics) {
intervalMetrics.add(new MetricsIntervalResultDto(m));
}
return intervalMetrics;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\MetricsRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public HistoricCaseInstanceEntity create(CaseInstance caseInstance) {
return dataManager.create(caseInstance);
}
@Override
public HistoricCaseInstanceQuery createHistoricCaseInstanceQuery() {
return new HistoricCaseInstanceQueryImpl(engineConfiguration.getCommandExecutor(), engineConfiguration);
}
@Override
public List<HistoricCaseInstanceEntity> findHistoricCaseInstancesByCaseDefinitionId(String caseDefinitionId) {
return dataManager.findHistoricCaseInstancesByCaseDefinitionId(caseDefinitionId);
}
@Override
public List<String> findHistoricCaseInstanceIdsByParentIds(Collection<String> caseInstanceIds) {
return dataManager.findHistoricCaseInstanceIdsByParentIds(caseInstanceIds);
}
@Override
public List<HistoricCaseInstance> findByCriteria(HistoricCaseInstanceQuery query) {
return dataManager.findByCriteria((HistoricCaseInstanceQueryImpl) query);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findWithVariablesByQueryCriteria(HistoricCaseInstanceQuery query) {
return dataManager.findWithVariablesByQueryCriteria((HistoricCaseInstanceQueryImpl) query);
}
@Override
public List<HistoricCaseInstance> findIdsByCriteria(HistoricCaseInstanceQuery query) {
return dataManager.findIdsByCriteria((HistoricCaseInstanceQueryImpl) query);
|
}
@Override
public long countByCriteria(HistoricCaseInstanceQuery query) {
return dataManager.countByCriteria((HistoricCaseInstanceQueryImpl) query);
}
@Override
public void deleteHistoricCaseInstances(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
dataManager.deleteHistoricCaseInstances(historicCaseInstanceQuery);
}
@Override
public void bulkDeleteHistoricCaseInstances(Collection<String> caseInstanceIds) {
dataManager.bulkDeleteHistoricCaseInstances(caseInstanceIds);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public void remove()
{
throw new UnsupportedOperationException();
}
/**
* 遍历下一个终止路径
*
* @param parent 父节点
* @param charPoint 子节点的char
* @return
*/
private int getNext(int parent, int charPoint)
{
int startChar = charPoint + 1;
int baseParent = getBase(parent);
int from = parent;
for (int i = startChar; i < charMap.getCharsetSize(); i++)
{
int to = baseParent + i;
if (check.size() > to && check.get(to) == from)
{
path.append(i);
from = to;
path.append(from);
baseParent = base.get(from);
if (getCheck(baseParent + UNUSED_CHAR_VALUE) == from)
{
value = getLeafValue(getBase(baseParent + UNUSED_CHAR_VALUE));
int[] ids = new int[path.size() / 2];
for (int k = 0, j = 1; j < path.size(); ++k, j += 2)
{
ids[k] = path.get(j);
}
key = charMap.toString(ids);
path.append(UNUSED_CHAR_VALUE);
currentBase = baseParent;
|
return from;
}
else
{
return getNext(from, 0);
}
}
}
return -1;
}
@Override
public String toString()
{
return key + '=' + value;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrieInteger.java
| 1
|
请完成以下Java代码
|
public Map<String, String> getHeaders() {
return getResponseParameter(PARAM_NAME_RESPONSE_HEADERS);
}
public String getHeader(String field) {
Map<String, String> headers = getHeaders();
if (headers != null) {
return headers.get(field);
} else {
return null;
}
}
protected void collectResponseParameters(Map<String, Object> responseParameters) {
responseParameters.put(PARAM_NAME_STATUS_CODE, httpResponse.getCode());
collectResponseHeaders();
if (httpResponse.getEntity() != null) {
try {
String response = IoUtil.inputStreamAsString(httpResponse.getEntity().getContent());
responseParameters.put(PARAM_NAME_RESPONSE, response);
} catch (IOException e) {
throw LOG.unableToReadResponse(e);
|
} finally {
IoUtil.closeSilently(httpResponse);
}
}
}
protected void collectResponseHeaders() {
Map<String, String> headers = new HashMap<>();
for (Header header : httpResponse.getHeaders()) {
headers.put(header.getName(), header.getValue());
}
responseParameters.put(PARAM_NAME_RESPONSE_HEADERS, headers);
}
protected Closeable getClosable() {
return httpResponse;
}
}
|
repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\HttpResponseImpl.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Letter letter = (Letter) o;
return Objects.equals(returningAddress, letter.returningAddress) &&
Objects.equals(insideAddress, letter.insideAddress) &&
Objects.equals(dateOfLetter, letter.dateOfLetter) &&
Objects.equals(salutation, letter.salutation) &&
Objects.equals(body, letter.body) &&
Objects.equals(closing, letter.closing);
}
@Override
public int hashCode() {
return Objects.hash(returningAddress, insideAddress, dateOfLetter, salutation, body, closing);
}
@Override
public String toString() {
return "Letter{" + "returningAddress='" + returningAddress + '\'' + ", insideAddress='" + insideAddress + '\''
+ ", dateOfLetter=" + dateOfLetter + ", salutation='" + salutation + '\'' + ", body='" + body + '\''
+ ", closing='" + closing + '\'' + '}';
}
static Letter createLetter(String salutation, String body) {
return new Letter(salutation, body);
}
static BiFunction<String, String, Letter> SIMPLE_LETTER_CREATOR = //
(salutation, body) -> new Letter(salutation, body);
static Function<String, Function<String, Letter>> SIMPLE_CURRIED_LETTER_CREATOR = //
saluation -> body -> new Letter(saluation, body);
static Function<String, Function<String, Function<LocalDate, Function<String, Function<String, Function<String, Letter>>>>>> LETTER_CREATOR = //
returnAddress
-> closing
-> dateOfLetter
-> insideAddress
-> salutation
-> body
-> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing);
static AddReturnAddress builder() {
return returnAddress
-> closing
-> dateOfLetter
-> insideAddress
-> salutation
|
-> body
-> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing);
}
interface AddReturnAddress {
Letter.AddClosing withReturnAddress(String returnAddress);
}
interface AddClosing {
Letter.AddDateOfLetter withClosing(String closing);
}
interface AddDateOfLetter {
Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter);
}
interface AddInsideAddress {
Letter.AddSalutation withInsideAddress(String insideAddress);
}
interface AddSalutation {
Letter.AddBody withSalutation(String salutation);
}
interface AddBody {
Letter withBody(String body);
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-functional\src\main\java\com\baeldung\currying\Letter.java
| 1
|
请完成以下Java代码
|
public class ListWorkflowsProcessor extends AbstractElementTagProcessor {
private static final String TAG_NAME = "listworkflows";
private static final String DEFAULT_FRAGMENT_NAME = "~{temporalwebdialect :: listworkflows}";
private static final int PRECEDENCE = 10000;
private final ApplicationContext ctx;
private WorkflowClient workflowClient;
public ListWorkflowsProcessor(final String dialectPrefix, ApplicationContext ctx,
WorkflowClient workflowClient) {
super(TemplateMode.HTML, dialectPrefix, TAG_NAME, true, null, false, PRECEDENCE);
this.ctx = ctx;
this.workflowClient = workflowClient;
}
@Override
protected void doProcess(ITemplateContext templateContext, IProcessableElementTag processInstancesTag,
IElementTagStructureHandler structureHandler) {
|
final IEngineConfiguration configuration = templateContext.getConfiguration();
IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
DialectUtils dialectUtils = new DialectUtils(workflowClient);
structureHandler.setLocalVariable("workflows", dialectUtils.listExecutions(
null, null
));
final IModelFactory modelFactory = templateContext.getModelFactory();
final IModel model = modelFactory.createModel();
model.add(modelFactory.createOpenElementTag("div", "th:replace", dialectUtils.getFragmentName(
processInstancesTag.getAttributeValue("fragment"), DEFAULT_FRAGMENT_NAME, parser, templateContext)));
model.add(modelFactory.createCloseElementTag("div"));
structureHandler.replaceWith(model, true);
}
}
|
repos\spring-boot-demo-main\src\main\java\com\temporal\demos\temporalspringbootdemo\webui\processor\ListWorkflowsProcessor.java
| 1
|
请完成以下Java代码
|
public I_AD_Desktop getAD_Desktop() throws RuntimeException
{
return (I_AD_Desktop)MTable.get(getCtx(), I_AD_Desktop.Table_Name)
.getPO(getAD_Desktop_ID(), get_TrxName()); }
/** Set Desktop.
@param AD_Desktop_ID
Collection of Workbenches
*/
public void setAD_Desktop_ID (int AD_Desktop_ID)
{
if (AD_Desktop_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, Integer.valueOf(AD_Desktop_ID));
}
/** Get Desktop.
@return Collection of Workbenches
*/
public int getAD_Desktop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Desktop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Desktop Workbench.
@param AD_DesktopWorkbench_ID Desktop Workbench */
public void setAD_DesktopWorkbench_ID (int AD_DesktopWorkbench_ID)
{
if (AD_DesktopWorkbench_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_DesktopWorkbench_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_DesktopWorkbench_ID, Integer.valueOf(AD_DesktopWorkbench_ID));
}
/** Get Desktop Workbench.
@return Desktop Workbench */
public int getAD_DesktopWorkbench_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_DesktopWorkbench_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Workbench getAD_Workbench() throws RuntimeException
{
return (I_AD_Workbench)MTable.get(getCtx(), I_AD_Workbench.Table_Name)
.getPO(getAD_Workbench_ID(), get_TrxName()); }
/** Set Workbench.
@param AD_Workbench_ID
Collection of windows, reports
|
*/
public void setAD_Workbench_ID (int AD_Workbench_ID)
{
if (AD_Workbench_ID < 1)
set_Value (COLUMNNAME_AD_Workbench_ID, null);
else
set_Value (COLUMNNAME_AD_Workbench_ID, Integer.valueOf(AD_Workbench_ID));
}
/** Get Workbench.
@return Collection of windows, reports
*/
public int getAD_Workbench_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workbench_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(getAD_Workbench_ID()));
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_DesktopWorkbench.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getProtocol() {
return this.protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public boolean isReloadOnUpdate() {
return this.reloadOnUpdate;
}
public void setReloadOnUpdate(boolean reloadOnUpdate) {
this.reloadOnUpdate = reloadOnUpdate;
}
public static class Options {
/**
* Supported SSL ciphers.
*/
private @Nullable Set<String> ciphers;
/**
* Enabled SSL protocols.
*/
private @Nullable Set<String> enabledProtocols;
public @Nullable Set<String> getCiphers() {
return this.ciphers;
}
public void setCiphers(@Nullable Set<String> ciphers) {
this.ciphers = ciphers;
}
public @Nullable Set<String> getEnabledProtocols() {
return this.enabledProtocols;
}
public void setEnabledProtocols(@Nullable Set<String> enabledProtocols) {
this.enabledProtocols = enabledProtocols;
}
}
public static class Key {
/**
* The password used to access the key in the key store.
*/
private @Nullable String password;
|
/**
* The alias that identifies the key in the key store.
*/
private @Nullable String alias;
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getAlias() {
return this.alias;
}
public void setAlias(@Nullable String alias) {
this.alias = alias;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\SslBundleProperties.java
| 2
|
请完成以下Java代码
|
public Optional<ExternalSystem> getOptionalByType(@NonNull final ExternalSystemType type)
{
return getMap().getOptionalByType(type);
}
public Optional<ExternalSystem> getOptionalByValue(@NonNull final String value)
{
return getMap().getOptionalByType(ExternalSystemType.ofValue(value));
}
@NonNull
public ExternalSystem getById(@NonNull final ExternalSystemId id)
{
return getMap().getById(id);
}
private static ExternalSystem fromRecord(@NonNull final I_ExternalSystem externalSystemRecord)
{
return ExternalSystem.builder()
.id(ExternalSystemId.ofRepoId(externalSystemRecord.getExternalSystem_ID()))
.type(ExternalSystemType.ofValue(externalSystemRecord.getValue()))
.name(externalSystemRecord.getName())
.build();
}
public ExternalSystem create(@NonNull final ExternalSystemCreateRequest request)
{
final I_ExternalSystem record = InterfaceWrapperHelper.newInstance(I_ExternalSystem.class);
record.setName(request.getName());
record.setValue(request.getType().getValue());
InterfaceWrapperHelper.save(record);
return fromRecord(record);
|
}
@Nullable
public ExternalSystem getByLegacyCodeOrValueOrNull(@NonNull final String value)
{
final ExternalSystemMap map = getMap();
return CoalesceUtil.coalesceSuppliers(
() -> map.getByTypeOrNull(ExternalSystemType.ofValue(value)),
() -> {
final ExternalSystemType externalSystemType = ExternalSystemType.ofLegacyCodeOrNull(value);
return externalSystemType != null ? map.getByTypeOrNull(externalSystemType) : null;
}
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemRepository.java
| 1
|
请完成以下Java代码
|
public TranslatableStringBuilder append(final int value)
{
return append(NumberTranslatableString.of(value));
}
public TranslatableStringBuilder appendDate(@NonNull final Date value)
{
return append(DateTimeTranslatableString.ofDate(value));
}
public TranslatableStringBuilder appendDate(@NonNull final LocalDate value)
{
return append(TranslatableStrings.date(value));
}
public TranslatableStringBuilder appendDate(
@Nullable final LocalDate value,
@Nullable final String defaultValueIfNull)
{
return value != null ? appendDate(value) : append(defaultValueIfNull);
}
public TranslatableStringBuilder appendTemporal(
@Nullable final Temporal value,
@Nullable final String defaultValueIfNull)
{
return value != null ? append(TranslatableStrings.temporal(value)) : append(defaultValueIfNull);
}
public TranslatableStringBuilder appendDateTime(@NonNull final Date value)
{
return append(TranslatableStrings.dateAndTime(value));
}
public TranslatableStringBuilder appendDateTime(@NonNull final Instant value)
{
return append(DateTimeTranslatableString.ofDateTime(value));
}
public TranslatableStringBuilder appendDateTime(@NonNull final ZonedDateTime value)
{
return append(DateTimeTranslatableString.ofDateTime(value));
}
public TranslatableStringBuilder appendTimeZone(
@NonNull final ZoneId zoneId,
@NonNull final TextStyle textStyle)
{
return append(TimeZoneTranslatableString.ofZoneId(zoneId, textStyle));
}
public TranslatableStringBuilder append(final Boolean value)
{
if (value == null)
{
return append("?");
}
else
{
return append(msgBL.getTranslatableMsgText(value));
}
}
|
public TranslatableStringBuilder appendADMessage(
final AdMessageKey adMessage,
final Object... msgParameters)
{
final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters);
return append(value);
}
@Deprecated
public TranslatableStringBuilder appendADMessage(
@NonNull final String adMessage,
final Object... msgParameters)
{
return appendADMessage(AdMessageKey.of(adMessage), msgParameters);
}
public TranslatableStringBuilder insertFirstADMessage(
final AdMessageKey adMessage,
final Object... msgParameters)
{
final ITranslatableString value = msgBL.getTranslatableMsgText(adMessage, msgParameters);
return insertFirst(value);
}
@Deprecated
public TranslatableStringBuilder insertFirstADMessage(
final String adMessage,
final Object... msgParameters)
{
return insertFirstADMessage(AdMessageKey.of(adMessage), msgParameters);
}
public TranslatableStringBuilder appendADElement(final String columnName)
{
final ITranslatableString value = msgBL.translatable(columnName);
return append(value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableStringBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public EventResponse getEvent(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "eventId") @PathVariable("eventId") String eventId) {
HistoricTaskInstance task = getHistoricTaskFromRequest(taskId);
Event event = taskService.getEvent(eventId);
if (event == null || !task.getId().equals(event.getTaskId())) {
throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an event with id '" + eventId + "'.", Event.class);
}
return restResponseFactory.createEventResponse(event);
}
@ApiOperation(value = "Delete an event on a task", tags = { "Tasks" }, code = 204)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the task was found and the events are returned."),
@ApiResponse(code = 404, message = "Indicates the requested task was not found or the task does not have the requested event.")
})
@DeleteMapping(value = "/runtime/tasks/{taskId}/events/{eventId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteEvent(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "eventId") @PathVariable("eventId") String eventId) {
|
// Check if task exists
Task task = getTaskFromRequestWithoutAccessCheck(taskId);
Event event = taskService.getEvent(eventId);
if (event == null || event.getTaskId() == null || !event.getTaskId().equals(task.getId())) {
throw new FlowableObjectNotFoundException("Task '" + task.getId() + "' does not have an event with id '" + event + "'.", Event.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.deleteTaskEvent(task, event);
}
taskService.deleteComment(eventId);
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskEventResource.java
| 2
|
请完成以下Java代码
|
public Integer handle(TotalProductsShippedQuery query) {
AtomicInteger result = new AtomicInteger();
orders.find(shippedProductFilter(query.getProductId()))
.map(d -> d.get(PRODUCTS_PROPERTY_NAME, Document.class))
.map(d -> d.getInteger(query.getProductId(), 0))
.forEach(result::addAndGet);
return result.get();
}
@QueryHandler
public Order handle(OrderUpdatesQuery query) {
return getOrder(query.getOrderId()).orElse(null);
}
@Override
public void reset(List<Order> orderList) {
orders.deleteMany(new Document());
orderList.forEach(o -> orders.insertOne(orderToDocument(o)));
}
private Optional<Order> getOrder(String orderId) {
return Optional.ofNullable(orders.find(eq(ORDER_ID_PROPERTY_NAME, orderId))
.first())
.map(this::documentToOrder);
}
private Order emitUpdate(Order order) {
emitter.emit(OrderUpdatesQuery.class, q -> order.getOrderId()
.equals(q.getOrderId()), order);
return order;
}
private Order updateOrder(Order order, Consumer<Order> updateFunction) {
updateFunction.accept(order);
return order;
}
private UpdateResult persistUpdate(Order order) {
return orders.replaceOne(eq(ORDER_ID_PROPERTY_NAME, order.getOrderId()), orderToDocument(order));
}
private void update(String orderId, Consumer<Order> updateFunction) {
UpdateResult result = getOrder(orderId).map(o -> updateOrder(o, updateFunction))
.map(this::emitUpdate)
.map(this::persistUpdate)
|
.orElse(null);
logger.info("Result of updating order with orderId '{}': {}", orderId, result);
}
private Document orderToDocument(Order order) {
return new Document(ORDER_ID_PROPERTY_NAME, order.getOrderId()).append(PRODUCTS_PROPERTY_NAME, order.getProducts())
.append(ORDER_STATUS_PROPERTY_NAME, order.getOrderStatus()
.toString());
}
private Order documentToOrder(@NonNull Document document) {
Order order = new Order(document.getString(ORDER_ID_PROPERTY_NAME));
Document products = document.get(PRODUCTS_PROPERTY_NAME, Document.class);
products.forEach((k, v) -> order.getProducts()
.put(k, (Integer) v));
String status = document.getString(ORDER_STATUS_PROPERTY_NAME);
if (OrderStatus.CONFIRMED.toString()
.equals(status)) {
order.setOrderConfirmed();
} else if (OrderStatus.SHIPPED.toString()
.equals(status)) {
order.setOrderShipped();
}
return order;
}
private Bson shippedProductFilter(String productId) {
return and(eq(ORDER_STATUS_PROPERTY_NAME, OrderStatus.SHIPPED.toString()), exists(String.format(PRODUCTS_PROPERTY_NAME + ".%s", productId)));
}
}
|
repos\tutorials-master\patterns-modules\axon\src\main\java\com\baeldung\axon\querymodel\MongoOrdersEventHandler.java
| 1
|
请完成以下Java代码
|
public class RedisTbCacheTransaction<K extends Serializable, V extends Serializable> implements TbCacheTransaction<K, V> {
private final RedisTbTransactionalCache<K, V> cache;
private final RedisConnection connection;
@Override
public void put(K key, V value) {
cache.put(key, value, connection);
}
@Override
public boolean commit() {
try {
var execResult = connection.exec();
var result = execResult != null && execResult.stream().anyMatch(Objects::nonNull);
|
return result;
} finally {
connection.close();
}
}
@Override
public void rollback() {
try {
connection.discard();
} finally {
connection.close();
}
}
}
|
repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\RedisTbCacheTransaction.java
| 1
|
请完成以下Java代码
|
public class JerseyTimeoutClient {
private static final long TIMEOUT = TimeoutResource.STALL / 2;
private final String endpoint;
public JerseyTimeoutClient(String endpoint) {
this.endpoint = endpoint;
}
private String get(Client client) {
return get(client, null);
}
private String get(Client client, Long requestTimeout) {
Builder request = client.target(endpoint)
.request();
if (requestTimeout != null) {
request.property(ClientProperties.CONNECT_TIMEOUT, requestTimeout);
request.property(ClientProperties.READ_TIMEOUT, requestTimeout);
}
return request.get(String.class);
}
public String viaClientBuilder() {
|
ClientBuilder builder = ClientBuilder.newBuilder()
.connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(TIMEOUT, TimeUnit.MILLISECONDS);
return get(builder.build());
}
public String viaClientConfig() {
ClientConfig config = new ClientConfig();
config.property(ClientProperties.CONNECT_TIMEOUT, TIMEOUT);
config.property(ClientProperties.READ_TIMEOUT, TIMEOUT);
return get(ClientBuilder.newClient(config));
}
public String viaClientProperty() {
Client client = ClientBuilder.newClient();
client.property(ClientProperties.CONNECT_TIMEOUT, TIMEOUT);
client.property(ClientProperties.READ_TIMEOUT, TIMEOUT);
return get(client);
}
public String viaRequestProperty() {
return get(ClientBuilder.newClient(), TIMEOUT);
}
}
|
repos\tutorials-master\web-modules\jersey-2\src\main\java\com\baeldung\jersey\timeout\client\JerseyTimeoutClient.java
| 1
|
请完成以下Java代码
|
public static class Jar implements RepackagingLayout {
@Override
public @Nullable String getLauncherClassName() {
return "org.springframework.boot.loader.launch.JarLauncher";
}
@Override
public String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) {
return "BOOT-INF/lib/";
}
@Override
public String getClassesLocation() {
return "";
}
@Override
public String getRepackagedClassesLocation() {
return "BOOT-INF/classes/";
}
@Override
public String getClasspathIndexFileLocation() {
return "BOOT-INF/classpath.idx";
}
@Override
public String getLayersIndexFileLocation() {
return "BOOT-INF/layers.idx";
}
@Override
public boolean isExecutable() {
return true;
}
}
/**
* Executable expanded archive layout.
*/
public static class Expanded extends Jar {
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.PropertiesLauncher";
}
}
/**
* No layout.
*/
public static class None extends Jar {
@Override
public @Nullable String getLauncherClassName() {
return null;
}
@Override
public boolean isExecutable() {
return false;
}
}
/**
* Executable WAR layout.
*/
public static class War implements Layout {
private static final Map<LibraryScope, String> SCOPE_LOCATION;
|
static {
Map<LibraryScope, String> locations = new HashMap<>();
locations.put(LibraryScope.COMPILE, "WEB-INF/lib/");
locations.put(LibraryScope.CUSTOM, "WEB-INF/lib/");
locations.put(LibraryScope.RUNTIME, "WEB-INF/lib/");
locations.put(LibraryScope.PROVIDED, "WEB-INF/lib-provided/");
SCOPE_LOCATION = Collections.unmodifiableMap(locations);
}
@Override
public String getLauncherClassName() {
return "org.springframework.boot.loader.launch.WarLauncher";
}
@Override
public @Nullable String getLibraryLocation(String libraryName, @Nullable LibraryScope scope) {
return SCOPE_LOCATION.get(scope);
}
@Override
public String getClassesLocation() {
return "WEB-INF/classes/";
}
@Override
public String getClasspathIndexFileLocation() {
return "WEB-INF/classpath.idx";
}
@Override
public String getLayersIndexFileLocation() {
return "WEB-INF/layers.idx";
}
@Override
public boolean isExecutable() {
return true;
}
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\Layouts.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ConnectionCustomizerService implements IConnectionCustomizerService
{
private final List<IConnectionCustomizer> permanentCustomizers = new ArrayList<>();
private final ThreadLocal<List<ITemporaryConnectionCustomizer>> temporaryCustomizers = ThreadLocal.withInitial(() -> new ArrayList<>());
private final ThreadLocal<Set<IConnectionCustomizer>> currentlyInvokedCustomizers = ThreadLocal.withInitial(() -> new IdentityHashSet<>());
@Override
public void registerPermanentCustomizer(@NonNull final IConnectionCustomizer connectionCustomizer)
{
permanentCustomizers.add(connectionCustomizer);
}
@Override
public AutoCloseable registerTemporaryCustomizer(@NonNull final ITemporaryConnectionCustomizer connectionCustomizer)
{
temporaryCustomizers.get().add(connectionCustomizer);
return new AutoCloseable()
{
@Override
public void close() throws Exception
{
removeTemporaryCustomizer(connectionCustomizer);
}
};
}
private void removeTemporaryCustomizer(@NonNull final ITemporaryConnectionCustomizer dlmConnectionCustomizer)
{
final boolean wasInTheList = temporaryCustomizers.get().remove(dlmConnectionCustomizer);
Check.errorIf(!wasInTheList, "ITemporaryConnectionCustomizer={} was not in the thread-local list of temperary customizers; this={}", dlmConnectionCustomizer, this);
}
@Override
public void fireRegisteredCustomizers(@NonNull final Connection c)
{
getRegisteredCustomizers().forEach(
customizer ->
|
{
invokeIfNotYetInvoked(customizer, c);
});
}
@Override
public String toString()
{
return "ConnectionCustomizerService [permanentCustomizers=" + permanentCustomizers + ", (thread-local-)temporaryCustomizers=" + temporaryCustomizers.get() + ", (thread-local-)currentlyInvokedCustomizers=" + currentlyInvokedCustomizers + "]";
}
private List<IConnectionCustomizer> getRegisteredCustomizers()
{
return new ImmutableList.Builder<IConnectionCustomizer>()
.addAll(permanentCustomizers)
.addAll(temporaryCustomizers.get())
.build();
}
/**
* Invoke {@link IConnectionCustomizer#customizeConnection(Connection)} with the given parameters, unless the customizer was already invoked within this thread and that invocation did not yet finish.
* So the goal is to avoid recursive invocations on the same customizer. Also see {@link IConnectionCustomizerService#fireRegisteredCustomizers(Connection)}.
*
* @param customizer
* @param connection
*/
private void invokeIfNotYetInvoked(@NonNull final IConnectionCustomizer customizer, @NonNull final Connection connection)
{
try
{
if (currentlyInvokedCustomizers.get().add(customizer))
{
customizer.customizeConnection(connection);
currentlyInvokedCustomizers.get().remove(customizer);
}
}
finally
{
currentlyInvokedCustomizers.get().remove(customizer);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\ConnectionCustomizerService.java
| 2
|
请完成以下Java代码
|
public static String decimalToTwosComplementBinaryUsingShortCut(BigInteger num, int numBits) {
if (!canRepresentInNBits(num, numBits)) {
throw new IllegalArgumentException(numBits + " bits is not enough to represent the number " + num);
}
var isNegative = num.signum() == -1;
var absNum = num.abs();
// Convert the abs value of the number to its binary representation
String binary = absNum.toString(2);
// Pad the binary representation with zeros to make it numBits long
while (binary.length() < numBits) {
binary = "0" + binary;
}
// If the input number is negative, calculate two's complement
if (isNegative) {
binary = performTwosComplementUsingShortCut(binary);
}
return formatInNibbles(binary);
}
private static String performTwosComplementUsingShortCut(String binary) {
|
int firstOneIndexFromRight = binary.lastIndexOf('1');
if (firstOneIndexFromRight == -1) {
return binary;
}
String rightPart = binary.substring(firstOneIndexFromRight);
String leftPart = binary.substring(0, firstOneIndexFromRight);
String leftWithOnes = leftPart.chars().mapToObj(c -> c == '0' ? '1' : '0')
.map(String::valueOf).collect(Collectors.joining(""));
return leftWithOnes + rightPart;
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-7\src\main\java\com\baeldung\twoscomplement\TwosComplement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AsyncExecutor implements AsyncConfigurer {
public static int corePoolSize;
public static int maxPoolSize;
public static int keepAliveSeconds;
public static int queueCapacity;
@Value("${task.pool.core-pool-size}")
public void setCorePoolSize(int corePoolSize) {
AsyncExecutor.corePoolSize = corePoolSize;
}
@Value("${task.pool.max-pool-size}")
public void setMaxPoolSize(int maxPoolSize) {
AsyncExecutor.maxPoolSize = maxPoolSize;
}
@Value("${task.pool.keep-alive-seconds}")
public void setKeepAliveSeconds(int keepAliveSeconds) {
AsyncExecutor.keepAliveSeconds = keepAliveSeconds;
}
@Value("${task.pool.queue-capacity}")
public void setQueueCapacity(int queueCapacity) {
AsyncExecutor.queueCapacity = queueCapacity;
}
/**
* 自定义线程池,用法 @Async
* @return Executor
*/
@Override
|
public Executor getAsyncExecutor() {
// 自定义工厂
ThreadFactory factory = r -> new Thread(r, "el-async-" + new AtomicInteger(1).getAndIncrement());
// 自定义线程池
return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueCapacity), factory,
new ThreadPoolExecutor.CallerRunsPolicy());
}
/**
* 自定义线程池,用法,注入到类中使用
* private ThreadPoolTaskExecutor taskExecutor;
* @return ThreadPoolTaskExecutor
*/
@Bean("taskAsync")
public ThreadPoolTaskExecutor taskAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(4);
executor.setQueueCapacity(20);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("el-task-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
|
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\AsyncExecutor.java
| 2
|
请完成以下Java代码
|
public String getNbOfLines() {
return nbOfLines;
}
/**
* Sets the value of the nbOfLines property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfLines(String value) {
this.nbOfLines = value;
}
/**
* Gets the value of the lineWidth property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getLineWidth() {
return lineWidth;
}
/**
* Sets the value of the lineWidth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLineWidth(String value) {
this.lineWidth = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\DisplayCapabilities1.java
| 1
|
请完成以下Java代码
|
public void updateCallOrderContractLine(final I_C_OrderLine orderLine)
{
final ConditionsId conditionsId = ConditionsId.ofRepoIdOrNull(orderLine.getC_Flatrate_Conditions_ID());
if (conditionsId != null)
{
final boolean isCallOrderContractLine = contractService.isCallOrderContractLine(orderLine);
if (isCallOrderContractLine)
{
orderLineBL.updatePrices(orderLine);
}
}
else
{
orderLineBL.updatePrices(orderLine);
}
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_C_Flatrate_Term_ID })
|
public void updateOrderLineFromContract(final I_C_OrderLine orderLine)
{
final FlatrateTermId contractId = FlatrateTermId.ofRepoIdOrNull(orderLine.getC_Flatrate_Term_ID());
if (contractId != null)
{
final boolean isCallOrderLine = contractService.isCallOrderContractLine(orderLine);
if (isCallOrderLine)
{
orderLineBL.updatePrices(orderLine);
}
}
else
{
orderLineBL.updatePrices(orderLine);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\interceptor\C_OrderLine.java
| 1
|
请完成以下Java代码
|
public class GetTaskVariableCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
protected String variableName;
protected boolean isLocal;
public GetTaskVariableCmd(String taskId, String variableName, boolean isLocal) {
this.taskId = taskId;
this.variableName = variableName;
this.isLocal = isLocal;
}
@Override
public Object execute(CommandContext commandContext) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("taskId is null");
}
if (variableName == null) {
throw new FlowableIllegalArgumentException("variableName is null");
}
|
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
TaskEntity task = cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("task " + taskId + " doesn't exist", Task.class);
}
Object value;
if (isLocal) {
value = task.getVariableLocal(variableName, false);
} else {
value = task.getVariable(variableName, false);
}
return value;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetTaskVariableCmd.java
| 1
|
请完成以下Java代码
|
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
final I_M_InventoryLine inventoryLine = getM_InventoryLine(ic);
final org.compiere.model.I_M_InOutLine originInOutLine = inventoryLine.getM_InOutLine();
Check.assumeNotNull(originInOutLine, "InventoryLine {0} must have an origin inoutline set", inventoryLine);
final I_M_InOut inOut = originInOutLine.getM_InOut();
final I_C_Order order = inOut.getC_Order();
if (inOut.getC_Order_ID() > 0)
{
ic.setC_Order(order); // also set the order; even if the iol does not directly refer to an order line, it is there because of that order
ic.setDateOrdered(order.getDateOrdered());
}
else if (ic.getC_Order_ID() <= 0)
{
// don't attempt to "clear" the order data if it is already set/known.
ic.setC_Order(null);
ic.setDateOrdered(inOut.getMovementDate());
}
final I_M_Inventory inventory = inventoryLine.getM_Inventory();
final DocStatus inventoryDocStatus = DocStatus.ofCode(inventory.getDocStatus());
if (inventoryDocStatus.isCompletedOrClosed())
{
final BigDecimal qtyMultiplier = ONE.negate();
final BigDecimal qtyDelivered = inventoryLine.getQtyInternalUse().multiply(qtyMultiplier);
ic.setQtyEntered(qtyDelivered);
ic.setQtyOrdered(qtyDelivered);
}
else
{
// Corrected, voided etc document. Set qty to zero.
|
ic.setQtyOrdered(ZERO);
ic.setQtyEntered(ZERO);
}
final IProductBL productBL = Services.get(IProductBL.class);
final UomId stockingUOMId = productBL.getStockUOMId(inventoryLine.getM_Product_ID());
ic.setC_UOM_ID(UomId.toRepoId(stockingUOMId));
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
final BigDecimal qtyDelivered = ic.getQtyOrdered();
ic.setQtyDelivered(qtyDelivered); // when changing this, make sure to threat ProductType.Service specially
final BigDecimal qtyInUOM = Services.get(IUOMConversionBL.class)
.convertFromProductUOM(
ProductId.ofRepoId(ic.getM_Product_ID()),
UomId.ofRepoId(ic.getC_UOM_ID()),
qtyDelivered);
ic.setQtyDeliveredInUOM(qtyInUOM);
ic.setDeliveryDate(ic.getDateOrdered());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\M_InventoryLine_Handler.java
| 1
|
请完成以下Java代码
|
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getFootnotes() {
return footnotes;
}
public void setFootnotes(String footnotes) {
this.footnotes = footnotes;
}
|
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Override
public String toString() {
return "TouristData [region=" + region + ", country=" + country + ", year=" + year + ", series=" + series + ", value=" + value + ", footnotes=" + footnotes + ", source=" + source + "]";
}
}
|
repos\tutorials-master\apache-spark\src\main\java\com\baeldung\differences\dataframe\dataset\rdd\TouristData.java
| 1
|
请完成以下Java代码
|
public int getMKTG_ContactPerson_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class);
}
@Override
public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson)
{
set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson);
}
/** Set MKTG_ContactPerson.
|
@param MKTG_ContactPerson_ID MKTG_ContactPerson */
@Override
public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID)
{
if (MKTG_ContactPerson_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID));
}
/** Get MKTG_ContactPerson.
@return MKTG_ContactPerson */
@Override
public int getMKTG_ContactPerson_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_Attribute.java
| 1
|
请完成以下Java代码
|
public boolean containsKey(@Nullable final Object key)
{
return map.containsKey(key);
}
@Override
public boolean containsValue(final Object value)
{
for (final List<V> values : map.values())
{
if (values == null || values.isEmpty())
{
continue;
}
if (values.contains(value))
{
return true;
}
}
return false;
}
@Override
public List<V> get(final Object key)
{
return map.get(key);
}
@Override
public List<V> put(final K key, final List<V> value)
{
return map.put(key, value);
}
/**
* Add the given single value to the current list of values for the given key.
*
* @param key the key
* @param value the value to be added
*/
public void add(final K key, final V value)
{
List<V> values = map.get(key);
if (values == null)
{
values = newValuesList();
map.put(key, values);
}
values.add(value);
}
protected List<V> newValuesList()
{
return new ArrayList<V>();
}
/**
* Set the given single value under the given key.
*
* @param key the key
* @param value the value to set
*/
public void set(final K key, final V value)
{
List<V> values = map.get(key);
if (values == null)
{
|
values = new ArrayList<V>();
map.put(key, values);
}
else
{
values.clear();
}
values.add(value);
}
@Override
public List<V> remove(final Object key)
{
return map.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends List<V>> m)
{
map.putAll(m);
}
@Override
public void clear()
{
map.clear();
}
@Override
public Set<K> keySet()
{
return map.keySet();
}
@Override
public Collection<List<V>> values()
{
return map.values();
}
@Override
public Set<Map.Entry<K, List<V>>> entrySet()
{
return map.entrySet();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MultiValueMap.java
| 1
|
请完成以下Java代码
|
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
/** Set Rolle.
@param AD_Role_ID
Responsibility Role
*/
@Override
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Rolle.
@return Responsibility Role
*/
@Override
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set AD_Window_Access.
@param AD_Window_Access_ID AD_Window_Access */
@Override
public void setAD_Window_Access_ID (int AD_Window_Access_ID)
{
if (AD_Window_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Window_Access_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Window_Access_ID, Integer.valueOf(AD_Window_Access_ID));
}
/** Get AD_Window_Access.
@return AD_Window_Access */
@Override
public int getAD_Window_Access_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_Access_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Data entry or display window
*/
@Override
|
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Fenster.
@return Data entry or display window
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window_Access.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private LogoutFilter createLogoutFilter(H http) {
this.contextLogoutHandler.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
this.contextLogoutHandler.setSecurityContextRepository(getSecurityContextRepository(http));
this.logoutHandlers.add(this.contextLogoutHandler);
this.logoutHandlers.add(postProcess(new LogoutSuccessEventPublishingLogoutHandler()));
LogoutHandler[] handlers = this.logoutHandlers.toArray(new LogoutHandler[0]);
LogoutFilter result = new LogoutFilter(getLogoutSuccessHandler(), handlers);
result.setSecurityContextHolderStrategy(getSecurityContextHolderStrategy());
result.setLogoutRequestMatcher(getLogoutRequestMatcher(http));
result = postProcess(result);
return result;
}
private SecurityContextRepository getSecurityContextRepository(H http) {
SecurityContextRepository securityContextRepository = http.getSharedObject(SecurityContextRepository.class);
if (securityContextRepository == null) {
securityContextRepository = new HttpSessionSecurityContextRepository();
}
return securityContextRepository;
}
private RequestMatcher getLogoutRequestMatcher(H http) {
if (this.logoutRequestMatcher != null) {
return this.logoutRequestMatcher;
}
this.logoutRequestMatcher = createLogoutRequestMatcher(http);
return this.logoutRequestMatcher;
}
|
@SuppressWarnings("unchecked")
private RequestMatcher createLogoutRequestMatcher(H http) {
RequestMatcher post = createLogoutRequestMatcher("POST");
if (http.getConfigurer(CsrfConfigurer.class) != null) {
return post;
}
RequestMatcher get = createLogoutRequestMatcher("GET");
RequestMatcher put = createLogoutRequestMatcher("PUT");
RequestMatcher delete = createLogoutRequestMatcher("DELETE");
return new OrRequestMatcher(get, post, put, delete);
}
private RequestMatcher createLogoutRequestMatcher(String httpMethod) {
return getRequestMatcherBuilder().matcher(HttpMethod.valueOf(httpMethod), this.logoutUrl);
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\LogoutConfigurer.java
| 2
|
请完成以下Java代码
|
public class GroupEntityManagerImpl
extends AbstractIdmEngineEntityManager<GroupEntity, GroupDataManager>
implements GroupEntityManager {
public GroupEntityManagerImpl(IdmEngineConfiguration idmEngineConfiguration, GroupDataManager groupDataManager) {
super(idmEngineConfiguration, groupDataManager);
}
@Override
public Group createNewGroup(String groupId) {
GroupEntity groupEntity = dataManager.create();
groupEntity.setId(groupId);
groupEntity.setRevision(0); // Needed as groups can be transient and not save when they are returned
return groupEntity;
}
@Override
public void delete(String groupId) {
GroupEntity group = dataManager.findById(groupId);
if (group != null) {
getMembershipEntityManager().deleteMembershipByGroupId(groupId);
if (getEventDispatcher() != null && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(FlowableIdmEventBuilder.createMembershipEvent(FlowableIdmEventType.MEMBERSHIPS_DELETED, groupId, null),
engineConfiguration.getEngineCfgKey());
}
delete(group);
}
}
@Override
public GroupQuery createNewGroupQuery() {
return new GroupQueryImpl(getCommandExecutor());
}
@Override
public List<Group> findGroupByQueryCriteria(GroupQueryImpl query) {
return dataManager.findGroupByQueryCriteria(query);
}
@Override
public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
return dataManager.findGroupCountByQueryCriteria(query);
}
@Override
public List<Group> findGroupsByUser(String userId) {
return dataManager.findGroupsByUser(userId);
}
@Override
|
public List<Group> findGroupsByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findGroupsByNativeQuery(parameterMap);
}
@Override
public long findGroupCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findGroupCountByNativeQuery(parameterMap);
}
@Override
public boolean isNewGroup(Group group) {
return ((GroupEntity) group).getRevision() == 0;
}
@Override
public List<Group> findGroupsByPrivilegeId(String privilegeId) {
return dataManager.findGroupsByPrivilegeId(privilegeId);
}
protected MembershipEntityManager getMembershipEntityManager() {
return engineConfiguration.getMembershipEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\GroupEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public void rejectPicking(@NonNull final Quantity qtyRejected)
{
assertDraft();
assertNotApproved();
qtyPicked = qtyRejected;
pickStatus = PickingCandidatePickStatus.WILL_NOT_BE_PICKED;
}
public void rejectPickingPartially(@NonNull final QtyRejectedWithReason qtyRejected)
{
assertDraft();
// assertNotApproved();
Quantity.assertSameUOM(qtyPicked, qtyRejected.toQuantity());
this.qtyRejected = qtyRejected;
}
public void packTo(@Nullable final PackToSpec packToSpec)
{
assertDraft();
if (!pickStatus.isEligibleForPacking())
{
throw new AdempiereException("Invalid status when changing packing instructions: " + pickStatus);
}
this.packToSpec = packToSpec;
pickStatus = computePickOrPackStatus(this.packToSpec);
}
public void reviewPicking(final BigDecimal qtyReview)
{
assertDraft();
if (!pickStatus.isEligibleForReview())
{
throw new AdempiereException("Picking candidate cannot be approved because it's not picked or packed yet: " + this);
}
this.qtyReview = qtyReview;
approvalStatus = computeApprovalStatus(qtyPicked, this.qtyReview, pickStatus);
}
public void reviewPicking()
{
reviewPicking(qtyPicked.toBigDecimal());
}
private static PickingCandidateApprovalStatus computeApprovalStatus(final Quantity qtyPicked, final BigDecimal qtyReview, final PickingCandidatePickStatus pickStatus)
{
if (qtyReview == null)
{
return PickingCandidateApprovalStatus.TO_BE_APPROVED;
}
//
final BigDecimal qtyReviewToMatch;
if (pickStatus.isPickRejected())
{
qtyReviewToMatch = BigDecimal.ZERO;
}
else
{
qtyReviewToMatch = qtyPicked.toBigDecimal();
}
//
if (qtyReview.compareTo(qtyReviewToMatch) == 0)
{
|
return PickingCandidateApprovalStatus.APPROVED;
}
else
{
return PickingCandidateApprovalStatus.REJECTED;
}
}
private static PickingCandidatePickStatus computePickOrPackStatus(@Nullable final PackToSpec packToSpec)
{
return packToSpec != null ? PickingCandidatePickStatus.PACKED : PickingCandidatePickStatus.PICKED;
}
public boolean isPickFromPickingOrder()
{
return getPickFrom().isPickFromPickingOrder();
}
public void issueToPickingOrder(@Nullable final List<PickingCandidateIssueToBOMLine> issuesToPickingOrder)
{
this.issuesToPickingOrder = issuesToPickingOrder != null
? ImmutableList.copyOf(issuesToPickingOrder)
: ImmutableList.of();
}
public PickingCandidateSnapshot snapshot()
{
return PickingCandidateSnapshot.builder()
.id(getId())
.qtyReview(getQtyReview())
.pickStatus(getPickStatus())
.approvalStatus(getApprovalStatus())
.processingStatus(getProcessingStatus())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\PickingCandidate.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
return Objects.hash(firstName, lastName, position);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Player other = (Player) obj;
if (firstName == null) {
if (other.firstName != null) {
return false;
}
} else if (!firstName.equals(other.firstName)) {
return false;
}
if (lastName == null) {
if (other.lastName != null) {
return false;
}
|
} else if (!lastName.equals(other.lastName)) {
return false;
}
if (position == null) {
if (other.position != null) {
return false;
}
} else if (!position.equals(other.position)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-3\src\main\java\com\baeldung\hash\Player.java
| 1
|
请完成以下Java代码
|
public IQueueProcessor getQueueProcessor(@NonNull final QueueProcessorId queueProcessorId)
{
mainLock.lock();
try
{
return asyncProcessorPlanner
.getQueueProcessor(queueProcessorId)
.orElse(null);
}
finally
{
mainLock.unlock();
}
}
@Override
public void shutdown()
{
mainLock.lock();
try
{
logger.info("Shutdown started");
asyncProcessorPlanner.getRegisteredQueueProcessors()
.stream()
.map(IQueueProcessor::getQueueProcessorId)
.map(QueueProcessorId::getRepoId)
.forEach(this::removeQueueProcessor0);
this.asyncProcessorPlanner.shutdown();
logger.info("Shutdown finished");
}
finally
{
mainLock.unlock();
}
}
private void registerMBean(final IQueueProcessor queueProcessor)
{
unregisterMBean(queueProcessor);
final JMXQueueProcessor processorMBean = new JMXQueueProcessor(queueProcessor, queueProcessor.getQueueProcessorId().getRepoId());
final String jmxName = createJMXName(queueProcessor);
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try
{
final ObjectName name = new ObjectName(jmxName);
mbs.registerMBean(processorMBean, name);
}
catch (final MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | NullPointerException e)
{
e.printStackTrace();
}
}
private void unregisterMBean(@NonNull final IQueueProcessor queueProcessor)
{
final String jmxName = createJMXName(queueProcessor);
|
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try
{
final ObjectName name = new ObjectName(jmxName);
mbs.unregisterMBean(name);
}
catch (final InstanceNotFoundException e)
{
// nothing
// e.printStackTrace();
}
catch (final MalformedObjectNameException | NullPointerException | MBeanRegistrationException e)
{
e.printStackTrace();
}
}
private IQueueProcessor createProcessor(@NonNull final I_C_Queue_Processor processorDef)
{
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForPackageProcessing(processorDef);
return queueProcessorFactory.createAsynchronousQueueProcessor(processorDef, queue);
}
private static String createJMXName(@NonNull final IQueueProcessor queueProcessor)
{
return QueueProcessorsExecutor.class.getName()
+ ":type=" + queueProcessor.getName();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorsExecutor.java
| 1
|
请完成以下Java代码
|
public String getValueName(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public Object getValueInitial(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public BigDecimal getValueInitialAsBigDecimal(final AttributeCode attributeCode)
{
throw new AttributeNotFoundException(attributeCode, this);
}
@Override
public IAttributeValueCallout getAttributeValueCallout(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public void onChildAttributeStorageAdded(final IAttributeStorage childAttributeStorage)
{
throw new HUException("Null storage cannot have children");
}
@Override
public void onChildAttributeStorageRemoved(final IAttributeStorage childAttributeStorageRemoved)
{
throw new HUException("Null storage cannot have children");
}
@Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public boolean isDisplayedUI(final I_M_Attribute attribute, final Set<ProductId> productIds)
{
return false;
}
@Override
public boolean isMandatory(final @NonNull I_M_Attribute attribute, final Set<ProductId> productIds, final boolean isMaterialReceipt)
{
return false;
}
@Override
public void pushUp()
{
// nothing
}
@Override
public void pushUpRollback()
{
// nothing
}
@Override
public void pushDown()
{
// nothing
}
@Override
public void saveChangesIfNeeded()
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public void setSaveOnChange(final boolean saveOnChange)
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public IAttributeStorageFactory getAttributeStorageFactory()
{
throw new UnsupportedOperationException();
}
|
@Nullable
@Override
public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{
return "NullAttributeStorage []";
}
@Override
public BigDecimal getStorageQtyOrZERO()
{
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/
@Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java
| 1
|
请完成以下Java代码
|
public class CircularBuffer<E> {
private static final int DEFAULT_CAPACITY = 8;
private final int capacity;
private final E[] data;
private volatile int writeSequence, readSequence;
@SuppressWarnings("unchecked")
public CircularBuffer(int capacity) {
this.capacity = (capacity < 1) ? DEFAULT_CAPACITY : capacity;
this.data = (E[]) new Object[this.capacity];
this.readSequence = 0;
this.writeSequence = -1;
}
public boolean offer(E element) {
if (isNotFull()) {
int nextWriteSeq = writeSequence + 1;
data[nextWriteSeq % capacity] = element;
writeSequence++;
return true;
}
return false;
}
public E poll() {
if (isNotEmpty()) {
E nextValue = data[readSequence % capacity];
readSequence++;
return nextValue;
}
return null;
}
public int capacity() {
return capacity;
}
public int size() {
return (writeSequence - readSequence) + 1;
|
}
public boolean isEmpty() {
return writeSequence < readSequence;
}
public boolean isFull() {
return size() >= capacity;
}
private boolean isNotEmpty() {
return !isEmpty();
}
private boolean isNotFull() {
return !isFull();
}
}
|
repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\circularbuffer\CircularBuffer.java
| 1
|
请完成以下Java代码
|
public HUConsolidationJob setTarget(@NonNull final HUConsolidationJobId jobId, @Nullable final HUConsolidationTarget target, @NonNull UserId callerId)
{
return SetTargetCommand.builder()
.jobRepository(jobRepository)
//
.callerId(callerId)
.jobId(jobId)
.target(target)
//
.build().execute();
}
public HUConsolidationJob closeTarget(@NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId)
{
return jobRepository.updateById(jobId, job -> {
job.assertUserCanEdit(callerId);
return targetCloser.closeTarget(job);
});
}
public void printTargetLabel(@NonNull final HUConsolidationJobId jobId, @NotNull final UserId callerId)
{
final HUConsolidationJob job = jobRepository.getById(jobId);
final HUConsolidationTarget currentTarget = job.getCurrentTargetNotNull();
labelPrinter.printLabel(currentTarget);
}
public HUConsolidationJob consolidate(@NonNull final ConsolidateRequest request)
{
return ConsolidateCommand.builder()
.jobRepository(jobRepository)
.huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService)
.request(request)
|
.build()
.execute();
}
public JsonHUConsolidationJobPickingSlotContent getPickingSlotContent(final HUConsolidationJobId jobId, final PickingSlotId pickingSlotId)
{
return GetPickingSlotContentCommand.builder()
.jobRepository(jobRepository)
.huQRCodesService(huQRCodesService)
.pickingSlotService(pickingSlotService)
.jobId(jobId)
.pickingSlotId(pickingSlotId)
.build()
.execute();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\HUConsolidationJobService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void addCorsMappings(CorsRegistry registry) {
CorsConfiguration configuration = this.corsProperties.toCorsConfiguration();
if (configuration != null) {
registry.addMapping(this.graphQlProperties.getHttp().getPath()).combine(configuration);
}
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty("spring.graphql.websocket.path")
static class WebSocketConfiguration {
@Bean
@ConditionalOnMissingBean
GraphQlWebSocketHandler graphQlWebSocketHandler(WebGraphQlHandler webGraphQlHandler,
GraphQlProperties properties, ServerCodecConfigurer configurer) {
return new GraphQlWebSocketHandler(webGraphQlHandler, configurer,
properties.getWebsocket().getConnectionInitTimeout(), properties.getWebsocket().getKeepAlive());
}
@Bean
HandlerMapping graphQlWebSocketEndpoint(GraphQlWebSocketHandler graphQlWebSocketHandler,
GraphQlProperties properties) {
String path = properties.getWebsocket().getPath();
Assert.state(path != null, "'path' must not be null");
|
logger.info(LogMessage.format("GraphQL endpoint WebSocket %s", path));
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setHandlerPredicate(new WebSocketUpgradeHandlerPredicate());
mapping.setUrlMap(Collections.singletonMap(path, graphQlWebSocketHandler));
mapping.setOrder(-2); // Ahead of HTTP endpoint ("routerFunctionMapping" bean)
return mapping;
}
}
static class GraphiQlResourceHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphiql/index.html");
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\reactive\GraphQlWebFluxAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public static SecretKey random()
{
final byte[] bytes = new byte[20];
random.nextBytes(bytes);
return new SecretKey(BaseEncoding.base32().encode(bytes));
}
public static SecretKey ofString(@NonNull String string)
{
return new SecretKey(string);
}
public static Optional<SecretKey> optionalOfString(@Nullable String string)
{
return StringUtils.trimBlankToOptional(string).map(SecretKey::new);
}
@Deprecated
|
@Override
public String toString() {return getAsString();}
public String getAsString() {return string;}
public boolean isValid(@NonNull final OTP otp)
{
return TOTPUtils.validate(this, otp);
}
public String toHexString()
{
final byte[] bytes = BaseEncoding.base32().decode(string);
//return java.util.HexFormat.of().formatHex(bytes);
return Hex.encodeHexString(bytes);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\SecretKey.java
| 1
|
请完成以下Java代码
|
private static ImmutableMap<String, Object> toImmutableMap(final Map<String, Object> map)
{
if (map instanceof ImmutableMap)
{
return (ImmutableMap<String, Object>)map;
}
else
{
return map.entrySet()
.stream()
.filter(entry -> entry.getKey() != null && entry.getValue() != null)
.collect(GuavaCollectors.toImmutableMap());
}
}
public SqlDocumentFilterConverterContext withViewId(@Nullable final ViewId viewId)
{
return !ViewId.equals(this.viewId, viewId)
? new SqlDocumentFilterConverterContext(viewId, this.userRolePermissionsKey, this.parameters, this.queryIfNoFilters)
: this;
}
|
public SqlDocumentFilterConverterContext withUserRolePermissionsKey(final UserRolePermissionsKey userRolePermissionsKey)
{
return !Objects.equals(this.userRolePermissionsKey, userRolePermissionsKey)
? new SqlDocumentFilterConverterContext(this.viewId, userRolePermissionsKey, this.parameters, this.queryIfNoFilters)
: this;
}
public int getPropertyAsInt(@NonNull final String name, final int defaultValue)
{
final ImmutableMap<String, Object> params = getParameters();
final Object value = params.get(name);
return NumberUtils.asInt(value, defaultValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlDocumentFilterConverterContext.java
| 1
|
请完成以下Java代码
|
public BPartnerQuery createQueryFailIfNotExists(
@NonNull final BPartnerCompositeLookupKey queryLookupKey,
@Nullable final OrgId orgId)
{
final BPartnerQueryBuilder queryBuilder = BPartnerQuery.builder()
.failIfNotExists(true);
if (orgId != null)
{
queryBuilder.onlyOrgId(orgId);
}
addKeyToQueryBuilder(queryLookupKey, queryBuilder);
return queryBuilder.build();
}
private static BPartnerQuery createBPartnerQuery(
@NonNull final Collection<BPartnerCompositeLookupKey> bpartnerLookupKeys,
@Nullable final OrgId onlyOrgId)
{
final BPartnerQueryBuilder query = BPartnerQuery.builder();
if (onlyOrgId != null)
{
query.onlyOrgId(onlyOrgId)
.onlyOrgId(OrgId.ANY);
}
for (final BPartnerCompositeLookupKey bpartnerLookupKey : bpartnerLookupKeys)
{
addKeyToQueryBuilder(bpartnerLookupKey, query);
}
return query.build();
}
private static void addKeyToQueryBuilder(final BPartnerCompositeLookupKey bpartnerLookupKey, final BPartnerQueryBuilder queryBuilder)
{
final JsonExternalId jsonExternalId = bpartnerLookupKey.getJsonExternalId();
if (jsonExternalId != null)
{
queryBuilder.externalId(JsonConverters.fromJsonOrNull(jsonExternalId));
}
|
final String value = bpartnerLookupKey.getCode();
if (isNotBlank(value))
{
queryBuilder.bpartnerValue(value.trim());
}
final GLN gln = bpartnerLookupKey.getGln();
if (gln != null)
{
queryBuilder.gln(gln);
}
final GlnWithLabel glnWithLabel = bpartnerLookupKey.getGlnWithLabel();
if (glnWithLabel != null)
{
queryBuilder.gln(glnWithLabel.getGln());
queryBuilder.glnLookupLabel(glnWithLabel.getLabel());
}
final MetasfreshId metasfreshId = bpartnerLookupKey.getMetasfreshId();
if (metasfreshId != null)
{
queryBuilder.bPartnerId(BPartnerId.ofRepoId(metasfreshId.getValue()));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerQueryService.java
| 1
|
请完成以下Java代码
|
public static void main(String[] args) {
System.out.println("-------Just-----------");
Observable<String> observable = Observable.just("Hello");
observable.subscribe(
System.out::println, //onNext
Throwable::printStackTrace, //onError
() -> System.out.println("onCompleted") //onCompleted
);
BlockingObservable<String> blockingObservable = observable.toBlocking();
System.out.println();
System.out.println("-------Map-----------");
Observable.from(letters)
.map(String::toUpperCase)
.subscribe(System.out::print);
System.out.println();
System.out.println("-------FlatMap-----------");
Observable.just("book1", "book2")
.flatMap(s -> getTitle())
.subscribe(System.out::print);
System.out.println();
System.out.println("--------Scan----------");
Observable.from(letters)
.scan(new StringBuilder(), StringBuilder::append)
.subscribe(System.out::println);
System.out.println();
System.out.println("------GroubBy------------");
Observable.from(numbers)
.groupBy(i -> 0 == (i % 2) ? "EVEN" : "ODD")
.subscribe((group) -> group.subscribe((number) -> {
|
System.out.println(group.getKey() + " : " + number);
}));
System.out.println();
System.out.println("-------Filter-----------");
Observable.from(numbers)
.filter(i -> (i % 2 == 1))
.subscribe(System.out::println);
System.out.println("------DefaultIfEmpty------------");
Observable.empty()
.defaultIfEmpty("Observable is empty")
.subscribe(System.out::println);
System.out.println("------DefaultIfEmpty-2-----------");
Observable.from(letters)
.defaultIfEmpty("Observable is empty")
.first()
.subscribe(System.out::println);
System.out.println("-------TakeWhile-----------");
Observable.from(numbers)
.takeWhile(i -> i < 5)
.subscribe(System.out::println);
}
}
|
repos\tutorials-master\rxjava-modules\rxjava-core-2\src\main\java\com\baeldung\rxjava\ObservableImpl.java
| 1
|
请完成以下Java代码
|
private static Validation extractValidation(@NonNull final I_AD_BusinessRule_Precondition record)
{
final ValidationType type = ValidationType.ofCode(record.getPreconditionType());
switch (type)
{
case SQL:
//noinspection DataFlowIssue
return Validation.sql(record.getPreconditionSQL());
case ValidationRule:
return Validation.adValRule(AdValRuleId.ofRepoId(record.getPrecondition_Rule_ID()));
default:
throw new AdempiereException("Unknown validation type: " + type);
}
}
private static BusinessRuleTrigger fromRecord(@NonNull final I_AD_BusinessRule_Trigger record)
{
return BusinessRuleTrigger.builder()
.id(BusinessRuleTriggerId.ofRepoId(record.getAD_BusinessRule_Trigger_ID()))
.triggerTableId(AdTableId.ofRepoId(record.getSource_Table_ID()))
.timings(extractTimings(record))
.condition(extractCondition(record))
.targetRecordMappingSQL(record.getTargetRecordMappingSQL())
.build();
}
private static @NonNull ImmutableSet<TriggerTiming> extractTimings(final I_AD_BusinessRule_Trigger record)
{
final ImmutableSet.Builder<TriggerTiming> timings = ImmutableSet.builder();
if (record.isOnNew())
{
timings.add(TriggerTiming.NEW);
}
if (record.isOnUpdate())
{
timings.add(TriggerTiming.UPDATE);
}
if (record.isOnDelete())
{
timings.add(TriggerTiming.DELETE);
|
}
return timings.build();
}
@Nullable
private static Validation extractCondition(final I_AD_BusinessRule_Trigger record)
{
return StringUtils.trimBlankToOptional(record.getConditionSQL())
.map(Validation::sql)
.orElse(null);
}
private static BusinessRuleWarningTarget fromRecord(@NonNull final I_AD_BusinessRule_WarningTarget record)
{
final String lookupSQL = StringUtils.trimBlankToNull(record.getLookupSQL());
if (lookupSQL == null)
{
throw new FillMandatoryException(I_AD_BusinessRule_WarningTarget.COLUMNNAME_LookupSQL);
}
return BusinessRuleWarningTarget.sqlLookup(
AdTableId.ofRepoId(record.getAD_Table_ID()),
lookupSQL
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\BusinessRuleLoader.java
| 1
|
请完成以下Java代码
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<IdentityLinkEntity> getIdentityLinks() {
if (!isIdentityLinksInitialized) {
definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration()
.getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true;
}
return definitionIdentityLinkEntities;
}
public String getLocalizedName() {
return localizedName;
|
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object getValue(ValueFields valueFields) {
Long longValue = valueFields.getLongValue();
if (longValue != null) {
return new DateTime(longValue);
}
return null;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
if (valueFields.getTaskId() != null) {
JodaDeprecationLogger.LOGGER.warn(
"Using Joda-Time DateTime has been deprecated and will be removed in a future version. Task Variable {} in task {} was a Joda-Time DateTime. ",
valueFields.getName(), valueFields.getTaskId());
|
} else if (valueFields.getProcessInstanceId() != null) {
JodaDeprecationLogger.LOGGER.warn(
"Using Joda-Time DateTime has been deprecated and will be removed in a future version. Process Variable {} in process instance {} and execution {} was a Joda-Time DateTime. ",
valueFields.getName(), valueFields.getProcessInstanceId(), valueFields.getExecutionId());
} else {
JodaDeprecationLogger.LOGGER.warn(
"Using Joda-Time DateTime has been deprecated and will be removed in a future version. Variable {} in {} instance {} and sub-scope {} was a Joda-Time DateTime. ",
valueFields.getName(), valueFields.getScopeType(), valueFields.getScopeId(), valueFields.getSubScopeId());
}
valueFields.setLongValue(((DateTime) value).getMillis());
} else {
valueFields.setLongValue(null);
}
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\JodaDateTimeType.java
| 2
|
请完成以下Java代码
|
long getContentLength() {
return this.size;
}
@Override
public void run() {
releaseAll();
}
private void releaseAll() {
synchronized (this) {
if (this.zipContent != null) {
IOException exceptionChain = null;
try {
this.inputStream.close();
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
try {
this.zipContent.close();
|
}
catch (IOException ex) {
exceptionChain = addToExceptionChain(exceptionChain, ex);
}
this.size = -1;
if (exceptionChain != null) {
throw new UncheckedIOException(exceptionChain);
}
}
}
}
private IOException addToExceptionChain(IOException exceptionChain, IOException ex) {
if (exceptionChain != null) {
exceptionChain.addSuppressed(ex);
return exceptionChain;
}
return ex;
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\nested\NestedUrlConnectionResources.java
| 1
|
请完成以下Java代码
|
public String getAccumulationType ()
{
return (String)get_Value(COLUMNNAME_AccumulationType);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** 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());
}
/** Set Benchmark.
@param PA_Benchmark_ID
Performance Benchmark
*/
public void setPA_Benchmark_ID (int PA_Benchmark_ID)
{
if (PA_Benchmark_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Benchmark_ID, Integer.valueOf(PA_Benchmark_ID));
}
/** Get Benchmark.
@return Performance Benchmark
*/
public int getPA_Benchmark_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Benchmark_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Benchmark.java
| 1
|
请完成以下Java代码
|
public void setAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.amt = value;
}
/**
* Gets the value of the cdtDbtInd property.
*
* @return
* possible object is
* {@link CreditDebitCode }
*
*/
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
/**
* Gets the value of the rsn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRsn() {
return rsn;
}
/**
* Sets the value of the rsn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
|
public void setRsn(String value) {
this.rsn = value;
}
/**
* Gets the value of the addtlInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlInf() {
return addtlInf;
}
/**
* Sets the value of the addtlInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlInf(String value) {
this.addtlInf = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\DocumentAdjustment1.java
| 1
|
请完成以下Java代码
|
public void setCustomerLabelName(final String customerLabelName)
{
this.customerLabelName = customerLabelName;
customerLabelNameSet = true;
}
public void setIngredients(final String ingredients)
{
this.ingredients = ingredients;
ingredientsSet = true;
}
public void setCurrentVendor(final Boolean currentVendor)
{
this.currentVendor = currentVendor;
currentVendorSet = true;
}
public void setExcludedFromSales(final Boolean excludedFromSales)
{
this.excludedFromSales = excludedFromSales;
excludedFromSalesSet = true;
}
public void setExclusionFromSalesReason(final String exclusionFromSalesReason)
{
this.exclusionFromSalesReason = exclusionFromSalesReason;
exclusionFromSalesReasonSet = true;
}
public void setDropShip(final Boolean dropShip)
{
this.dropShip = dropShip;
dropShipSet = true;
|
}
public void setUsedForVendor(final Boolean usedForVendor)
{
this.usedForVendor = usedForVendor;
usedForVendorSet = true;
}
public void setExcludedFromPurchase(final Boolean excludedFromPurchase)
{
this.excludedFromPurchase = excludedFromPurchase;
excludedFromPurchaseSet = true;
}
public void setExclusionFromPurchaseReason(final String exclusionFromPurchaseReason)
{
this.exclusionFromPurchaseReason = exclusionFromPurchaseReason;
exclusionFromPurchaseReasonSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestBPartnerProductUpsert.java
| 1
|
请完成以下Java代码
|
public class MessageFlowAssociationImpl extends BaseElementImpl implements MessageFlowAssociation {
protected static AttributeReference<MessageFlow> innerMessageFlowRefAttribute;
protected static AttributeReference<MessageFlow> outerMessageFlowRefAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(MessageFlowAssociation.class, BPMN_ELEMENT_MESSAGE_FLOW_ASSOCIATION)
.namespaceUri(BPMN20_NS)
.extendsType(BaseElement.class)
.instanceProvider(new ModelTypeInstanceProvider<MessageFlowAssociation>() {
public MessageFlowAssociation newInstance(ModelTypeInstanceContext instanceContext) {
return new MessageFlowAssociationImpl(instanceContext);
}
});
innerMessageFlowRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_INNER_MESSAGE_FLOW_REF)
.required()
.qNameAttributeReference(MessageFlow.class)
.build();
outerMessageFlowRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OUTER_MESSAGE_FLOW_REF)
.required()
.qNameAttributeReference(MessageFlow.class)
.build();
typeBuilder.build();
}
public MessageFlowAssociationImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
|
public MessageFlow getInnerMessageFlow() {
return innerMessageFlowRefAttribute.getReferenceTargetElement(this);
}
public void setInnerMessageFlow(MessageFlow innerMessageFlow) {
innerMessageFlowRefAttribute.setReferenceTargetElement(this, innerMessageFlow);
}
public MessageFlow getOuterMessageFlow() {
return outerMessageFlowRefAttribute.getReferenceTargetElement(this);
}
public void setOuterMessageFlow(MessageFlow outerMessageFlow) {
outerMessageFlowRefAttribute.setReferenceTargetElement(this, outerMessageFlow);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\MessageFlowAssociationImpl.java
| 1
|
请完成以下Java代码
|
public class Item {
@Size(min = 37, max = 37)
@JsonDeserialize(using = ZeroWidthStringDeserializer.class)
private String id;
@NotNull
@Size(min = 1, max = 20)
@JsonDeserialize(using = ZeroWidthStringDeserializer.class)
private String name;
@Min(1)
@Max(100)
@NotNull
@JsonDeserialize(using = ZeroWidthIntDeserializer.class)
private int value;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
|
}
@Override
public String toString() {
return "Item [id=" + id + ", name=" + name + ", value=" + value + "]";
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
return Objects.equals(id, other.id);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\cats\model\Item.java
| 1
|
请完成以下Java代码
|
public HistoricActivityStatisticsQuery orderByActivityId() {
return orderBy(HistoricActivityStatisticsQueryProperty.ACTIVITY_ID_);
}
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return
commandContext
.getHistoricStatisticsManager()
.getHistoricStatisticsCountGroupedByActivity(this);
}
public List<HistoricActivityStatistics> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return
commandContext
.getHistoricStatisticsManager()
.getHistoricStatisticsGroupedByActivity(this, page);
}
protected void checkQueryOk() {
super.checkQueryOk();
ensureNotNull("No valid process definition id supplied", "processDefinitionId", processDefinitionId);
}
// getters /////////////////////////////////////////////////
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isIncludeFinished() {
return includeFinished;
}
|
public boolean isIncludeCanceled() {
return includeCanceled;
}
public boolean isIncludeCompleteScope() {
return includeCompleteScope;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public boolean isIncludeIncidents() {
return includeIncidents;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricActivityStatisticsQueryImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName;
}
public String getOperateType() {
return operateType;
}
public void setOperateType(String operateType) {
this.operateType = operateType;
}
public String getIp() {
|
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsOperatorLog.java
| 2
|
请完成以下Java代码
|
protected Map.Entry<String, String> onGenerateEntry(String line)
{
String[] paramArray = line.split(separator, 2);
if (paramArray.length != 2)
{
Predefine.logger.warning("词典有一行读取错误: " + line);
return null;
}
return new AbstractMap.SimpleEntry<String, String>(paramArray[0], paramArray[1]);
}
/**
* 保存词典
* @param path
* @return 是否成功
*/
public boolean save(String path)
{
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
for (Map.Entry<String, String> entry : trie.entrySet())
{
bw.write(entry.getKey());
bw.write(separator);
bw.write(entry.getValue());
bw.newLine();
}
bw.close();
}
catch (Exception e)
{
|
Predefine.logger.warning("保存词典到" + path + "失败");
return true;
}
return false;
}
/**
* 将自己逆转过来返回
* @return
*/
public StringDictionary reverse()
{
StringDictionary dictionary = new StringDictionary(separator);
for (Map.Entry<String, String> entry : entrySet())
{
dictionary.trie.put(entry.getValue(), entry.getKey());
}
return dictionary;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\StringDictionary.java
| 1
|
请完成以下Java代码
|
public String getExitCriterionId() {
return exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public String getExtraValue() {
return extraValue;
}
public String getInvolvedUser() {
return involvedUser;
}
public Collection<String> getInvolvedGroups() {
return involvedGroups;
}
public boolean isOnlyStages() {
return onlyStages;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public boolean isIncludeLocalVariables() {
return includeLocalVariables;
}
|
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds;
}
public void setSafeCaseInstanceIds(List<List<String>> safeProcessInstanceIds) {
this.safeCaseInstanceIds = safeProcessInstanceIds;
}
public Collection<String> getCaseInstanceIds() {
return caseInstanceIds;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricPlanItemInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public void onChangeClassname(final I_AD_JavaClass_Type type)
{
final IJavaClassDAO javaClassDAO = Services.get(IJavaClassDAO.class);
final List<I_AD_JavaClass> classes = javaClassDAO.retrieveAllJavaClasses(type);
for (final I_AD_JavaClass clazz : classes)
{
if(!clazz.isActive())
{
continue;
}
if(clazz.isInterface())
{
continue;
}
Services.get(IJavaClassBL.class).newInstance(clazz);
}
}
@ModelChange(
timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW },
ifColumnsChanged = { I_AD_JavaClass_Type.COLUMNNAME_Classname })
public void checkClassAndUpdateInternalName(final I_AD_JavaClass_Type javaClassType)
{
final boolean throwEx = true; // we don't want an exception.
checkClassAndUpdateInternalName(javaClassType, throwEx);
}
@CalloutMethod(columnNames = I_AD_JavaClass_Type.COLUMNNAME_Classname)
|
public void checkClassAndUpdateInternalName(I_AD_JavaClass_Type javaClassType, ICalloutField field)
{
final boolean throwEx = false; // we don't want an exception.
checkClassAndUpdateInternalName(javaClassType, throwEx);
}
private void checkClassAndUpdateInternalName(I_AD_JavaClass_Type javaClassType, final boolean throwEx)
{
final IJavaClassTypeBL javaClassTypeBL = Services.get(IJavaClassTypeBL.class);
final Class<?> classNameClass = javaClassTypeBL.checkClassName(javaClassType, throwEx);
if (classNameClass == null)
{
javaClassType.setInternalName(null);
return;
}
javaClassType.setInternalName(classNameClass.getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\model\interceptor\AD_JavaClass_Type.java
| 1
|
请完成以下Java代码
|
public class Pipeline<IN, OUT> {
private Collection<Pipe<?, ?>> pipes;
private Pipeline(Pipe<IN, OUT> pipe) {
pipes = Collections.singletonList(pipe);
}
private Pipeline(Collection<Pipe<?, ?>> pipes) {
this.pipes = new ArrayList<>(pipes);
}
public static <IN, OUT> Pipeline<IN, OUT> of(Pipe<IN, OUT> pipe) {
return new Pipeline<>(pipe);
}
|
public <NEW_OUT> Pipeline<IN, NEW_OUT> withNextPipe(Pipe<OUT, NEW_OUT> pipe) {
final ArrayList<Pipe<?, ?>> newPipes = new ArrayList<>(pipes);
newPipes.add(pipe);
return new Pipeline<>(newPipes);
}
public OUT process(IN input) {
Object output = input;
for (final Pipe pipe : pipes) {
output = pipe.process(output);
}
return (OUT) output;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-structural-2\src\main\java\com\baeldung\pipeline\immutable\Pipeline.java
| 1
|
请完成以下Java代码
|
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setOpenAmt (final BigDecimal OpenAmt)
{
set_ValueNoCheck (COLUMNNAME_OpenAmt, OpenAmt);
}
@Override
public BigDecimal getOpenAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPayAmt (final BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
@Override
public BigDecimal getPayAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PayAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* PaymentRule AD_Reference_ID=195
* Reference name: _Payment Rule
*/
public static final int PAYMENTRULE_AD_Reference_ID=195;
/** Cash = B */
public static final String PAYMENTRULE_Cash = "B";
/** CreditCard = K */
public static final String PAYMENTRULE_CreditCard = "K";
/** DirectDeposit = T */
public static final String PAYMENTRULE_DirectDeposit = "T";
/** Check = S */
public static final String PAYMENTRULE_Check = "S";
/** OnCredit = P */
public static final String PAYMENTRULE_OnCredit = "P";
/** DirectDebit = D */
public static final String PAYMENTRULE_DirectDebit = "D";
/** Mixed = M */
public static final String PAYMENTRULE_Mixed = "M";
/** PayPal = L */
|
public static final String PAYMENTRULE_PayPal = "L";
/** PayPal Extern = V */
public static final String PAYMENTRULE_PayPalExtern = "V";
/** Kreditkarte Extern = U */
public static final String PAYMENTRULE_KreditkarteExtern = "U";
/** Sofortüberweisung = R */
public static final String PAYMENTRULE_Sofortueberweisung = "R";
/** Rückerstattung = E */
public static final String PAYMENTRULE_Rueckerstattung = "E";
/** Verrechnung = F */
public static final String PAYMENTRULE_Verrechnung = "F";
@Override
public void setPaymentRule (final java.lang.String PaymentRule)
{
set_Value (COLUMNNAME_PaymentRule, PaymentRule);
}
@Override
public java.lang.String getPaymentRule()
{
return get_ValueAsString(COLUMNNAME_PaymentRule);
}
@Override
public void setReference (final @Nullable java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
@Override
public java.lang.String getReference()
{
return get_ValueAsString(COLUMNNAME_Reference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelectionLine.java
| 1
|
请完成以下Java代码
|
public class DatagramServer {
public static DatagramChannel startServer() throws IOException {
InetSocketAddress address = new InetSocketAddress("localhost", 7001);
DatagramChannel server = DatagramChannelBuilder.bindChannel(address);
System.out.println("Server started at #" + address);
return server;
}
public static String receiveMessage(DatagramChannel server) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketAddress remoteAdd = server.receive(buffer);
String message = extractMessage(buffer);
System.out.println("Client at #" + remoteAdd + " sent: " + message);
return message;
}
|
private static String extractMessage(ByteBuffer buffer) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String msg = new String(bytes);
return msg;
}
public static void main(String[] args) throws IOException {
DatagramChannel server = startServer();
receiveMessage(server);
}
}
|
repos\tutorials-master\core-java-modules\core-java-nio-2\src\main\java\com\baeldung\datagramchannel\DatagramServer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public Integer getRiskDay() {
return riskDay;
}
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
public String getAuditStatusDesc() {
return PublicEnum.getEnum(this.getAuditStatus()).getDesc();
}
public String getFundIntoTypeDesc() {
|
return FundInfoTypeEnum.getEnum(this.getFundIntoType()).getDesc();
}
public String getSecurityRating() {
return securityRating;
}
public void setSecurityRating(String securityRating) {
this.securityRating = securityRating;
}
public String getMerchantServerIp() {
return merchantServerIp;
}
public void setMerchantServerIp(String merchantServerIp) {
this.merchantServerIp = merchantServerIp;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayConfig.java
| 2
|
请完成以下Java代码
|
final class FixedPositionImpDataLineParser implements ImpDataLineParser
{
private final ImmutableList<ImpFormatColumn> columns;
public FixedPositionImpDataLineParser(@NonNull final ImpFormat importFormat)
{
this.columns = importFormat.getColumns();
}
@Override
public List<ImpDataCell> parseDataCells(final String line)
{
final int columnsCount = columns.size();
final List<ImpDataCell> cells = new ArrayList<>(columnsCount);
for (final ImpFormatColumn impFormatColumn : columns)
{
final ImpDataCell cell = parseDataCell(line, impFormatColumn);
cells.add(cell);
} // for all columns
return ImmutableList.copyOf(cells);
} // parseLine
private ImpDataCell parseDataCell(final String line, final ImpFormatColumn column)
{
try
{
final String rawValue = extractCellRawValue(line, column);
final Object value = column.parseCellValue(rawValue);
return ImpDataCell.value(value);
}
|
catch (final Exception ex)
{
return ImpDataCell.error(ErrorMessage.of(ex));
}
}
private static String extractCellRawValue(final String line, final ImpFormatColumn impFormatColumn)
{
if (impFormatColumn.isConstant())
{
return impFormatColumn.getConstantValue();
}
else
{
// check length
if (impFormatColumn.getStartNo() > 0 && impFormatColumn.getEndNo() <= line.length())
{
return line.substring(impFormatColumn.getStartNo() - 1, impFormatColumn.getEndNo());
}
else
{
return null;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FixedPositionImpDataLineParser.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_PackageTree[")
.append(get_ID()).append("]");
return sb.toString();
}
public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException
{
return (org.compiere.model.I_C_BPartner_Location)MTable.get(getCtx(), org.compiere.model.I_C_BPartner_Location.Table_Name)
.getPO(getC_BPartner_Location_ID(), get_TrxName()); }
/** Set Standort.
@param C_BPartner_Location_ID
Identifiziert die (Liefer-) Adresse des Geschäftspartners
*/
public void setC_BPartner_Location_ID (int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Location_ID, Integer.valueOf(C_BPartner_Location_ID));
}
/** Get Standort.
@return Identifiziert die (Liefer-) Adresse des Geschäftspartners
*/
public int getC_BPartner_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Geschlossen.
@param IsClosed
The status is closed
*/
public void setIsClosed (boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, Boolean.valueOf(IsClosed));
}
/** Get Geschlossen.
@return The status is closed
*/
public boolean isClosed ()
{
Object oo = get_Value(COLUMNNAME_IsClosed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public org.compiere.model.I_M_Package getM_Package() throws RuntimeException
{
return (org.compiere.model.I_M_Package)MTable.get(getCtx(), org.compiere.model.I_M_Package.Table_Name)
.getPO(getM_Package_ID(), get_TrxName()); }
|
/** Set PackstĂĽck.
@param M_Package_ID
Shipment Package
*/
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get PackstĂĽck.
@return Shipment Package
*/
public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Virtual Package.
@param M_PackageTree_ID Virtual Package */
public void setM_PackageTree_ID (int M_PackageTree_ID)
{
if (M_PackageTree_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, Integer.valueOf(M_PackageTree_ID));
}
/** Get Virtual Package.
@return Virtual Package */
public int getM_PackageTree_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackageTree_ID);
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\org\compiere\model\X_M_PackageTree.java
| 1
|
请完成以下Java代码
|
private Stream<I_C_Doc_Outbound_Log_Line> getPDFArchiveDocOutboundLines(@NonNull final ImmutableList<IDocOutboundDAO.LogWithLines> logsWithLines, final boolean onlyNotSendMails)
{
return logsWithLines.stream()
.map(logWithLines -> logWithLines.findCurrentPDFArchiveLogLine()
.filter(currentLine -> isEmailSendable(logWithLines, currentLine, onlyNotSendMails))
.orElse(null))
.filter(Objects::nonNull);
}
private boolean isEmailSendable(@NonNull final IDocOutboundDAO.LogWithLines logWithLines, @NonNull final I_C_Doc_Outbound_Log_Line currentLogLine, final boolean onlyNotSendMails)
{
if (ArchiveId.ofRepoIdOrNull(currentLogLine.getAD_Archive_ID()) == null)
{
final I_C_Doc_Outbound_Log log = logWithLines.getLog();
Loggables.addLog(msgBL.getMsg( MSG_EMPTY_AD_Archive_ID, ImmutableList.of(StringUtils.nullToEmpty(log.getDocumentNo()))));
return false;
}
return !onlyNotSendMails || !logWithLines.wasEmailSentAtLeastOnce();
}
private int sendMails(@NonNull final Stream<I_C_Doc_Outbound_Log_Line> lines,
@Nullable final PInstanceId pInstanceId)
{
final AtomicInteger counter = new AtomicInteger();
final IWorkPackageQueue queue = workPackageQueueFactory.getQueueForEnqueuing(MailWorkpackageProcessor.class);
|
lines.forEach(docOutboundLogLine -> {
final IWorkPackageBuilder builder = queue.newWorkPackage()
.addElement(docOutboundLogLine)
.bindToThreadInheritedTrx();
if (pInstanceId != null)
{
builder.setAD_PInstance_ID(pInstanceId);
}
builder.buildAndEnqueue();
counter.getAndIncrement();
});
return counter.get();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\DocOutboundService.java
| 1
|
请完成以下Java代码
|
public void setAuthor(Author author) {
this.author = author;
}
public short getVersion() {
return version;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
|
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchUpdateOrder\src\main\java\com\bookstore\entity\Book.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getVirtualHost() {
return this.properties.determineVirtualHost();
}
@Override
public List<Address> getAddresses() {
List<Address> addresses = new ArrayList<>();
for (String address : this.properties.determineAddresses()) {
int portSeparatorIndex = address.lastIndexOf(':');
String host = address.substring(0, portSeparatorIndex);
String port = address.substring(portSeparatorIndex + 1);
addresses.add(new Address(host, Integer.parseInt(port)));
}
return addresses;
}
|
@Override
public @Nullable SslBundle getSslBundle() {
Ssl ssl = this.properties.getSsl();
if (!ssl.determineEnabled()) {
return null;
}
if (StringUtils.hasLength(ssl.getBundle())) {
Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context");
return this.sslBundles.getBundle(ssl.getBundle());
}
return null;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\PropertiesRabbitConnectionDetails.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private DocOutboundConfigMap retrieveDocOutboundConfigMap()
{
final ImmutableList<DocOutboundConfig> docOutboundConfig = queryBL.createQueryBuilder(I_C_Doc_Outbound_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(DocOutboundConfigRepository::ofRecord)
.collect(ImmutableList.toImmutableList());
return new DocOutboundConfigMap(docOutboundConfig);
}
private static DocOutboundConfig ofRecord(@NotNull final I_C_Doc_Outbound_Config record)
{
return DocOutboundConfig.builder()
.id(DocOutboundConfigId.ofRepoId(record.getC_Doc_Outbound_Config_ID()))
.tableId(AdTableId.ofRepoId(record.getAD_Table_ID()))
.docBaseType(DocBaseType.ofNullableCode(record.getDocBaseType()))
|
.printFormatId(PrintFormatId.ofRepoIdOrNull(record.getAD_PrintFormat_ID()))
.ccPath(record.getCCPath())
.isDirectProcessQueueItem(record.isDirectProcessQueueItem())
.isDirectEnqueue(record.isDirectEnqueue())
.isAutoSendDocument(record.isAutoSendDocument())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.build();
}
@NonNull
public ImmutableSet<AdTableId> getDistinctConfigTableIds()
{
return getDocOutboundConfigMap().getTableIds();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\config\DocOutboundConfigRepository.java
| 2
|
请完成以下Java代码
|
public static CostCalculationMethod ofCode(@NonNull final String code) {return index.ofCode(code);}
public interface ParamsMapper<T>
{
T fixedAmount(FixedAmountCostCalculationMethodParams params);
T percentageOfAmount(PercentageCostCalculationMethodParams params);
}
public <T> T mapOnParams(@Nullable final CostCalculationMethodParams params, @NonNull final ParamsMapper<T> mapper)
{
if (this == CostCalculationMethod.FixedAmount)
{
return mapper.fixedAmount(castParams(params, FixedAmountCostCalculationMethodParams.class));
}
else if (this == CostCalculationMethod.PercentageOfAmount)
{
return mapper.percentageOfAmount(castParams(params, PercentageCostCalculationMethodParams.class));
}
else
{
throw new AdempiereException("Calculation method not handled: " + this);
}
}
public <T extends CostCalculationMethodParams> T castParams(@Nullable final CostCalculationMethodParams params, @NonNull final Class<T> type)
{
if (params == null)
{
throw new AdempiereException("No calculation method parameters provided for " + type.getSimpleName());
}
return type.cast(params);
}
public interface CaseMapper<T>
|
{
T fixedAmount();
T percentageOfAmount();
}
public <T> T map(@NonNull final CaseMapper<T> mapper)
{
if (this == CostCalculationMethod.FixedAmount)
{
return mapper.fixedAmount();
}
else if (this == CostCalculationMethod.PercentageOfAmount)
{
return mapper.percentageOfAmount();
}
else
{
throw new AdempiereException("Calculation method not handled: " + this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\calculation_methods\CostCalculationMethod.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractCaseInstanceMigrationJobHandler implements JobHandler {
public static final String BATCH_RESULT_STATUS_LABEL = "resultStatus";
public static final String BATCH_RESULT_MESSAGE_LABEL = "resultMessage";
public static final String BATCH_RESULT_STACKTRACE_LABEL = "resultStacktrace";
protected static final String CFG_LABEL_BATCH_ID = "batchId";
protected static final String CFG_LABEL_BATCH_PART_ID = "batchPartId";
protected static String getBatchIdFromHandlerCfg(String handlerCfg) {
try {
JsonNode cfgAsJson = getObjectMapper().readTree(handlerCfg);
if (cfgAsJson.has(CFG_LABEL_BATCH_ID)) {
return cfgAsJson.get(CFG_LABEL_BATCH_ID).asString();
}
return null;
} catch (JacksonException e) {
return null;
}
}
protected static String getBatchPartIdFromHandlerCfg(String handlerCfg) {
try {
JsonNode cfgAsJson = getObjectMapper().readTree(handlerCfg);
if (cfgAsJson.has(CFG_LABEL_BATCH_PART_ID)) {
return cfgAsJson.get(CFG_LABEL_BATCH_PART_ID).asString();
}
return null;
} catch (JacksonException e) {
return null;
}
}
|
public static String getHandlerCfgForBatchId(String batchId) {
ObjectNode handlerCfg = getObjectMapper().createObjectNode();
handlerCfg.put(CFG_LABEL_BATCH_ID, batchId);
return handlerCfg.toString();
}
public static String getHandlerCfgForBatchPartId(String batchPartId) {
ObjectNode handlerCfg = getObjectMapper().createObjectNode();
handlerCfg.put(CFG_LABEL_BATCH_PART_ID, batchPartId);
return handlerCfg.toString();
}
protected static ObjectMapper getObjectMapper() {
if (CommandContextUtil.getCommandContext() != null) {
return CommandContextUtil.getCmmnEngineConfiguration().getObjectMapper();
} else {
return JsonMapper.shared();
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\job\AbstractCaseInstanceMigrationJobHandler.java
| 1
|
请完成以下Java代码
|
public GridField getField()
{
return m_field;
} // getField
@Override
public void keyPressed(final KeyEvent e)
{
}
@Override
public void keyTyped(final KeyEvent e)
{
}
/**
* Key Released. if Escape Restore old Text
*
* @param e event
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@Override
public void keyReleased(final KeyEvent e)
{
if (LogManager.isLevelFinest())
{
log.trace("Key=" + e.getKeyCode() + " - " + e.getKeyChar() + " -> " + m_text.getText());
}
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
m_text.setText(m_initialText);
}
else if (e.getKeyChar() == KeyEvent.CHAR_UNDEFINED)
{
return;
}
m_setting = true;
try
{
String clear = m_text.getText();
if (clear.length() > m_fieldLength)
{
clear = clear.substring(0, m_fieldLength);
|
}
fireVetoableChange(m_columnName, m_oldText, clear);
}
catch (final PropertyVetoException pve)
{
}
m_setting = false;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VFile
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VFile.java
| 1
|
请完成以下Java代码
|
public void setPP_Order_Cost_TrxType (final java.lang.String PP_Order_Cost_TrxType)
{
set_Value (COLUMNNAME_PP_Order_Cost_TrxType, PP_Order_Cost_TrxType);
}
@Override
public java.lang.String getPP_Order_Cost_TrxType()
{
return get_ValueAsString(COLUMNNAME_PP_Order_Cost_TrxType);
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order)
|
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Cost.java
| 1
|
请完成以下Java代码
|
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.cors()
.and()
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS)
.permitAll()
.antMatchers("/graphiql")
.permitAll()
.antMatchers("/graphql")
.permitAll()
.antMatchers(HttpMethod.GET, "/articles/feed")
.authenticated()
.antMatchers(HttpMethod.POST, "/users", "/users/login")
.permitAll()
.antMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags")
.permitAll()
.anyRequest()
.authenticated();
http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
|
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(asList("*"));
configuration.setAllowedMethods(asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the
// wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(false);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\security\WebSecurityConfig.java
| 1
|
请完成以下Java代码
|
public int getAD_Sequence_ProjectValue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Sequence_ProjectValue_ID);
}
@Override
public void setC_ProjectType_ID (final int C_ProjectType_ID)
{
if (C_ProjectType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ProjectType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ProjectType_ID, C_ProjectType_ID);
}
@Override
public int getC_ProjectType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ProjectType_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@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);
}
/**
* ProjectCategory AD_Reference_ID=288
* Reference name: C_ProjectType Category
*/
public static final int PROJECTCATEGORY_AD_Reference_ID=288;
/** General = N */
public static final String PROJECTCATEGORY_General = "N";
/** AssetProject = A */
public static final String PROJECTCATEGORY_AssetProject = "A";
/** WorkOrderJob = W */
public static final String PROJECTCATEGORY_WorkOrderJob = "W";
/** ServiceChargeProject = S */
public static final String PROJECTCATEGORY_ServiceChargeProject = "S";
/** ServiceOrRepair = R */
public static final String PROJECTCATEGORY_ServiceOrRepair = "R";
/** SalesPurchaseOrder = O */
public static final String PROJECTCATEGORY_SalesPurchaseOrder = "O";
@Override
public void setProjectCategory (final java.lang.String ProjectCategory)
{
set_ValueNoCheck (COLUMNNAME_ProjectCategory, ProjectCategory);
}
@Override
public java.lang.String getProjectCategory()
{
return get_ValueAsString(COLUMNNAME_ProjectCategory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectType.java
| 1
|
请完成以下Java代码
|
public String columnName()
{
return this._columnName;
}
public String getAD_Message()
{
return this._adMessage;
}
/** @return column names, in the same order as the enum constants are defined in this class */
public static Set<String> columnNames()
{
return getColumnName2typesMap().keySet();
}
public static final InvoiceWriteOffAmountType valueOfColumnNameOrNull(final String columnName)
{
final InvoiceWriteOffAmountType type = getColumnName2typesMap().get(columnName);
return type;
}
public static final InvoiceWriteOffAmountType valueOfColumnName(final String columnName)
{
final InvoiceWriteOffAmountType type = getColumnName2typesMap().get(columnName);
if (type == null)
{
throw new IllegalArgumentException("No type for " + columnName);
}
return type;
}
|
private static Map<String, InvoiceWriteOffAmountType> _columnName2types;
private static final Map<String, InvoiceWriteOffAmountType> getColumnName2typesMap()
{
if (_columnName2types == null)
{
// NOTE: we preserve the same order as the values() are.
final ImmutableMap.Builder<String, InvoiceWriteOffAmountType> columnName2types = ImmutableMap.builder();
for (final InvoiceWriteOffAmountType type : values())
{
final String columnName = type.columnName();
columnName2types.put(columnName, type);
}
_columnName2types = columnName2types.build();
}
return _columnName2types;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceWriteOffAmountType.java
| 1
|
请完成以下Java代码
|
public JsonGetNextEligiblePickFromLineResponse getNextEligiblePickFromLine(@RequestBody @NonNull final JsonGetNextEligiblePickFromLineRequest request)
{
assertApplicationAccess();
return distributionMobileApplication.getNextEligiblePickFromLine(request, getLoggedUserId());
}
@PostMapping("/event")
public JsonWFProcess postEvent(@RequestBody @NonNull final JsonDistributionEvent event)
{
assertApplicationAccess();
final WFProcess wfProcess = distributionMobileApplication.processEvent(event, getLoggedUserId());
return workflowRestController.toJson(wfProcess);
}
@PostMapping("/dropAll")
public void dropAllTo(@RequestBody @NonNull final JsonDropAllRequest request)
{
assertApplicationAccess();
distributionMobileApplication.dropAll(request, getLoggedUserId());
|
}
@PostMapping("/job/{wfProcessId}/complete")
public WFProcess complete(@PathVariable("wfProcessId") final String wfProcessIdStr)
{
assertApplicationAccess();
return distributionMobileApplication.complete(WFProcessId.ofString(wfProcessIdStr), getLoggedUserId());
}
@PostMapping("/print/materialInTransitReport")
public void printMaterialInTransitReport()
{
assertApplicationAccess();
distributionMobileApplication.printMaterialInTransitReport(getLoggedUserId(), getADLanguageOrBaseLanguage());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\rest_api\DistributionRestController.java
| 1
|
请完成以下Java代码
|
public Book getBookWithTitle(String title) {
return BOOKS_DATA.stream()
.filter(book -> book.getTitle().equals(title))
.findFirst()
.orElse(null);
}
@Override
public List<Book> getAllBooks() {
return new ArrayList<>(BOOKS_DATA);
}
@Override
public Book addBook(Book book) {
BOOKS_DATA.add(book);
return book;
}
@Override
public Book updateBook(Book book) {
BOOKS_DATA.removeIf(b -> Objects.equals(b.getId(), book.getId()));
|
BOOKS_DATA.add(book);
return book;
}
@Override
public boolean deleteBook(Book book) {
return BOOKS_DATA.remove(book);
}
private static Set<Book> initializeData() {
Book book = new Book(1, "J.R.R. Tolkien", "The Lord of the Rings");
Set<Book> books = new HashSet<>();
books.add(book);
return books;
}
}
|
repos\tutorials-master\graphql-modules\graphql-spqr\src\main\java\com\baeldung\spqr\BookService.java
| 1
|
请完成以下Java代码
|
public class PickingSlotViewFilters
{
private static final String PickingSlotBarcodeFilter_FilterId = "PickingSlotBarcodeFilter";
private static final String PARAM_Barcode = "Barcode";
private static final AdMessageKey MSG_BarcodeFilter = AdMessageKey.of("webui.view.pickingSlot.filters.pickingSlotBarcodeFilter");
public static DocumentFilterDescriptorsProvider createFilterDescriptorsProvider()
{
return ImmutableDocumentFilterDescriptorsProvider.of(createPickingSlotBarcodeFilters());
}
public static DocumentFilterDescriptor createPickingSlotBarcodeFilters()
{
return DocumentFilterDescriptor.builder()
.setFilterId(PickingSlotBarcodeFilter_FilterId)
.setFrequentUsed(true)
.setParametersLayoutType(PanelLayoutType.SingleOverlayField)
.addParameter(DocumentFilterParamDescriptor.builder()
.fieldName(PARAM_Barcode)
.displayName(TranslatableStrings.adMessage(MSG_BarcodeFilter))
.mandatory(true)
.widgetType(DocumentFieldWidgetType.Text)
.barcodeScannerType(BarcodeScannerType.QRCode))
.build();
}
@Nullable
public static PickingSlotQRCode getPickingSlotQRCode(final DocumentFilterList filters)
{
final String barcodeString = StringUtils.trimBlankToNull(filters.getParamValueAsString(PickingSlotBarcodeFilter_FilterId, PARAM_Barcode));
if (barcodeString == null)
{
return null;
}
|
//
// Try parsing the Global QR Code, if possible
final GlobalQRCode globalQRCode = GlobalQRCode.parse(barcodeString).orNullIfError();
//
// Case: valid Global QR Code
if (globalQRCode != null)
{
return PickingSlotQRCode.ofGlobalQRCode(globalQRCode);
}
//
// Case: Legacy barcode support
else
{
final IPickingSlotDAO pickingSlotDAO = Services.get(IPickingSlotDAO.class);
return pickingSlotDAO.getPickingSlotIdAndCaptionByCode(barcodeString)
.map(PickingSlotQRCode::ofPickingSlotIdAndCaption)
.orElseThrow(() -> new AdempiereException("Invalid barcode: " + barcodeString));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotViewFilters.java
| 1
|
请完成以下Java代码
|
public class ScriptTaskActivityBehavior extends TaskActivityBehavior {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = LoggerFactory.getLogger(ScriptTaskActivityBehavior.class);
protected String scriptTaskId;
protected String script;
protected String language;
protected String resultVariable;
protected boolean storeScriptVariables = false; // see https://activiti.atlassian.net/browse/ACT-1626
public ScriptTaskActivityBehavior(String script, String language, String resultVariable) {
this.script = script;
this.language = language;
this.resultVariable = resultVariable;
}
public ScriptTaskActivityBehavior(
String scriptTaskId,
String script,
String language,
String resultVariable,
boolean storeScriptVariables
) {
this(script, language, resultVariable);
this.scriptTaskId = scriptTaskId;
this.storeScriptVariables = storeScriptVariables;
}
public void execute(DelegateExecution execution) {
ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
if (Context.getProcessEngineConfiguration().isEnableProcessDefinitionInfoCache()) {
ObjectNode taskElementProperties = Context.getBpmnOverrideElementProperties(
scriptTaskId,
execution.getProcessDefinitionId()
);
if (taskElementProperties != null && taskElementProperties.has(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT)) {
String overrideScript = taskElementProperties.get(DynamicBpmnConstants.SCRIPT_TASK_SCRIPT).asText();
if (StringUtils.isNotEmpty(overrideScript) && !overrideScript.equals(script)) {
script = overrideScript;
|
}
}
}
boolean noErrors = true;
try {
Object result = scriptingEngines.evaluate(script, language, execution, storeScriptVariables);
if (resultVariable != null) {
execution.setVariable(resultVariable, result);
}
} catch (ActivitiException e) {
LOGGER.warn(
"Exception while executing " + execution.getCurrentFlowElement().getId() + " : " + e.getMessage()
);
noErrors = false;
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (rootCause instanceof BpmnError) {
ErrorPropagation.propagateError((BpmnError) rootCause, execution);
} else {
throw e;
}
}
if (noErrors) {
leave(execution);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\ScriptTaskActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Attachment attachment = (Attachment) o;
return Objects.equals(this._id, attachment._id) &&
Objects.equals(this.filename, attachment.filename) &&
Objects.equals(this.contentType, attachment.contentType) &&
Objects.equals(this.uploadDate, attachment.uploadDate) &&
Objects.equals(this.metadata, attachment.metadata);
}
@Override
public int hashCode() {
return Objects.hash(_id, filename, contentType, uploadDate, metadata);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Attachment {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" filename: ").append(toIndentedString(filename)).append("\n");
sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n");
sb.append(" uploadDate: ").append(toIndentedString(uploadDate)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n");
|
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Attachment.java
| 2
|
请完成以下Java代码
|
static void readMultipleCharacters() {
System.out.println("Enter characters (Press 'Enter' to quit):");
try {
int input;
while ((input = System.in.read()) != '\n') {
System.out.print((char) input);
}
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
}
}
static void readWithParameters() {
try {
byte[] byteArray = new byte[5];
|
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = System.in.read(byteArray, 0, byteArray.length)) != -1) {
System.out.print("Data read: " + new String(byteArray, 0, bytesRead));
totalBytesRead += bytesRead;
}
System.out.println("\nBytes Read: " + totalBytesRead);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\systemin\SystemInRead.java
| 1
|
请完成以下Java代码
|
public void setMovementDate (java.sql.Timestamp MovementDate)
{
throw new IllegalArgumentException ("MovementDate is virtual column"); }
/** Get Bewegungsdatum.
@return Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde
*/
@Override
public java.sql.Timestamp getMovementDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_MovementDate);
}
/** Set Ausgelagerte Menge.
@param QtyIssued Ausgelagerte Menge */
@Override
public void setQtyIssued (java.math.BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
}
/** Get Ausgelagerte Menge.
@return Ausgelagerte Menge */
@Override
public java.math.BigDecimal getQtyIssued ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Empfangene Menge.
@param QtyReceived Empfangene Menge */
@Override
public void setQtyReceived (java.math.BigDecimal QtyReceived)
{
throw new IllegalArgumentException ("QtyReceived is virtual column"); }
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
|
return BigDecimal.ZERO;
return bd;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\model\X_M_Material_Tracking_Ref.java
| 1
|
请完成以下Java代码
|
public blink addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public blink addElement(String element)
{
addElementToRegistry(element);
|
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public blink removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\blink.java
| 1
|
请完成以下Java代码
|
public String getDocumentNo ()
{
return (String)get_Value(COLUMNNAME_DocumentNo);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getDocumentNo());
}
/** Set Sales Transaction.
@param IsSOTrx
This is a Sales Transaction
*/
public void setIsSOTrx (boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx));
}
/** Get Sales Transaction.
@return This is a Sales Transaction
*/
public boolean isSOTrx ()
{
Object oo = get_Value(COLUMNNAME_IsSOTrx);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
|
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoiceBatch.java
| 1
|
请完成以下Java代码
|
public final boolean isSaveOnChange()
{
return saveOnChange;
}
/**
*
* @return HU's attribute; never return null
*/
public I_M_HU_Attribute getM_HU_Attribute()
{
return huAttribute;
}
@Override
protected void setInternalValueString(final String value)
{
huAttribute.setValue(value);
valueString = value;
}
@Override
protected void setInternalValueNumber(final BigDecimal value)
{
huAttribute.setValueNumber(value);
valueNumber = value;
}
@Override
protected String getInternalValueString()
{
return valueString;
}
@Override
protected BigDecimal getInternalValueNumber()
{
return valueNumber;
}
@Override
protected String getInternalValueStringInitial()
{
return huAttribute.getValueInitial();
}
@Override
protected BigDecimal getInternalValueNumberInitial()
{
return huAttribute.getValueNumberInitial();
}
@Override
protected void setInternalValueStringInitial(final String value)
{
huAttribute.setValueInitial(value);
}
@Override
protected void setInternalValueNumberInitial(final BigDecimal value)
{
huAttribute.setValueNumberInitial(value);
}
@Override
protected final void onValueChanged(final Object valueOld, final Object valueNew)
{
saveIfNeeded();
}
/**
* Save to database if {@link #isSaveOnChange()}.
*/
private final void saveIfNeeded()
{
if (!saveOnChange)
{
return;
}
save();
}
/**
* Save to database. This method is saving no matter what {@link #isSaveOnChange()} says.
*/
final void save()
|
{
// Make sure the storage was not disposed
assertNotDisposed();
// Make sure HU Attribute contains the right/fresh data
huAttribute.setValue(valueString);
huAttribute.setValueNumber(valueNumber);
huAttribute.setValueDate(TimeUtil.asTimestamp(valueDate));
getHUAttributesDAO().save(huAttribute);
}
@Override
public boolean isNew()
{
return huAttribute.getM_HU_Attribute_ID() <= 0;
}
@Override
protected void setInternalValueDate(Date value)
{
huAttribute.setValueDate(TimeUtil.asTimestamp(value));
this.valueDate = value;
}
@Override
protected Date getInternalValueDate()
{
return valueDate;
}
@Override
protected void setInternalValueDateInitial(Date value)
{
huAttribute.setValueDateInitial(TimeUtil.asTimestamp(value));
}
@Override
protected Date getInternalValueDateInitial()
{
return huAttribute.getValueDateInitial();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\HUAttributeValue.java
| 1
|
请完成以下Java代码
|
private final String getAggregationKey(final ShipmentScheduleWithHU schedWithHU)
{
if (schedWithHU == null)
{
return "";
}
final I_M_ShipmentSchedule shipmentSchedule = schedWithHU.getM_ShipmentSchedule();
if (shipmentSchedule == null)
{
// shall not happen
return "";
}
final StringBuilder aggregationKey = new StringBuilder();
//
// Shipment header aggregation key (from M_ShipmentSchedule)
final String shipmentScheduleAggregationKey = shipmentScheduleKeyBuilder.buildKey(shipmentSchedule);
if (shipmentScheduleAggregationKey != null)
{
aggregationKey.append(shipmentScheduleAggregationKey);
}
//
// Shipment header aggregation key (the HU related part)
final String huShipmentScheduleAggregationKey = huShipmentScheduleKeyBuilder.buildKey(schedWithHU);
if (huShipmentScheduleAggregationKey != null)
{
if (aggregationKey.length() > 0)
{
aggregationKey.append("#");
}
aggregationKey.append(huShipmentScheduleAggregationKey);
}
//
// Shipment line aggregation key
{
final Object attributesAggregationKey = schedWithHU.getAttributesAggregationKey();
if (aggregationKey.length() > 0)
{
aggregationKey.append("#");
}
|
aggregationKey.append(attributesAggregationKey);
}
return aggregationKey.toString();
}
private final int getM_HU_ID(@NonNull final ShipmentScheduleWithHU schedWithHU)
{
final I_M_HU huRecord = coalesce(schedWithHU.getM_LU_HU(), schedWithHU.getM_TU_HU(), schedWithHU.getVHU());
if (huRecord == null)
{
return Integer.MAX_VALUE;
}
final int huId = huRecord.getM_HU_ID();
if (huId <= 0)
{
return Integer.MAX_VALUE;
}
return huId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleWithHUComparator.java
| 1
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
|
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
}
}
|
repos\tutorials-master\libraries-http\src\main\java\com\baeldung\retrofitguide\User.java
| 1
|
请完成以下Java代码
|
void comment(Username user, String message) {
comments.add(new Comment(user, message));
}
void like(Username user) {
likedBy.add(user);
}
void dislike(Username user) {
likedBy.remove(user);
}
public Slug getSlug() {
return slug;
}
public Username getAuthor() {
return author;
}
public String getTitle() {
return title;
|
}
public String getContent() {
return content;
}
public Status getStatus() {
return status;
}
public List<Comment> getComments() {
return Collections.unmodifiableList(comments);
}
public List<Username> getLikedBy() {
return Collections.unmodifiableList(likedBy);
}
}
|
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddjmolecules\article\Article.java
| 1
|
请完成以下Java代码
|
public void setJob(String job) {
this.job = job;
}
public String getPersonalizedSignature() {
return personalizedSignature;
}
public void setPersonalizedSignature(String personalizedSignature) {
this.personalizedSignature = personalizedSignature;
}
public Integer getSourceType() {
return sourceType;
}
public void setSourceType(Integer sourceType) {
this.sourceType = sourceType;
}
public Integer getIntegration() {
return integration;
}
public void setIntegration(Integer integration) {
this.integration = integration;
}
public Integer getGrowth() {
return growth;
}
public void setGrowth(Integer growth) {
this.growth = growth;
}
public Integer getLuckeyCount() {
return luckeyCount;
}
public void setLuckeyCount(Integer luckeyCount) {
this.luckeyCount = luckeyCount;
}
|
public Integer getHistoryIntegration() {
return historyIntegration;
}
public void setHistoryIntegration(Integer historyIntegration) {
this.historyIntegration = historyIntegration;
}
@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(", memberLevelId=").append(memberLevelId);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", nickname=").append(nickname);
sb.append(", phone=").append(phone);
sb.append(", status=").append(status);
sb.append(", createTime=").append(createTime);
sb.append(", icon=").append(icon);
sb.append(", gender=").append(gender);
sb.append(", birthday=").append(birthday);
sb.append(", city=").append(city);
sb.append(", job=").append(job);
sb.append(", personalizedSignature=").append(personalizedSignature);
sb.append(", sourceType=").append(sourceType);
sb.append(", integration=").append(integration);
sb.append(", growth=").append(growth);
sb.append(", luckeyCount=").append(luckeyCount);
sb.append(", historyIntegration=").append(historyIntegration);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMember.java
| 1
|
请完成以下Java代码
|
public class C_Invoice_Line_Alloc
{
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_DELETE })
public void invalidateCandidate(final I_C_Invoice_Line_Alloc ila)
{
Services.get(IInvoiceCandDAO.class).invalidateCand(ila.getC_Invoice_Candidate());
}
/**
* Making sure that the invoiced qty is not above invoice candidate's the invoiceable qty, i.e. <code>QtyToInvoice + QtyInvoiced</code>.
* In the absence of any bugs, this would not be the case, but this method makes sure.
*
* @param ila
*/
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_BEFORE_DELETE })
public void checkConsistency(final I_C_Invoice_Line_Alloc ila)
{
// Commented out for now, interferes with 05420
//
// final I_C_Invoice_Candidate ic = ila.getC_Invoice_Candidate();
//
// if (ic.isToRecompute() || ic.isToClear())
// {
// return;
// }
|
//
// final BigDecimal invoicedQty =
// new Query(InterfaceWrapperHelper.getCtx(ila), I_C_Invoice_Line_Alloc.Table_Name, I_C_Invoice_Line_Alloc.COLUMNNAME_C_Invoice_Candidate_ID + "=?",
// InterfaceWrapperHelper.getTrxName(ila))
// .setParameters(ila.getC_Invoice_Candidate_ID())
// .setOnlyActiveRecords(true)
// .setClient_ID()
// .sum(I_C_Invoice_Line_Alloc.COLUMNNAME_QtyInvoiced);
//
// final BigDecimal maxQty = ic.getQtyToInvoice().add(ic.getQtyInvoiced());
//
// Check.assume(invoicedQty.compareTo(maxQty) <= 0,
// ic + " has QtyToInvoice + QtyInvoiced = " + maxQty + " but the QtyInvoiced of all C_Invoice_Line_Allocs sums up to " + invoicedQty);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\C_Invoice_Line_Alloc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setName(Object value) {
this.name = value;
}
/**
* Gets the value of the department property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getDepartment() {
return department;
}
/**
* Sets the value of the department property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setDepartment(Object value) {
this.department = value;
}
/**
* Gets the value of the street property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getStreet() {
return street;
}
/**
* Sets the value of the street property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setStreet(Object value) {
this.street = value;
}
/**
* Gets the value of the zip property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getZIP() {
return zip;
}
/**
* Sets the value of the zip property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setZIP(Object value) {
this.zip = value;
|
}
/**
* Gets the value of the town property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getTown() {
return town;
}
/**
* Sets the value of the town property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setTown(Object value) {
this.town = value;
}
/**
* Gets the value of the country property.
*
* @return
* possible object is
* {@link Object }
*
*/
public Object getCountry() {
return country;
}
/**
* Sets the value of the country property.
*
* @param value
* allowed object is
* {@link Object }
*
*/
public void setCountry(Object value) {
this.country = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ShipFromType.java
| 2
|
请完成以下Java代码
|
private Collection<OrgId> getOrgIdsToUse(@NonNull final AcctSchema acctSchema, @Nullable final OrgId orgId)
{
if (orgId != null)
{
return Collections.singleton(orgId);
}
final ImmutableSet<OrgId> postOnlyForOrgIds = acctSchema.getPostOnlyForOrgIds();
return postOnlyForOrgIds.isEmpty() ? Collections.singleton(acctSchema.getOrgId()) : postOnlyForOrgIds;
}
private void updateDebitorCreditorIdsAndSave(@NonNull final AcctSchema acctSchema, @NonNull final I_C_BPartner bpartner)
{
Services.get(ITrxManager.class).runInNewTrx(localTrxName -> {
try
{
updateDebitorCreditorIds(acctSchema, bpartner);
InterfaceWrapperHelper.save(bpartner);
}
catch (final RuntimeException runException)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.WARN);
loggable.addLog("AcctSchemaBL.updateDebitorCreditorIdsAndSave, for bpartnerId {} - caught {} with message={}",
bpartner.getC_BPartner_ID(),
runException.getClass(),
runException.getMessage(),
runException);
}
});
}
@Override
public void updateDebitorCreditorIds(@NonNull final AcctSchema acctSchema, @NonNull final I_C_BPartner bpartner)
{
if (acctSchema.isAutoSetDebtoridAndCreditorid())
{
String value = bpartner.getValue();
//as per c_bpartner_datev_no_generate.sql, we should be updating only values with length between 5 and 7
|
if (Check.isNotBlank(value))
{
if (value.startsWith("<") && value.endsWith(">"))
{
value = value.substring(1, value.length() - 1);
}
if (value.length() >= 5 && value.length() <= 7 && StringUtils.isNumber(value))
{
final String valueAsString = Strings.padStart(value, 7, '0').substring(0, 7);
bpartner.setCreditorId(Integer.parseInt(acctSchema.getCreditorIdPrefix() + valueAsString));
bpartner.setDebtorId(Integer.parseInt(acctSchema.getDebtorIdPrefix() + valueAsString));
}
else
{
Loggables.withLogger(logger, Level.DEBUG).addLog("value {} for bpartnerId {} must be a number with 5 to 7 digits", value, bpartner.getC_BPartner_ID());
}
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AcctSchemaBL.java
| 1
|
请完成以下Java代码
|
public AmountSourceAndAcct add(@NonNull final AmountSourceAndAcct other)
{
assertCurrencyAndRateMatching(other);
if (other.isZero())
{
return this;
}
else if (this.isZero())
{
return other;
}
else
{
return toBuilder()
.amtSource(this.amtSource.add(other.amtSource))
.amtAcct(this.amtAcct.add(other.amtAcct))
.build();
}
|
}
public AmountSourceAndAcct subtract(@NonNull final AmountSourceAndAcct other)
{
return add(other.negate());
}
private void assertCurrencyAndRateMatching(@NonNull final AmountSourceAndAcct other)
{
if (!Objects.equals(this.currencyAndRate, other.currencyAndRate))
{
throw new AdempiereException("Currency rate not matching: " + this.currencyAndRate + ", " + other.currencyAndRate);
}
}
}
} // Doc_Bank
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\acct\Doc_BankStatement.java
| 1
|
请完成以下Java代码
|
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
String name = (String)getFromCache(value);
if(name == null) {
init(value);
name = (String)getFromCache(value);
}
setName(name);
return this;
}
/*
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if(!isVirtual()) {
if(!isInitialized()) {
init(value);
}
return this;
}
else {
CachableTreeCellRenderer r = null;
try {
System.out.println(this.getClass()+" class: "+getClass());
r = (CachableTreeCellRenderer)this.getClass().newInstance();
r.setVirtual(false);
r.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
complement = (CachableTreeCellRenderer)tree.getCellRenderer();
|
tree.setCellRenderer(r);
}
catch(Exception e) {
e.printStackTrace();
}
return r;
}
}
*/
public boolean isInitialized() {
return !cache.isEmpty();
}
public void addToCache(Object key, Object value) {
cache.put(key, value);
}
public Object getFromCache(Object key) {
return cache.get(key);
}
public boolean isVirtual() {
return virtual;
}
public void setVirtual(boolean on) {
this.virtual = on;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\form\tree\CachableTreeCellRenderer.java
| 1
|
请完成以下Java代码
|
public class SetVariablesAsyncDto {
protected List<String> processInstanceIds;
protected ProcessInstanceQueryDto processInstanceQuery;
protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery;
protected Map<String, VariableValueDto> variables;
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(List<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
public ProcessInstanceQueryDto getProcessInstanceQuery() {
return processInstanceQuery;
}
public void setProcessInstanceQuery(ProcessInstanceQueryDto runtimeQuery) {
this.processInstanceQuery = runtimeQuery;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
|
return historicProcessInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historyQuery) {
this.historicProcessInstanceQuery = historyQuery;
}
public Map<String, VariableValueDto> getVariables() {
return variables;
}
public void setVariables(Map<String, VariableValueDto> variables) {
this.variables = variables;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\batch\SetVariablesAsyncDto.java
| 1
|
请完成以下Java代码
|
public int getC_Flatrate_Term_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Term_ID);
}
@Override
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCand_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
/**
* DocStatus AD_Reference_ID=131
* Reference name: _Document Status
*/
public static final int DOCSTATUS_AD_Reference_ID=131;
/** Drafted = DR */
public static final String DOCSTATUS_Drafted = "DR";
/** Completed = CO */
public static final String DOCSTATUS_Completed = "CO";
/** Approved = AP */
public static final String DOCSTATUS_Approved = "AP";
/** NotApproved = NA */
public static final String DOCSTATUS_NotApproved = "NA";
/** Voided = VO */
public static final String DOCSTATUS_Voided = "VO";
/** Invalid = IN */
public static final String DOCSTATUS_Invalid = "IN";
/** Reversed = RE */
|
public static final String DOCSTATUS_Reversed = "RE";
/** Closed = CL */
public static final String DOCSTATUS_Closed = "CL";
/** Unknown = ?? */
public static final String DOCSTATUS_Unknown = "??";
/** InProgress = IP */
public static final String DOCSTATUS_InProgress = "IP";
/** WaitingPayment = WP */
public static final String DOCSTATUS_WaitingPayment = "WP";
/** WaitingConfirmation = WC */
public static final String DOCSTATUS_WaitingConfirmation = "WC";
@Override
public void setDocStatus (final @Nullable java.lang.String DocStatus)
{
throw new IllegalArgumentException ("DocStatus is virtual column"); }
@Override
public java.lang.String getDocStatus()
{
return get_ValueAsString(COLUMNNAME_DocStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Contract_Term_Alloc.java
| 1
|
请完成以下Java代码
|
public String getErrorDetails() {
return errorDetails;
}
public String getBusinessKey() {
return businessKey;
}
public Map<String, String> getExtensionProperties(){
return extensionProperties;
}
public static LockedExternalTaskDto fromLockedExternalTask(LockedExternalTask task) {
LockedExternalTaskDto dto = new LockedExternalTaskDto();
dto.activityId = task.getActivityId();
dto.activityInstanceId = task.getActivityInstanceId();
dto.errorMessage = task.getErrorMessage();
dto.errorDetails = task.getErrorDetails();
dto.executionId = task.getExecutionId();
dto.id = task.getId();
dto.lockExpirationTime = task.getLockExpirationTime();
dto.createTime = task.getCreateTime();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processDefinitionKey = task.getProcessDefinitionKey();
dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag();
dto.processInstanceId = task.getProcessInstanceId();
dto.retries = task.getRetries();
dto.topicName = task.getTopicName();
dto.workerId = task.getWorkerId();
dto.tenantId = task.getTenantId();
dto.variables = VariableValueDto.fromMap(task.getVariables());
dto.priority = task.getPriority();
dto.businessKey = task.getBusinessKey();
dto.extensionProperties = task.getExtensionProperties();
return dto;
}
public static List<LockedExternalTaskDto> fromLockedExternalTasks(List<LockedExternalTask> tasks) {
List<LockedExternalTaskDto> dtos = new ArrayList<>();
for (LockedExternalTask task : tasks) {
dtos.add(LockedExternalTaskDto.fromLockedExternalTask(task));
}
|
return dtos;
}
@Override
public String toString() {
return
"LockedExternalTaskDto [activityId=" + activityId
+ ", activityInstanceId=" + activityInstanceId
+ ", errorMessage=" + errorMessage
+ ", errorDetails=" + errorDetails
+ ", executionId=" + executionId
+ ", id=" + id
+ ", lockExpirationTime=" + lockExpirationTime
+ ", createTime=" + createTime
+ ", processDefinitionId=" + processDefinitionId
+ ", processDefinitionKey=" + processDefinitionKey
+ ", processDefinitionVersionTag=" + processDefinitionVersionTag
+ ", processInstanceId=" + processInstanceId
+ ", retries=" + retries
+ ", suspended=" + suspended
+ ", workerId=" + workerId
+ ", topicName=" + topicName
+ ", tenantId=" + tenantId
+ ", variables=" + variables
+ ", priority=" + priority
+ ", businessKey=" + businessKey + "]";
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\LockedExternalTaskDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class AbstractManager {
protected TaskServiceConfiguration taskServiceConfiguration;
public AbstractManager(TaskServiceConfiguration taskServiceConfiguration) {
this.taskServiceConfiguration = taskServiceConfiguration;
}
// Command scoped
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected TaskServiceConfiguration getTaskServiceConfiguration() {
return taskServiceConfiguration;
}
|
protected Clock getClock() {
return getTaskServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getTaskServiceConfiguration().getEventDispatcher();
}
protected TaskEntityManager getTaskEntityManager() {
return getTaskServiceConfiguration().getTaskEntityManager();
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getTaskServiceConfiguration().getHistoricTaskInstanceEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\AbstractManager.java
| 2
|
请完成以下Java代码
|
public class X_M_HU_PackagingCode extends org.compiere.model.PO implements I_M_HU_PackagingCode, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1348078474L;
/** Standard Constructor */
public X_M_HU_PackagingCode (final Properties ctx, final int M_HU_PackagingCode_ID, @Nullable final String trxName)
{
super (ctx, M_HU_PackagingCode_ID, trxName);
}
/** Load Constructor */
public X_M_HU_PackagingCode (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* HU_UnitType AD_Reference_ID=540472
* Reference name: HU_UnitType
*/
public static final int HU_UNITTYPE_AD_Reference_ID=540472;
/** TransportUnit = TU */
public static final String HU_UNITTYPE_TransportUnit = "TU";
/** LoadLogistiqueUnit = LU */
public static final String HU_UNITTYPE_LoadLogistiqueUnit = "LU";
/** VirtualPI = V */
public static final String HU_UNITTYPE_VirtualPI = "V";
@Override
public void setHU_UnitType (final @Nullable java.lang.String HU_UnitType)
{
set_Value (COLUMNNAME_HU_UnitType, HU_UnitType);
}
@Override
public java.lang.String getHU_UnitType()
|
{
return get_ValueAsString(COLUMNNAME_HU_UnitType);
}
@Override
public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID)
{
if (M_HU_PackagingCode_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID);
}
@Override
public int getM_HU_PackagingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID);
}
@Override
public void setPackagingCode (final java.lang.String PackagingCode)
{
set_Value (COLUMNNAME_PackagingCode, PackagingCode);
}
@Override
public java.lang.String getPackagingCode()
{
return get_ValueAsString(COLUMNNAME_PackagingCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackagingCode.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8080
servlet:
context-path: /demo
spring:
swagger:
enabled: true
title: spring-boot-demo
base-package: com.xkcoding.swagger.beauty.controller
description: 这是一个简单的 Swagger API 演示
version: 1.0.0-SNAPSHOT
contact:
name: Yangkai.Shen
email: 237497819@qq.com
url: http://xkcoding.com
# swagger扫描的基础包,默认:全扫描
# base-package:
# 需要处理的基础URL规则,默认:/**
# base-path:
# 需要排除的URL规则,默认:空
# exclude-path:
security:
# 是否启用 swagger 登录验证
filter-plugin: true
username: xkcoding
password: 123456
global-response-messages:
GET[0]:
code: 400
message: Bad Request,一般为请求参数不对
GET[1]:
code: 404
|
message: NOT FOUND,一般为请求路径不对
GET[2]:
code: 500
message: ERROR,一般为程序内部错误
POST[0]:
code: 400
message: Bad Request,一般为请求参数不对
POST[1]:
code: 404
message: NOT FOUND,一般为请求路径不对
POST[2]:
code: 500
message: ERROR,一般为程序内部错误
|
repos\spring-boot-demo-master\demo-swagger-beauty\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class EmployeeDto {
@JsonProperty("name")
private String name;
@JsonProperty("dept")
private String dept;
@JsonProperty("salary")
private long salary;
public EmployeeDto() {
}
public EmployeeDto(String name, String dept, long salary) {
this.name = name;
this.dept = dept;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-rest\src\main\java\com\baeldung\pageentityresponse\EmployeeDto.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.