instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getStateStr() {
return stateStr;
}
public void setStateStr(String stateStr) {
this.stateStr = stateStr;
}
public String getPids() {
return pids;
}
public void setPids(String pids) {
this.pids = pids;
}
public List<Integer> getPidsList() { | return pidsList;
}
public void setPidsList(List<Integer> pidsList) {
this.pidsList = pidsList;
}
public String getPnames() {
return pnames;
}
public void setPnames(String pnames) {
this.pnames = pnames;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\model\ManagerInfo.java | 1 |
请完成以下Java代码 | private Optional<TableRecordReference> retrieveParentRecordRef()
{
final GenericZoomIntoTableInfo tableInfo = getTableInfo();
if (tableInfo.getParentTableName() == null
|| tableInfo.getParentLinkColumnName() == null)
{
return Optional.empty();
}
final String sqlWhereClause = getRecordWhereClause(); // might be null
if (sqlWhereClause == null || Check.isBlank(sqlWhereClause))
{
return Optional.empty();
}
final String sql = "SELECT " + tableInfo.getParentLinkColumnName()
+ " FROM " + tableInfo.getTableName()
+ " WHERE " + sqlWhereClause;
try
{
final int parentRecordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql);
if (parentRecordId < InterfaceWrapperHelper.getFirstValidIdByColumnName(tableInfo.getParentTableName() + "_ID"))
{
return Optional.empty();
}
final TableRecordReference parentRecordRef = TableRecordReference.of(tableInfo.getParentTableName(), parentRecordId);
return Optional.of(parentRecordRef);
}
catch (final Exception ex) | {
logger.warn("Failed retrieving parent record ID from current record. Returning empty. \n\tthis={} \n\tSQL: {}", this, sql, ex);
return Optional.empty();
}
}
@NonNull
private static CustomizedWindowInfoMapRepository getCustomizedWindowInfoMapRepository()
{
return !Adempiere.isUnitTestMode()
? SpringContextHolder.instance.getBean(CustomizedWindowInfoMapRepository.class)
: NullCustomizedWindowInfoMapRepository.instance;
}
@Value
@Builder
private static class TableInfoCacheKey
{
@NonNull String tableName;
boolean ignoreExcludeFromZoomTargetsFlag;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\RecordWindowFinder.java | 1 |
请完成以下Java代码 | public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
} | @Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Product.java | 1 |
请完成以下Java代码 | private <T> T sendXmlObject(final Object xmlRequestObj)
{
final Document xmlRequest = convertObjectToDocument(xmlRequestObj);
final StringBuilder importInfo = new StringBuilder();
final Document xmlResponse = importHelper.importXMLDocument(importInfo, xmlRequest, ITrx.TRXNAME_None);
if (xmlResponse == null)
{
return null;
}
try
{
@SuppressWarnings("unchecked")
final JAXBElement<T> jaxbElement = (JAXBElement<T>)jaxbUnmarshaller.unmarshal(xmlResponse);
final T xmlResponseObj = jaxbElement.getValue();
return xmlResponseObj;
}
catch (Exception e)
{
throw new AdempiereException("Cannot unmarshall xml response '" + xmlResponse + "' associated with request '" + xmlRequestObj + "'", e);
}
}
private Document convertObjectToDocument(final Object xmlObj)
{
try
{
return convertObjectToDocument0(xmlObj);
}
catch (final Exception e)
{
throw new AdempiereException("Error while converting object '" + xmlObj + "' to XML document", e);
}
}
private Document convertObjectToDocument0(final Object xmlObj) throws JAXBException, ParserConfigurationException, SAXException, IOException
{
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setValidating(false);
final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
final Document document = documentBuilder.newDocument(); | final JAXBElement<Object> jaxbElement = ObjectFactoryHelper.createJAXBElement(new ObjectFactory(), xmlObj);
jaxbMarshaller.marshal(jaxbElement, document);
return document;
}
private String createTransactionId()
{
final String transactionId = UUID.randomUUID().toString();
return transactionId;
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
// final PRTLoginRequestType xmlLoginRequest = LoginRequestConverter.instance.convert(loginRequest);
// final PRTLoginRequestType xmlLoginResponse = sendXmlObject(xmlLoginRequest);
// final LoginResponse loginResponse = LoginResponseConverter.instance.convert(xmlLoginResponse);
// return loginResponse;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.embedded-client\src\main\java\de\metas\printing\client\endpoint\LoopbackPrintConnectionEndpoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the comments
*/
public CommentCollectionResource getComments() {
return comments;
}
/**
* @param comments the comments to set
*/
public void setComments(CommentCollectionResource comments) {
this.comments = comments;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comments == null) ? 0 : comments.hashCode());
result = prime * result + (completed ? 1231 : 1237);
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((taskId == null) ? 0 : taskId.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TaskDTO other = (TaskDTO) obj;
if (comments == null) {
if (other.comments != null)
return false;
} else if (!comments.equals(other.comments))
return false;
if (completed != other.completed) | return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (taskId == null) {
if (other.taskId != null)
return false;
} else if (!taskId.equals(other.taskId))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TaskDTO [taskId=" + taskId + ", description=" + description + ", completed=" + completed + ", userName="
+ userName + ", comments=" + comments + "]";
}
} | repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\dtos\TaskDTO.java | 2 |
请完成以下Java代码 | private I_DD_Order createDDOrderHeader(@NonNull final I_M_InOutLine inOutLine)
{
final IProductPlanningDAO productPlanningDAO = Services.get(IProductPlanningDAO.class);
final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
final ProductId productId = ProductId.ofRepoId(inOutLine.getM_Product_ID());
final OrgId orgId = OrgId.ofRepoId(inOutLine.getAD_Org_ID());
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoId(inOutLine.getM_AttributeSetInstance_ID());
final ProductPlanningQuery query = ProductPlanningQuery.builder()
.orgId(orgId)
.productId(productId)
.attributeSetInstanceId(asiId)
// no warehouse, no plant
.build();
final ProductPlanning productPlanning = productPlanningDAO.find(query)
.orElseThrow(() -> new AdempiereException("No Product Planning found for " + query));
final DocTypeQuery docTypeQuery = DocTypeQuery.builder()
.docBaseType(X_C_DocType.DOCBASETYPE_DistributionOrder)
.adClientId(inOutLine.getAD_Client_ID())
.adOrgId(inOutLine.getAD_Org_ID())
.build();
final int docTypeId = docTypeDAO.getDocTypeId(docTypeQuery).getRepoId();
final I_M_InOut inout = inOutLine.getM_InOut();
final I_DD_Order ddOrderHeader = newInstance(I_DD_Order.class);
ddOrderHeader.setC_BPartner_ID(inout.getC_BPartner_ID());
ddOrderHeader.setC_BPartner_Location_ID(inout.getC_BPartner_Location_ID());
ddOrderHeader.setDeliveryViaRule(inout.getDeliveryViaRule());
ddOrderHeader.setDeliveryRule(inout.getDeliveryRule());
ddOrderHeader.setPriorityRule(inout.getPriorityRule());
ddOrderHeader.setM_Warehouse_ID(WarehouseId.toRepoId(productPlanning.getWarehouseId()));
ddOrderHeader.setC_DocType_ID(docTypeId);
ddOrderHeader.setDocStatus(X_DD_Order.DOCSTATUS_Drafted);
ddOrderHeader.setDocAction(X_DD_Order.DOCACTION_Complete);
ddOrderHeader.setIsInDispute(inOutLine.isInDispute());
ddOrderHeader.setIsInTransit(inout.isInTransit());
save(ddOrderHeader);
return ddOrderHeader;
}
private I_DD_OrderLine createDDOrderLine(
@NonNull final I_DD_Order ddOrderHeader, | @NonNull final I_M_InOutLine inOutLine,
@Nullable final LocatorId locatorToId)
{
final I_M_InOut inout = inOutLine.getM_InOut();
final I_DD_OrderLine ddOrderLine = newInstance(I_DD_OrderLine.class);
ddOrderLine.setDD_Order(ddOrderHeader);
ddOrderLine.setLine(10);
ddOrderLine.setM_Product_ID(inOutLine.getM_Product_ID());
ddOrderLine.setQtyEntered(inOutLine.getQtyEntered());
ddOrderLine.setC_UOM_ID(inOutLine.getC_UOM_ID());
ddOrderLine.setQtyEnteredTU(inOutLine.getQtyEnteredTU());
ddOrderLine.setM_HU_PI_Item_Product(inOutLine.getM_HU_PI_Item_Product());
ddOrderLine.setM_Locator_ID(inOutLine.getM_Locator_ID());
ddOrderLine.setM_LocatorTo_ID(locatorToId.getRepoId());
ddOrderLine.setIsInvoiced(false);
ddOrderLine.setDateOrdered(inout.getDateOrdered());
ddOrderLine.setDatePromised(inout.getMovementDate());
save(ddOrderLine);
return ddOrderLine;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\impl\InOutDDOrderBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RestartProcessInstancesBatchConfiguration extends BatchConfiguration {
protected List<AbstractProcessInstanceModificationCommand> instructions;
protected String processDefinitionId;
protected boolean initialVariables;
protected boolean skipCustomListeners;
protected boolean skipIoMappings;
protected boolean withoutBusinessKey;
public RestartProcessInstancesBatchConfiguration(List<String> processInstanceIds,
List<AbstractProcessInstanceModificationCommand> instructions, String processDefinitionId,
boolean initialVariables, boolean skipCustomListeners, boolean skipIoMappings, boolean withoutBusinessKey) {
this(processInstanceIds, null, instructions, processDefinitionId, initialVariables, skipCustomListeners, skipIoMappings, withoutBusinessKey);
}
public RestartProcessInstancesBatchConfiguration(List<String> processInstanceIds, DeploymentMappings mappings,
List<AbstractProcessInstanceModificationCommand> instructions, String processDefinitionId,
boolean initialVariables, boolean skipCustomListeners, boolean skipIoMappings, boolean withoutBusinessKey) {
super(processInstanceIds, mappings);
this.instructions = instructions;
this.processDefinitionId = processDefinitionId;
this.initialVariables = initialVariables;
this.skipCustomListeners = skipCustomListeners;
this.skipIoMappings = skipIoMappings;
this.withoutBusinessKey = withoutBusinessKey;
}
public List<AbstractProcessInstanceModificationCommand> getInstructions() {
return instructions;
}
public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
this.instructions = instructions;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) { | this.processDefinitionId = processDefinitionId;
}
public boolean isInitialVariables() {
return initialVariables;
}
public void setInitialVariables(boolean initialVariables) {
this.initialVariables = initialVariables;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
public void setWithoutBusinessKey(boolean withoutBusinessKey) {
this.withoutBusinessKey = withoutBusinessKey;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstancesBatchConfiguration.java | 2 |
请完成以下Java代码 | private void markAsBuilt()
{
final boolean wasAlreadyBuilt = built.getAndSet(true);
Check.assume(!wasAlreadyBuilt, "not already built");
}
@Override
public IWorkPackageBuilder end()
{
return _parentBuilder;
}
/* package */void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage workpackage)
{
assertNotBuilt();
_workpackage = workpackage;
}
private I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
Check.assumeNotNull(_workpackage, "workpackage not null");
return _workpackage;
}
@Override
public IWorkPackageParamsBuilder setParameter(final String parameterName, final Object parameterValue)
{
assertNotBuilt();
Check.assumeNotEmpty(parameterName, "parameterName not empty");
parameterName2valueMap.put(parameterName, parameterValue);
return this;
}
@Override
public IWorkPackageParamsBuilder setParameters(final Map<String, ?> parameters)
{
assertNotBuilt();
if (parameters == null || parameters.isEmpty())
{
return this;
}
for (final Map.Entry<String, ?> param : parameters.entrySet())
{ | final String parameterName = param.getKey();
Check.assumeNotEmpty(parameterName, "parameterName not empty");
final Object parameterValue = param.getValue();
parameterName2valueMap.put(parameterName, parameterValue);
}
return this;
}
@Override
public IWorkPackageParamsBuilder setParameters(@Nullable final IParams parameters)
{
assertNotBuilt();
if (parameters == null)
{
return this;
}
final Collection<String> parameterNames = parameters.getParameterNames();
if(parameterNames.isEmpty())
{
return this;
}
for (final String parameterName : parameterNames)
{
Check.assumeNotEmpty(parameterName, "parameterName not empty");
final Object parameterValue = parameters.getParameterAsObject(parameterName);
parameterName2valueMap.put(parameterName, parameterValue);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageParamsBuilder.java | 1 |
请完成以下Java代码 | public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQR_IBAN (final @Nullable java.lang.String QR_IBAN)
{
set_Value (COLUMNNAME_QR_IBAN, QR_IBAN);
}
@Override
public java.lang.String getQR_IBAN()
{
return get_ValueAsString(COLUMNNAME_QR_IBAN);
}
/**
* R_AvsAddr AD_Reference_ID=213
* Reference name: C_Payment AVS
*/
public static final int R_AVSADDR_AD_Reference_ID=213;
/** Match = Y */
public static final String R_AVSADDR_Match = "Y";
/** NoMatch = N */
public static final String R_AVSADDR_NoMatch = "N";
/** Unavailable = X */
public static final String R_AVSADDR_Unavailable = "X";
@Override
public void setR_AvsAddr (final @Nullable java.lang.String R_AvsAddr)
{
set_ValueNoCheck (COLUMNNAME_R_AvsAddr, R_AvsAddr);
}
@Override
public java.lang.String getR_AvsAddr()
{
return get_ValueAsString(COLUMNNAME_R_AvsAddr);
}
/**
* R_AvsZip AD_Reference_ID=213
* Reference name: C_Payment AVS
*/
public static final int R_AVSZIP_AD_Reference_ID=213;
/** Match = Y */
public static final String R_AVSZIP_Match = "Y";
/** NoMatch = N */
public static final String R_AVSZIP_NoMatch = "N";
/** Unavailable = X */
public static final String R_AVSZIP_Unavailable = "X"; | @Override
public void setR_AvsZip (final @Nullable java.lang.String R_AvsZip)
{
set_ValueNoCheck (COLUMNNAME_R_AvsZip, R_AvsZip);
}
@Override
public java.lang.String getR_AvsZip()
{
return get_ValueAsString(COLUMNNAME_R_AvsZip);
}
@Override
public void setRoutingNo (final @Nullable java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setSEPA_CreditorIdentifier (final @Nullable java.lang.String SEPA_CreditorIdentifier)
{
set_Value (COLUMNNAME_SEPA_CreditorIdentifier, SEPA_CreditorIdentifier);
}
@Override
public java.lang.String getSEPA_CreditorIdentifier()
{
return get_ValueAsString(COLUMNNAME_SEPA_CreditorIdentifier);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<String> index() {
return new ResponseEntity<>("Index", HttpStatus.OK);
}
@GetMapping("/greeting")
public ResponseEntity<String> greeting(@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE) String language) {
String greeting = "";
List<Locale.LanguageRange> ranges = Locale.LanguageRange.parse(language);
String firstLanguage = ranges.get(0).getRange();
switch (firstLanguage) {
case "es":
greeting = "Hola!";
break;
case "de":
greeting = "Hallo!";
break;
case "fr":
greeting = "Bonjour!";
break;
case "en":
default:
greeting = "Hello!";
break;
}
return new ResponseEntity<>(greeting, HttpStatus.OK);
}
@GetMapping("/double")
public ResponseEntity<String> doubleNumber(@RequestHeader("my-number") int myNumber) {
return new ResponseEntity<>(
String.format("%d * 2 = %d", myNumber, (myNumber * 2)),
HttpStatus.OK);
}
@GetMapping("/listHeaders")
public ResponseEntity<String> listAllHeaders(@RequestHeader Map<String, String> headers) {
headers.forEach((key, value) -> LOG.info(String.format("Header '%s' = %s", key, value)));
return new ResponseEntity<>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
} | @GetMapping("/multiValue")
public ResponseEntity<String> multiValue(@RequestHeader MultiValueMap<String, String> headers) {
headers.forEach((key, value) -> LOG.info(String.format("Header '%s' = %s", key, String.join("|", value))));
return new ResponseEntity<>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
}
@GetMapping("/getBaseUrl")
public ResponseEntity<String> getBaseUrl(@RequestHeader HttpHeaders headers) {
InetSocketAddress host = headers.getHost();
String url = "http://" + host.getHostName() + ":" + host.getPort();
return new ResponseEntity<>(String.format("Base URL = %s", url), HttpStatus.OK);
}
@GetMapping("/nonRequiredHeader")
public ResponseEntity<String> evaluateNonRequiredHeader(
@RequestHeader(value = "optional-header", required = false) String optionalHeader) {
return new ResponseEntity<>(
String.format("Was the optional header present? %s!", (optionalHeader == null ? "No" : "Yes")),
HttpStatus.OK);
}
@GetMapping("/default")
public ResponseEntity<String> evaluateDefaultHeaderValue(
@RequestHeader(value = "optional-header", defaultValue = "3600") int optionalHeader) {
return new ResponseEntity<>(String.format("Optional Header is %d", optionalHeader), HttpStatus.OK);
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\headers\controller\ReadHeaderRestController.java | 2 |
请完成以下Java代码 | public void setFirauditer(String firauditer) {
this.firauditer = firauditer;
}
public String getFiraudittime() {
return firaudittime;
}
public void setFiraudittime(String firaudittime) {
this.firaudittime = firaudittime;
}
public String getFinauditer() {
return finauditer;
}
public void setFinauditer(String finauditer) {
this.finauditer = finauditer;
}
public String getFinaudittime() {
return finaudittime;
}
public void setFinaudittime(String finaudittime) {
this.finaudittime = finaudittime;
}
public String getEdittime() {
return edittime;
}
public void setEdittime(String edittime) {
this.edittime = edittime;
} | public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtoll.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Pair<Boolean, Boolean> saveOrUpdateAiModel(TenantId tenantId, AiModelId aiModelId, AiModelUpdateMsg aiModelUpdateMsg) {
boolean isCreated = false;
boolean isNameUpdated = false;
try {
AiModel aiModel = JacksonUtil.fromString(aiModelUpdateMsg.getEntity(), AiModel.class, true);
if (aiModel == null) {
throw new RuntimeException("[{" + tenantId + "}] aiModelUpdateMsg {" + aiModelUpdateMsg + " } cannot be converted to aiModel");
}
Optional<AiModel> aiModelById = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId);
if (aiModelById.isEmpty()) {
aiModel.setCreatedTime(Uuids.unixTimestamp(aiModelId.getId()));
isCreated = true;
aiModel.setId(null);
} else {
aiModel.setId(aiModelId);
}
String aiModelName = aiModel.getName();
Optional<AiModel> aiModelByName = edgeCtx.getAiModelService().findAiModelByTenantIdAndName(aiModel.getTenantId(), aiModelName);
if (aiModelByName.isPresent() && !aiModelByName.get().getId().equals(aiModelId)) {
aiModelName = aiModelName + "_" + StringUtils.randomAlphabetic(15);
log.warn("[{}] aiModel with name {} already exists. Renaming aiModel name to {}",
tenantId, aiModel.getName(), aiModelByName.get().getName());
isNameUpdated = true;
}
aiModel.setName(aiModelName); | aiModelValidator.validate(aiModel, AiModel::getTenantId);
if (isCreated) {
aiModel.setId(aiModelId);
}
edgeCtx.getAiModelService().save(aiModel, false);
} catch (Exception e) {
log.error("[{}] Failed to process aiModel update msg [{}]", tenantId, aiModelUpdateMsg, e);
throw e;
}
return Pair.of(isCreated, isNameUpdated);
}
protected void deleteAiModel(TenantId tenantId, Edge edge, AiModelId aiModelId) {
Optional<AiModel> aiModel = edgeCtx.getAiModelService().findAiModelById(tenantId, aiModelId);
if (aiModel.isPresent()) {
edgeCtx.getAiModelService().deleteByTenantIdAndId(tenantId, aiModelId);
pushEntityEventToRuleEngine(tenantId, edge, aiModel.get(), TbMsgType.ENTITY_DELETED);
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\ai\BaseAiModelProcessor.java | 2 |
请完成以下Spring Boot application配置 | spring.application.name=logback-extension
logging.config=./src/main/resources/logback-spring.xml
spring.profiles.active=logbook
server.port=8083
# Enable Logbook
logbook.filter.enabled=true
# Log incoming requests and responses
logbook.format.style=http
# Include request and response | bodies
logbook.include.body=true
# this is needed to display http requests
logging.level.org.zalando.logbook.Logbook=TRACE | repos\tutorials-master\spring-boot-modules\spring-boot-logging-logback\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void validate(I_AD_Role_Included roleIncluded)
{
if (roleIncluded.getAD_Role_ID() == roleIncluded.getIncluded_Role_ID())
{
throw new AdempiereException("@AD_Role_ID@ == @Included_Role_ID@");
}
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = I_AD_Role_Included.COLUMNNAME_Included_Role_ID)
public void assertNoLoops(final I_AD_Role_Included roleIncluded)
{
final RoleId includedRoleId = RoleId.ofRepoIdOrNull(roleIncluded.getIncluded_Role_ID());
final List<RoleId> trace = new ArrayList<>();
if (hasLoop(includedRoleId, trace))
{
final IRoleDAO roleDAO = Services.get(IRoleDAO.class);
final StringBuilder roles = new StringBuilder();
for (final RoleId roleId : trace)
{
if (roles.length() > 0)
roles.append(" - ");
roles.append(roleDAO.getRoleName(roleId));
}
throw new AdempiereException("Loop has detected: " + roles);
}
}
/**
* @return true if loop detected. If you specified not null trace, you will have in that list the IDs from the loop
*/
// TODO: use recursive WITH sql clause
private static boolean hasLoop(final RoleId roleId, final List<RoleId> trace)
{
final List<RoleId> trace2;
if (trace == null)
{
trace2 = new ArrayList<>();
}
else
{
trace2 = new ArrayList<>(trace);
}
trace2.add(roleId);
//
final String sql = "SELECT "
+ I_AD_Role_Included.COLUMNNAME_Included_Role_ID
+ "," + I_AD_Role_Included.COLUMNNAME_AD_Role_ID
+ " FROM " + I_AD_Role_Included.Table_Name
+ " WHERE " + I_AD_Role_Included.COLUMNNAME_AD_Role_ID + "=?";
PreparedStatement pstmt = null;
ResultSet rs = null; | try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, roleId);
rs = pstmt.executeQuery();
while (rs.next())
{
final RoleId childId = RoleId.ofRepoId(rs.getInt(1));
if (trace2.contains(childId))
{
trace.clear();
trace.addAll(trace2);
trace.add(childId);
return true;
}
if (hasLoop(childId, trace2))
{
trace.clear();
trace.addAll(trace2);
return true;
}
}
}
catch (SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
//
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Role_Included.java | 1 |
请完成以下Java代码 | public T getRule() {
return rule;
}
public AbstractRuleEntity<T> setRule(T rule) {
this.rule = rule;
return this;
}
@Override
public Date getGmtCreate() {
return gmtCreate;
}
public AbstractRuleEntity<T> setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
return this;
} | public Date getGmtModified() {
return gmtModified;
}
public AbstractRuleEntity<T> setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
return this;
}
@Override
public T toRule() {
return rule;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\rule\AbstractRuleEntity.java | 1 |
请完成以下Java代码 | public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent == null ? null : continent.trim();
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region == null ? null : region.trim();
}
public Float getSurfacearea() {
return surfacearea;
}
public void setSurfacearea(Float surfacearea) {
this.surfacearea = surfacearea;
}
public Short getIndepyear() {
return indepyear;
}
public void setIndepyear(Short indepyear) {
this.indepyear = indepyear;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public Float getLifeexpectancy() {
return lifeexpectancy;
}
public void setLifeexpectancy(Float lifeexpectancy) {
this.lifeexpectancy = lifeexpectancy;
} | public Float getGnp() {
return gnp;
}
public void setGnp(Float gnp) {
this.gnp = gnp;
}
public Float getGnpold() {
return gnpold;
}
public void setGnpold(Float gnpold) {
this.gnpold = gnpold;
}
public String getLocalname() {
return localname;
}
public void setLocalname(String localname) {
this.localname = localname == null ? null : localname.trim();
}
public String getGovernmentform() {
return governmentform;
}
public void setGovernmentform(String governmentform) {
this.governmentform = governmentform == null ? null : governmentform.trim();
}
public String getHeadofstate() {
return headofstate;
}
public void setHeadofstate(String headofstate) {
this.headofstate = headofstate == null ? null : headofstate.trim();
}
public Integer getCapital() {
return capital;
}
public void setCapital(Integer capital) {
this.capital = capital;
}
public String getCode2() {
return code2;
}
public void setCode2(String code2) {
this.code2 = code2 == null ? null : code2.trim();
}
} | repos\spring-boot-quick-master\quick-modules\dao\src\main\java\com\modules\entity\Country.java | 1 |
请完成以下Java代码 | public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]"; | }
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\OnCommittedResponseWrapper.java | 1 |
请完成以下Java代码 | public Optional<Author> getAuthor() {
return Optional.ofNullable(author);
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Book)) {
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\HibernateSpringBootOptional\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | public class WebSocketClientUsage {
void create() {
// tag::create[]
String url = "wss://spring.io/graphql";
WebSocketClient client = new ReactorNettyWebSocketClient();
WebSocketGraphQlClient graphQlClient = WebSocketGraphQlClient.builder(url, client).build();
// end::create[]
}
void mutate() {
// tag::mutate[]
String url = "wss://spring.io/graphql";
WebSocketClient client = new ReactorNettyWebSocketClient();
WebSocketGraphQlClient graphQlClient = WebSocketGraphQlClient.builder(url, client)
.headers((headers) -> headers.setBasicAuth("joe", "..."))
.build();
// Use graphQlClient... | WebSocketGraphQlClient anotherGraphQlClient = graphQlClient.mutate()
.headers((headers) -> headers.setBasicAuth("peter", "..."))
.build();
// Use anotherGraphQlClient...
// end::mutate[]
}
void keepAlive() {
// tag::keepAlive[]
String url = "wss://spring.io/graphql";
WebSocketClient client = new ReactorNettyWebSocketClient();
WebSocketGraphQlClient graphQlClient = WebSocketGraphQlClient.builder(url, client)
.keepAlive(Duration.ofSeconds(30))
.build();
// end::keepAlive[]
}
} | repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\client\websocketgraphqlclient\WebSocketClientUsage.java | 1 |
请完成以下Java代码 | public void configureClientInboundChannel(final ChannelRegistration registration)
{
registration.interceptors(new LoggingChannelInterceptor());
// NOTE: atm we don't care if the inbound messages arrived in the right order
// When and If we would care we would restrict the taskExecutor()'s corePoolSize to ONE.
// see: configureClientOutboundChannel().
}
@Override
public boolean configureMessageConverters(final List<MessageConverter> messageConverters)
{
messageConverters.add(new MappingJackson2MessageConverter());
return true;
}
private static class LoggingChannelInterceptor implements ChannelInterceptor
{
private static final Logger logger = LogManager.getLogger(LoggingChannelInterceptor.class);
@Override
public void afterSendCompletion(final @NonNull Message<?> message, final @NonNull MessageChannel channel, final boolean sent, final Exception ex)
{
if (!sent)
{
logger.warn("Failed sending: message={}, channel={}, sent={}", message, channel, sent, ex);
}
}
@Override
public void afterReceiveCompletion(final Message<?> message, final @NonNull MessageChannel channel, final Exception ex)
{
if (ex != null)
{
logger.warn("Failed receiving: message={}, channel={}", message, channel, ex);
} | }
}
private static class AuthorizationHandshakeInterceptor implements HandshakeInterceptor
{
private static final Logger logger = LogManager.getLogger(AuthorizationHandshakeInterceptor.class);
@Override
public boolean beforeHandshake(@NonNull final ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final @NonNull Map<String, Object> attributes)
{
final UserSession userSession = UserSession.getCurrentOrNull();
if (userSession == null)
{
logger.warn("Websocket connection not allowed (missing userSession)");
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
if (!userSession.isLoggedIn())
{
logger.warn("Websocket connection not allowed (not logged in) - userSession={}", userSession);
response.setStatusCode(HttpStatus.UNAUTHORIZED);
return false;
}
return true;
}
@Override
public void afterHandshake(final @NonNull ServerHttpRequest request, final @NonNull ServerHttpResponse response, final @NonNull WebSocketHandler wsHandler, final Exception exception)
{
// nothing
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\websocket\WebsocketConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getUserState() {
return userState;
}
public void setUserState(Integer userState) {
this.userState = userState;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRegisterTimeStart() {
return registerTimeStart;
}
public void setRegisterTimeStart(String registerTimeStart) {
this.registerTimeStart = registerTimeStart;
}
public String getRegisterTimeEnd() {
return registerTimeEnd;
}
public void setRegisterTimeEnd(String registerTimeEnd) {
this.registerTimeEnd = registerTimeEnd;
}
public Integer getOrderByRegisterTime() {
return orderByRegisterTime;
} | public void setOrderByRegisterTime(Integer orderByRegisterTime) {
this.orderByRegisterTime = orderByRegisterTime;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserQueryReq{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", registerTimeStart='" + registerTimeStart + '\'' +
", registerTimeEnd='" + registerTimeEnd + '\'' +
", userType=" + userType +
", userState=" + userState +
", roleId='" + roleId + '\'' +
", orderByRegisterTime=" + orderByRegisterTime +
", page=" + page +
", numPerPage=" + numPerPage +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\UserQueryReq.java | 2 |
请完成以下Java代码 | public void prepare() {
char common = 'a';
elements = new char[s];
for (int i = 0; i < s - 1; i++) {
elements[i] = common;
}
elements[s - 1] = pivot;
}
@TearDown
@Override
public void clean() {
elements = null;
}
@Benchmark
@BenchmarkMode(Mode.AverageTime) | public int findPosition() {
int index = 0;
while (pivot != elements[index]) {
index++;
}
return index;
}
@Override
public String getSimpleClassName() {
return CharPrimitiveLookup.class.getSimpleName();
}
} | repos\tutorials-master\core-java-modules\core-java-lang-2\src\main\java\com\baeldung\primitive\CharPrimitiveLookup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SumUpTransaction updateById(@NonNull final SumUpTransactionExternalId id, @NonNull final UnaryOperator<SumUpTransaction> updater)
{
final I_SUMUP_Transaction record = retrieveSingleRecordNotNull(SumUpTransactionQuery.ofExternalId(id));
return updateRecord(record, updater);
}
private SumUpTransaction updateRecord(@NonNull final I_SUMUP_Transaction record, @NonNull final UnaryOperator<SumUpTransaction> updater)
{
final SumUpTransaction trxBeforeChange = fromRecord(record);
final SumUpTransaction trx = updater.apply(trxBeforeChange);
if (Objects.equals(trxBeforeChange, trx))
{
return trxBeforeChange;
}
updateRecordAndSave(record, trx);
return trx;
}
public BulkUpdateByQueryResult bulkUpdateByQuery(
@NonNull final SumUpTransactionQuery query,
boolean isForceSendingChangeEvents,
@NonNull final UnaryOperator<SumUpTransaction> updater)
{
trxManager.assertThreadInheritedTrxNotExists();
final AtomicInteger countOK = new AtomicInteger(0);
final AtomicInteger countError = new AtomicInteger(0);
try (IAutoCloseable ignored = SumUpEventsDispatcher.temporaryForceSendingChangeEventsIf(isForceSendingChangeEvents))
{
toSqlQuery(query)
.clearOrderBys()
.orderBy(I_SUMUP_Transaction.COLUMNNAME_SUMUP_Transaction_ID)
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
.iterateAndStream()
.forEach(record -> {
try | {
trxManager.runInThreadInheritedTrx(() -> updateRecord(record, updater));
countOK.incrementAndGet();
}
catch (final Exception ex)
{
countError.incrementAndGet();
logger.warn("Failed updating transaction {}", record.getSUMUP_ClientTransactionId(), ex);
}
});
return BulkUpdateByQueryResult.builder()
.countOK(countOK.get())
.countError(countError.get())
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\repository\SumUpTransactionRepository.java | 2 |
请完成以下Java代码 | public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeList.add(new Employee(i, "John"));
}
employeeList.add(employee);
employeeIndex = employeeList.indexOf(employee);
}
}
@Benchmark
public void testAdd(MyState state) {
state.employeeList.add(new Employee(state.iterations + 1, "John"));
}
@Benchmark
public void testAddAt(MyState state) {
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
}
@Benchmark
public boolean testContains(MyState state) {
return state.employeeList.contains(state.employee);
}
@Benchmark
public int testIndexOf(MyState state) {
return state.employeeList.indexOf(state.employee);
}
@Benchmark
public Employee testGet(MyState state) { | return state.employeeList.get(state.employeeIndex);
}
@Benchmark
public boolean testRemove(MyState state) {
return state.employeeList.remove(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\performance\CopyOnWriteBenchmark.java | 1 |
请完成以下Java代码 | private boolean hasStringFieldChanged(Function<TaskInfo, String> comparableTaskGetter) {
if (originalTask != null && updatedTask != null) {
return !StringUtils.equals(
comparableTaskGetter.apply(originalTask),
comparableTaskGetter.apply(updatedTask)
);
}
return false;
}
private boolean hasIntegerFieldChanged(Function<TaskInfo, Integer> comparableTaskGetter) {
if (originalTask != null && updatedTask != null) {
return !Objects.equals(comparableTaskGetter.apply(originalTask), comparableTaskGetter.apply(updatedTask));
}
return false;
}
private boolean hasDateFieldChanged(Function<TaskInfo, Date> comparableTaskGetter) {
if (originalTask != null && updatedTask != null) {
Date originalDate = comparableTaskGetter.apply(originalTask);
Date newDate = comparableTaskGetter.apply(updatedTask);
return (
(originalDate == null && newDate != null) ||
(originalDate != null && newDate == null) ||
(originalDate != null && !originalDate.equals(newDate))
);
}
return false;
} | private TaskInfo copyInformationFromTaskInfo(TaskInfo task) {
if (task != null) {
TaskEntityImpl duplicatedTask = new TaskEntityImpl();
duplicatedTask.setName(task.getName());
duplicatedTask.setDueDate(task.getDueDate());
duplicatedTask.setDescription(task.getDescription());
duplicatedTask.setId(task.getId());
duplicatedTask.setOwner(task.getOwner());
duplicatedTask.setPriority(task.getPriority());
duplicatedTask.setCategory(task.getCategory());
duplicatedTask.setFormKey(task.getFormKey());
duplicatedTask.setAssignee(task.getAssignee());
duplicatedTask.setTaskDefinitionKey(task.getTaskDefinitionKey());
duplicatedTask.setParentTaskId(task.getParentTaskId());
return duplicatedTask;
}
throw new IllegalArgumentException("task must be non-null");
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\task\TaskComparatorImpl.java | 1 |
请完成以下Java代码 | private void processReceiptSchedule0(final I_M_ReceiptSchedule receiptSchedule)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
if (isReceiptScheduleCanBeClosed(receiptSchedule))
{
receiptScheduleBL.close(receiptSchedule);
loggable.addLog("M_ReceiptSchedule_ID={} - just closing without creating a receipt, because QtyOrdered={} and QtyMoved={}",
receiptSchedule.getM_ReceiptSchedule_ID(), receiptSchedule.getQtyOrdered(), receiptSchedule.getQtyMoved());
return;
}
if (!isCreateMovement)
{
receiptSchedule.setM_Warehouse_Dest_ID(0);
save(receiptSchedule);
}
// create HUs
final de.metas.handlingunits.model.I_M_ReceiptSchedule huReceiptSchedule = create(receiptSchedule, de.metas.handlingunits.model.I_M_ReceiptSchedule.class);
huReceiptScheduleBL.generateHUsIfNeeded(huReceiptSchedule, getCtx());
final CreateReceiptsParameters parameters = CreateReceiptsParameters.builder()
.ctx(getCtx())
.selectedHuIds(null) // null means to assign all planned HUs which are assigned to the receipt schedule's
.movementDateRule(ReceiptMovementDateRule.ORDER_DATE_PROMISED) // when creating M_InOuts, use the respective C_Orders' DatePromised values
.commitEachReceiptIndividually(true) | .destinationLocatorIdOrNull(null) // use receipt schedules' destination-warehouse settings
.receiptSchedules(ImmutableList.of(receiptSchedule))
.printReceiptLabels(false)
// we are already in a inside a trxItemProcessorExecutor, and processReceiptSchedules will fire up another one, but with just one item
// we don't want that internal processor to run with its own trx, because then we will at one point have trouble with 2 different trx-Names
.commitEachReceiptIndividually(false)
.build();
final InOutGenerateResult result = huReceiptScheduleBL.processReceiptSchedules(parameters);
loggable.addLog("M_ReceiptSchedule_ID={} - created a receipt; result={}", receiptSchedule.getM_ReceiptSchedule_ID(), result);
refresh(receiptSchedule);
final boolean rsCanBeClosedNow = isReceiptScheduleCanBeClosed(receiptSchedule);
if (rsCanBeClosedNow)
{
receiptScheduleBL.close(receiptSchedule);
}
}
private boolean isReceiptScheduleCanBeClosed(final I_M_ReceiptSchedule receiptSchedule)
{
final boolean rsCanBeClosedNow = receiptSchedule.getQtyOrdered().signum() > 0 && receiptSchedule.getQtyMoved().compareTo(receiptSchedule.getQtyOrdered()) >= 0;
return rsCanBeClosedNow;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\process\M_ReceiptSchedule_Generate_M_InOuts.java | 1 |
请完成以下Java代码 | protected void writeJobExecutorContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException {
ModelNode node = context.getModelNode();
ModelNode jobExecutorNode = node.get(Element.JOB_EXECUTOR.getLocalName());
if (jobExecutorNode.isDefined()) {
writer.writeStartElement(Element.JOB_EXECUTOR.getLocalName());
for (Property property : jobExecutorNode.asPropertyList()) {
ModelNode propertyValue = property.getValue();
for (AttributeDefinition jobExecutorAttribute : SubsystemAttributeDefinitons.JOB_EXECUTOR_ATTRIBUTES) {
if (jobExecutorAttribute.equals(SubsystemAttributeDefinitons.NAME)) {
((SimpleAttributeDefinition) jobExecutorAttribute).marshallAsAttribute(propertyValue, writer);
} else {
jobExecutorAttribute.marshallAsElement(propertyValue, writer);
}
}
writeJobAcquisitionsContent(writer, context, propertyValue);
}
// end job-executor
writer.writeEndElement();
}
}
protected void writeJobAcquisitionsContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context, ModelNode parentNode) throws XMLStreamException {
writer.writeStartElement(Element.JOB_AQUISITIONS.getLocalName());
ModelNode jobAcquisitionConfigurations = parentNode.get(Element.JOB_AQUISITIONS.getLocalName());
if (jobAcquisitionConfigurations.isDefined()) {
for (Property property : jobAcquisitionConfigurations.asPropertyList()) {
// write each child element to xml | writer.writeStartElement(Element.JOB_AQUISITION.getLocalName());
for (AttributeDefinition jobAcquisitionAttribute : SubsystemAttributeDefinitons.JOB_ACQUISITION_ATTRIBUTES) {
if (jobAcquisitionAttribute.equals(SubsystemAttributeDefinitons.NAME)) {
((SimpleAttributeDefinition) jobAcquisitionAttribute).marshallAsAttribute(property.getValue(), writer);
} else {
jobAcquisitionAttribute.marshallAsElement(property.getValue(), writer);
}
}
writer.writeEndElement();
}
}
// end job-acquisitions
writer.writeEndElement();
}
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\BpmPlatformParser1_1.java | 1 |
请完成以下Java代码 | public void addAuthor(Author author) {
authors.add(author);
}
// standard getters and setters
public Book() {
}
public Book(String title) {
this.title = title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\transientobject\entity\Book.java | 1 |
请完成以下Java代码 | public static JsonElement parse(Object value) {
if (value instanceof Integer) {
return new JsonPrimitive((Integer) value);
} else if (value instanceof Long) {
return new JsonPrimitive((Long) value);
} else if (value instanceof String) {
try {
return JsonParser.parseString((String) value);
} catch (Exception e) {
if (isBase64(value.toString())) {
value = "\"" + value + "\"";
}
return JsonParser.parseString((String) value);
}
} else if (value instanceof Boolean) {
return new JsonPrimitive((Boolean) value);
} else if (value instanceof Double) {
return new JsonPrimitive((Double) value);
} else if (value instanceof Float) {
return new JsonPrimitive((Float) value);
} else {
throw new IllegalArgumentException("Unsupported type: " + value.getClass().getSimpleName()); | }
}
public static JsonObject convertToJsonObject(Map<String, ?> map) {
JsonObject jsonObject = new JsonObject();
for (Map.Entry<String, ?> entry : map.entrySet()) {
jsonObject.add(entry.getKey(), parse(entry.getValue()));
}
return jsonObject;
}
public static boolean isBase64(String value) {
return value.length() % 4 == 0 && BASE64_PATTERN.matcher(value).matches();
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\util\JsonUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void method03() {
// 查询订单
self().method031();
// 查询用户
self().method032();
}
@Transactional // 报错,因为此时获取的是 primary 对应的 DataSource ,即 users 。
public void method031() {
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
}
@Transactional
public void method032() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
public void method04() {
// 查询订单
self().method041();
// 查询用户
self().method042();
}
@Transactional
@DS(DBConstants.DATASOURCE_ORDERS)
public void method041() {
OrderDO order = orderMapper.selectById(1);
System.out.println(order); | }
@Transactional
@DS(DBConstants.DATASOURCE_USERS)
public void method042() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
@Transactional
@DS(DBConstants.DATASOURCE_ORDERS)
public void method05() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
self().method052();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
@DS(DBConstants.DATASOURCE_USERS)
public void method052() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
} | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-baomidou-01\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\service\OrderService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CustomModelProcessor implements ModelProcessor {
private static final String XML_POM = "pom.xml";
private static final String JSON_POM = "pom.json";
private static final String JSON_EXT = ".json";
ObjectMapper objectMapper = new ObjectMapper();
@Requirement
private ModelReader modelReader;
@Override
public File locatePom(File projectDirectory) {
File pomFile = new File(projectDirectory, JSON_POM);
if (!pomFile.exists()) {
pomFile = new File(projectDirectory, XML_POM);
}
return pomFile;
}
@Override
public Model read(InputStream input, Map<String, ?> options) throws IOException, ModelParseException {
try (final Reader in = ReaderFactory.newPlatformReader(input)) { | return read(in, options);
}
}
@Override
public Model read(Reader reader, Map<String, ?> options) throws IOException, ModelParseException {
FileModelSource source = (options != null) ? (FileModelSource) options.get(SOURCE) : null;
if (source != null && source.getLocation().endsWith(JSON_EXT)) {
Model model = objectMapper.readValue(reader, Model.class);
return model;
}
//It's a normal maven project with a pom.xml file
return modelReader.read(reader, options);
}
@Override
public Model read(File input, Map<String, ?> options) throws IOException, ModelParseException {
return null;
}
} | repos\tutorials-master\maven-modules\maven-polyglot\maven-polyglot-json-extension\src\main\java\com\demo\polyglot\CustomModelProcessor.java | 2 |
请完成以下Java代码 | public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} | public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", age=" + age
+ ", name=" + name + ", genre=" + genre + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootRecordAndEmbeddables\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public class ProcessVariableMap implements Map<String, Object> {
@Inject
private BusinessProcess businessProcess;
@Override
public Object get(Object key) {
if (key == null) {
throw new IllegalArgumentException("This map does not support 'null' keys.");
}
return businessProcess.getVariable(key.toString());
}
@Override
public Object put(String key, Object value) {
if (key == null) {
throw new IllegalArgumentException("This map does not support 'null' keys.");
}
Object variableBefore = businessProcess.getVariable(key);
businessProcess.setVariable(key, value);
return variableBefore;
}
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
for (Map.Entry<? extends String, ? extends Object> newEntry : m.entrySet()) {
businessProcess.setVariable(newEntry.getKey(), newEntry.getValue());
}
}
@Override
public int size() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".size() is not supported.");
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".isEmpty() is not supported.");
}
@Override
public boolean containsKey(Object key) {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsKey() is not supported.");
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsValue() is not supported.");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException("ProcessVariableMap.remove is unsupported. Use ProcessVariableMap.put(key, null)"); | }
@Override
public void clear() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".clear() is not supported.");
}
@Override
public Set<String> keySet() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".keySet() is not supported.");
}
@Override
public Collection<Object> values() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".values() is not supported.");
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".entrySet() is not supported.");
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\ProcessVariableMap.java | 1 |
请完成以下Java代码 | public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunning(runnable);
} else {
return executeShortRunning(runnable);
}
}
protected boolean scheduleLongRunning(Runnable runnable) {
try {
workManager.scheduleWork(new JcaWorkRunnableAdapter(runnable));
return true;
} catch (WorkException e) {
logger.log(Level.WARNING, "Could not schedule : "+e.getMessage(), e);
return false;
}
}
protected boolean executeShortRunning(Runnable runnable) {
try {
workManager.startWork(new JcaWorkRunnableAdapter(runnable), START_WORK_TIMEOUT, null, null);
return true;
} catch (WorkRejectedException e) {
logger.log(Level.FINE, "WorkRejectedException while scheduling jobs for execution", e);
} catch (WorkException e) {
logger.log(Level.WARNING, "WorkException while scheduling jobs for execution", e);
}
return false;
} | public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new JcaInflowExecuteJobsRunnable(jobIds, processEngine, ra);
}
// javax.resource.Referenceable /////////////////////////
protected Reference reference;
public Reference getReference() throws NamingException {
return reference;
}
public void setReference(Reference reference) {
this.reference = reference;
}
// getters / setters ////////////////////////////////////
public WorkManager getWorkManager() {
return workManager;
}
public JcaExecutorServiceConnector getPlatformJobExecutorConnector() {
return ra;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaWorkManagerExecutorService.java | 1 |
请完成以下Java代码 | public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} | public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
} | repos\SpringBootBucket-master\springboot-resttemplate\src\main\java\com\xncoding\pos\model\LoginParam.java | 1 |
请完成以下Java代码 | public List<Task> getSubTasks(String parentTaskId) {
return commandExecutor.execute(new GetSubTasksCmd(parentTaskId));
}
public TaskReport createTaskReport() {
return new TaskReportImpl(commandExecutor);
}
@Override
public void handleBpmnError(String taskId, String errorCode) {
commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode));
}
@Override
public void handleBpmnError(String taskId, String errorCode, String errorMessage) {
commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage));
} | @Override
public void handleBpmnError(String taskId, String errorCode, String errorMessage, Map<String, Object> variables) {
commandExecutor.execute(new HandleTaskBpmnErrorCmd(taskId, errorCode, errorMessage, variables));
}
@Override
public void handleEscalation(String taskId, String escalationCode) {
commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode));
}
@Override
public void handleEscalation(String taskId, String escalationCode, Map<String, Object> variables) {
commandExecutor.execute(new HandleTaskEscalationCmd(taskId, escalationCode, variables));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\TaskServiceImpl.java | 1 |
请完成以下Java代码 | public final void setAsciiStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setAsciiStream(parameterIndex, x, length);
}
@Override
public final void setBinaryStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x, length);
}
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader, final long length) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader, length);
}
@Override
public final void setAsciiStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setAsciiStream(parameterIndex, x);
}
@Override
public final void setBinaryStream(final int parameterIndex, final InputStream x) throws SQLException
{
logMigrationScript_SetParam(parameterIndex, x);
getStatementImpl().setBinaryStream(parameterIndex, x);
}
@Override
public final void setCharacterStream(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setCharacterStream(parameterIndex, reader);
}
@Override
public final void setNCharacterStream(final int parameterIndex, final Reader value) throws SQLException | {
logMigrationScript_SetParam(parameterIndex, value);
getStatementImpl().setNCharacterStream(parameterIndex, value);
}
@Override
public final void setClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setClob(parameterIndex, reader);
}
@Override
public final void setBlob(final int parameterIndex, final InputStream inputStream) throws SQLException
{
//logMigrationScript_SetParam(parameterIndex, inputStream);
getStatementImpl().setBlob(parameterIndex, inputStream);
}
@Override
public final void setNClob(final int parameterIndex, final Reader reader) throws SQLException
{
// logMigrationScript_SetParam(parameterIndex, reader);
getStatementImpl().setNClob(parameterIndex, reader);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\CPreparedStatementProxy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Product {
@Id
@GeneratedValue
private int id;
private String name;
private double price;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "store_id")
private Store store;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public Product() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
} | public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Store getStore() {
return store;
}
public void setStore(Store store) {
this.store = store;
}
public void setNamePrefix(String prefix) {
this.name = prefix + this.name;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\domain\Product.java | 2 |
请完成以下Java代码 | public void setM_ShipperTransportation_ID (final int M_ShipperTransportation_ID)
{
if (M_ShipperTransportation_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShipperTransportation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShipperTransportation_ID, M_ShipperTransportation_ID);
}
@Override
public int getM_ShipperTransportation_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShipperTransportation_ID);
}
@Override
public void setM_ShippingPackage_ID (final int M_ShippingPackage_ID)
{
if (M_ShippingPackage_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ShippingPackage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ShippingPackage_ID, M_ShippingPackage_ID);
}
@Override
public int getM_ShippingPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ShippingPackage_ID);
}
@Override
public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
@Override
public void setPackageNetTotal (final BigDecimal PackageNetTotal)
{
set_Value (COLUMNNAME_PackageNetTotal, PackageNetTotal);
}
@Override
public BigDecimal getPackageNetTotal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageNetTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPackageWeight (final @Nullable BigDecimal PackageWeight)
{
set_Value (COLUMNNAME_PackageWeight, PackageWeight);
}
@Override
public BigDecimal getPackageWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed); | }
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
throw new IllegalArgumentException ("ProductName is virtual column"); }
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
throw new IllegalArgumentException ("ProductValue is virtual column"); }
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShippingPackage.java | 1 |
请完成以下Java代码 | public static HistoricDetailEntityManager getHistoricDetailEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getHistoricDetailEntityManager();
}
public static AttachmentEntityManager getAttachmentEntityManager() {
return getAttachmentEntityManager(getCommandContext());
}
public static AttachmentEntityManager getAttachmentEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getAttachmentEntityManager();
}
public static EventLogEntryEntityManager getEventLogEntryEntityManager() {
return getEventLogEntryEntityManager(getCommandContext());
}
public static EventLogEntryEntityManager getEventLogEntryEntityManager(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getEventLogEntryEntityManager();
}
public static FlowableEventDispatcher getEventDispatcher() {
return getEventDispatcher(getCommandContext());
}
public static FlowableEventDispatcher getEventDispatcher(CommandContext commandContext) { | return getProcessEngineConfiguration(commandContext).getEventDispatcher();
}
public static FailedJobCommandFactory getFailedJobCommandFactory() {
return getFailedJobCommandFactory(getCommandContext());
}
public static FailedJobCommandFactory getFailedJobCommandFactory(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getFailedJobCommandFactory();
}
public static ProcessInstanceHelper getProcessInstanceHelper() {
return getProcessInstanceHelper(getCommandContext());
}
public static ProcessInstanceHelper getProcessInstanceHelper(CommandContext commandContext) {
return getProcessEngineConfiguration(commandContext).getProcessInstanceHelper();
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CommandContextUtil.java | 1 |
请完成以下Java代码 | public void setM_QualityInsp_LagerKonf_Version_ID (int M_QualityInsp_LagerKonf_Version_ID)
{
if (M_QualityInsp_LagerKonf_Version_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID, Integer.valueOf(M_QualityInsp_LagerKonf_Version_ID));
}
/** Get Lagerkonferenz-Version.
@return Lagerkonferenz-Version */
@Override
public int getM_QualityInsp_LagerKonf_Version_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_QualityInsp_LagerKonf_Version_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausgleichsbetrag.
@param QualityAdj_Amt_Per_UOM Ausgleichsbetrag */
@Override
public void setQualityAdj_Amt_Per_UOM (java.math.BigDecimal QualityAdj_Amt_Per_UOM)
{
set_Value (COLUMNNAME_QualityAdj_Amt_Per_UOM, QualityAdj_Amt_Per_UOM);
}
/** Get Ausgleichsbetrag.
@return Ausgleichsbetrag */
@Override
public java.math.BigDecimal getQualityAdj_Amt_Per_UOM ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QualityAdj_Amt_Per_UOM);
if (bd == null)
return Env.ZERO;
return bd;
}
/**
* QualityAdjustmentMonth AD_Reference_ID=540507
* Reference name: QualityAdjustmentMonth
*/
public static final int QUALITYADJUSTMENTMONTH_AD_Reference_ID=540507;
/** Jan = Jan */
public static final String QUALITYADJUSTMENTMONTH_Jan = "Jan";
/** Feb = Feb */ | public static final String QUALITYADJUSTMENTMONTH_Feb = "Feb";
/** Mar = Mar */
public static final String QUALITYADJUSTMENTMONTH_Mar = "Mar";
/** Apr = Apr */
public static final String QUALITYADJUSTMENTMONTH_Apr = "Apr";
/** May = May */
public static final String QUALITYADJUSTMENTMONTH_May = "May";
/** Jun = Jun */
public static final String QUALITYADJUSTMENTMONTH_Jun = "Jun";
/** Jul = Jul */
public static final String QUALITYADJUSTMENTMONTH_Jul = "Jul";
/** Aug = Aug */
public static final String QUALITYADJUSTMENTMONTH_Aug = "Aug";
/** Sep = Sep */
public static final String QUALITYADJUSTMENTMONTH_Sep = "Sep";
/** Oct = Oct */
public static final String QUALITYADJUSTMENTMONTH_Oct = "Oct";
/** Nov = Nov */
public static final String QUALITYADJUSTMENTMONTH_Nov = "Nov";
/** Dec = Dec */
public static final String QUALITYADJUSTMENTMONTH_Dec = "Dec";
/** Set Monat.
@param QualityAdjustmentMonth Monat */
@Override
public void setQualityAdjustmentMonth (java.lang.String QualityAdjustmentMonth)
{
set_Value (COLUMNNAME_QualityAdjustmentMonth, QualityAdjustmentMonth);
}
/** Get Monat.
@return Monat */
@Override
public java.lang.String getQualityAdjustmentMonth ()
{
return (java.lang.String)get_Value(COLUMNNAME_QualityAdjustmentMonth);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_QualityInsp_LagerKonf_Month_Adj.java | 1 |
请完成以下Java代码 | public Builder setPayAmt(final BigDecimal payAmt)
{
this.payAmt = payAmt;
return this;
}
public Builder setPayAmtConv(final BigDecimal payAmtConv)
{
this.payAmtConv = payAmtConv;
return this;
}
public Builder setC_BPartner_ID(final int C_BPartner_ID)
{
this.C_BPartner_ID = C_BPartner_ID;
return this;
} | public Builder setOpenAmtConv(final BigDecimal openAmtConv)
{
this.openAmtConv = openAmtConv;
return this;
}
public Builder setMultiplierAP(final BigDecimal multiplierAP)
{
this.multiplierAP = multiplierAP;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentRow.java | 1 |
请完成以下Java代码 | public static IEnqueueResult scheduleIfNotPostponed(@NonNull final Object model)
{
final AsyncBatchId asyncBatchId = asyncBatchBL
.getAsyncBatchId(model)
.orElse(null);
final boolean scheduled = _scheduleIfNotPostponed(InterfaceWrapperHelper.getContextAware(model), asyncBatchId);
final int workpackageCount = scheduled ? 1 : 0;
return () -> workpackageCount;
}
/**
* Schedules a new "create missing shipment schedules" run, <b>unless</b> the processor is disabled or all scheds would be created later.<br>
* See {@link IShipmentScheduleBL#allMissingSchedsWillBeCreatedLater()}.
*
* @param ctxAware if it has a not-null trxName, then the workpackage will be marked as ready for processing when the given transaction is committed.
*/
private static boolean _scheduleIfNotPostponed(final IContextAware ctxAware, @Nullable final AsyncBatchId asyncBatchId)
{
if (shipmentScheduleBL.allMissingSchedsWillBeCreatedLater())
{
logger.debug("Not scheduling WP because IShipmentScheduleBL.allMissingSchedsWillBeCreatedLater() returned true: {}", CreateMissingShipmentSchedulesWorkpackageProcessor.class.getSimpleName());
return false;
}
// don't try to enqueue it if is not active
if (!queueDAO.isWorkpackageProcessorEnabled(CreateMissingShipmentSchedulesWorkpackageProcessor.class))
{
logger.debug("Not scheduling WP because this workpackage processor is disabled: {}", CreateMissingShipmentSchedulesWorkpackageProcessor.class.getSimpleName());
return false;
}
final Properties ctx = ctxAware.getCtx(); | workPackageQueueFactory.getQueueForEnqueuing(ctx, CreateMissingShipmentSchedulesWorkpackageProcessor.class)
.newWorkPackage()
.setAsyncBatchId(asyncBatchId)
.bindToTrxName(ctxAware.getTrxName())
.buildAndEnqueue();
return true;
}
// services
private final transient IShipmentScheduleHandlerBL inOutCandHandlerBL = Services.get(IShipmentScheduleHandlerBL.class);
@Override
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName_NOTUSED)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(workpackage);
final Set<ShipmentScheduleId> shipmentScheduleIds = inOutCandHandlerBL.createMissingCandidates(ctx);
// After shipment schedules where created, invalidate them because we want to make sure they are up2date.
final IShipmentScheduleInvalidateBL invalidSchedulesService = Services.get(IShipmentScheduleInvalidateBL.class);
final IShipmentSchedulePA shipmentScheduleDAO = Services.get(IShipmentSchedulePA.class);
final Collection<I_M_ShipmentSchedule> scheduleRecords = shipmentScheduleDAO.getByIds(shipmentScheduleIds).values();
for (final I_M_ShipmentSchedule scheduleRecord : scheduleRecords)
{
invalidSchedulesService.notifySegmentChangedForShipmentScheduleInclSched(scheduleRecord);
}
Loggables.addLog("Created " + shipmentScheduleIds.size() + " candidates");
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\async\CreateMissingShipmentSchedulesWorkpackageProcessor.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class);
}
@Override
public void setC_BPartner(org.compiere.model.I_C_BPartner C_BPartner)
{
set_ValueFromPO(COLUMNNAME_C_BPartner_ID, org.compiere.model.I_C_BPartner.class, C_BPartner);
}
/** Set Geschäftspartner.
@param C_BPartner_ID
Bezeichnet einen Geschäftspartner
*/
@Override
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Letzter Wareneingang.
@param LastReceiptDate Letzter Wareneingang */
@Override
public void setLastReceiptDate (java.sql.Timestamp LastReceiptDate)
{
set_ValueNoCheck (COLUMNNAME_LastReceiptDate, LastReceiptDate);
}
/** Get Letzter Wareneingang.
@return Letzter Wareneingang */
@Override
public java.sql.Timestamp getLastReceiptDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastReceiptDate);
} | /** Set Letzte Lieferung.
@param LastShipDate Letzte Lieferung */
@Override
public void setLastShipDate (java.sql.Timestamp LastShipDate)
{
set_ValueNoCheck (COLUMNNAME_LastShipDate, LastShipDate);
}
/** Get Letzte Lieferung.
@return Letzte Lieferung */
@Override
public java.sql.Timestamp getLastShipDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_LastShipDate);
}
@Override
public org.compiere.model.I_M_Product getM_Product() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_Product(org.compiere.model.I_M_Product M_Product)
{
set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product_Stats_InOut_Online_v.java | 1 |
请完成以下Java代码 | public Evaluatee prepareContext(final IAttributeSet attributeSet)
{
return Evaluatees.empty();
}
@Override
public List<? extends NamePair> getAvailableValues(final Evaluatee evalCtx_NOTUSED)
{
// NOTE: the only reason why we are fetching and returning the vendors instead of returning NULL,
// is because user needs to set it in purchase order's ASI.
return getCachedVendors();
}
@Nullable
private static BPartnerId normalizeValueKey(@Nullable final Object valueKey)
{
if (valueKey == null)
{
return null;
}
else if (valueKey instanceof Number)
{
final int valueInt = ((Number)valueKey).intValue();
return BPartnerId.ofRepoIdOrNull(valueInt);
}
else
{
final int valueInt = NumberUtils.asInt(valueKey.toString(), -1);
return BPartnerId.ofRepoIdOrNull(valueInt);
}
}
@Override
@Nullable
public KeyNamePair getAttributeValueOrNull(final Evaluatee evalCtx_NOTUSED, final Object valueKey)
{
final BPartnerId bpartnerId = normalizeValueKey(valueKey);
if (bpartnerId == null)
{
return null;
}
return getCachedVendors()
.stream()
.filter(vnp -> vnp.getKey() == bpartnerId.getRepoId())
.findFirst()
.orElseGet(() -> retrieveBPartnerKNPById(bpartnerId));
}
@Nullable
private KeyNamePair retrieveBPartnerKNPById(@NonNull final BPartnerId bpartnerId)
{
final I_C_BPartner bpartner = bpartnerDAO.getByIdOutOfTrx(bpartnerId);
return bpartner != null ? toKeyNamePair(bpartner) : null;
}
@Nullable
@Override
public AttributeValueId getAttributeValueIdOrNull(final Object valueKey)
{
return null;
} | private List<KeyNamePair> getCachedVendors()
{
final ImmutableList<KeyNamePair> vendors = vendorsCache.getOrLoad(0, this::retrieveVendorKeyNamePairs);
return ImmutableList.<KeyNamePair>builder()
.add(staticNullValue())
.addAll(vendors)
.build();
}
private QueryLimit getMaxVendors()
{
final int maxVendorsInt = sysconfigBL.getIntValue(SYSCONFIG_MAX_VENDORS, DEFAULT_MAX_VENDORS);
return QueryLimit.ofInt(maxVendorsInt);
}
private ImmutableList<KeyNamePair> retrieveVendorKeyNamePairs()
{
return bpartnerDAO.retrieveVendors(getMaxVendors())
.stream()
.map(HUVendorBPartnerAttributeValuesProvider::toKeyNamePair)
.sorted(Comparator.comparing(KeyNamePair::getName))
.collect(ImmutableList.toImmutableList());
}
private static KeyNamePair toKeyNamePair(@NonNull final I_C_BPartner bpartner)
{
return KeyNamePair.of(bpartner.getC_BPartner_ID(), bpartner.getName(), bpartner.getDescription());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\HUVendorBPartnerAttributeValuesProvider.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: spring-boot-admin-sample-war
boot:
admin:
client:
url: http://localhost:8080
instance:
service-base-url: http://localhost:8080
profiles:
active:
- secure
management:
| endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-war\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> cmmnProcessEngineConfigurationConfigurer(
CmmnEngineConfigurator cmmnEngineConfigurator) {
return processEngineConfiguration -> processEngineConfiguration.addConfigurator(cmmnEngineConfigurator);
}
@Bean
@ConditionalOnMissingBean
public CmmnEngineConfigurator cmmnEngineConfigurator(SpringCmmnEngineConfiguration cmmnEngineConfiguration) {
SpringCmmnEngineConfigurator cmmnEngineConfigurator = new SpringCmmnEngineConfigurator();
cmmnEngineConfigurator.setCmmnEngineConfiguration(cmmnEngineConfiguration);
cmmnEngineConfiguration.setDisableIdmEngine(true);
cmmnEngineConfiguration.setDisableEventRegistry(true);
invokeConfigurers(cmmnEngineConfiguration);
return cmmnEngineConfigurator;
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(type = {
"org.flowable.app.spring.SpringAppEngineConfiguration"
})
public static class CmmnEngineAppConfiguration extends BaseEngineConfigurationWithConfigurers<SpringCmmnEngineConfiguration> { | @Bean
@ConditionalOnMissingBean(name = "cmmnAppEngineConfigurationConfigurer")
public EngineConfigurationConfigurer<SpringAppEngineConfiguration> cmmnAppEngineConfigurationConfigurer(CmmnEngineConfigurator cmmnEngineConfigurator) {
return appEngineConfiguration -> appEngineConfiguration.addConfigurator(cmmnEngineConfigurator);
}
@Bean
@ConditionalOnMissingBean
public CmmnEngineConfigurator cmmnEngineConfigurator(SpringCmmnEngineConfiguration cmmnEngineConfiguration) {
SpringCmmnEngineConfigurator cmmnEngineConfigurator = new SpringCmmnEngineConfigurator();
cmmnEngineConfigurator.setCmmnEngineConfiguration(cmmnEngineConfiguration);
cmmnEngineConfiguration.setDisableIdmEngine(true);
cmmnEngineConfiguration.setDisableEventRegistry(true);
invokeConfigurers(cmmnEngineConfiguration);
return cmmnEngineConfigurator;
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\cmmn\CmmnEngineAutoConfiguration.java | 2 |
请完成以下Java代码 | default <T> IQueryFilter<T> getLockedByFilter(final Class<T> modelClass, final ILock lock)
{
return getLockedByFilter(modelClass, lock == null ? null : lock.getOwner());
}
/**
* Gets existing lock for given owner name
*
* @return existing lock
* @throws LockFailedException in case lock does not exist
*/
ILock getExistingLockForOwner(LockOwner lockOwner);
<T> IQueryFilter<T> getNotLockedFilter(@NonNull String modelTableName, @NonNull String joinColumnNameFQ); | /**
* Create and return a query builder that allows to retrieve all records of the given <code>modelClass</code> which are currently locked.
* <p>
* Note that the query builder does not specify any ordering.
*/
<T> IQueryBuilder<T> getLockedRecordsQueryBuilder(Class<T> modelClass, Object contextProvider);
<T> List<T> retrieveAndLockMultipleRecords(IQuery<T> query, Class<T> clazz);
<T> IQuery<T> addNotLockedClause(IQuery<T> query);
int removeAutoCleanupLocks();
ExistingLockInfo getLockInfo(TableRecordReference tableRecordReference, LockOwner lockOwner);
SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(@NonNull TableRecordReferenceSet recordRefs);
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\ILockManager.java | 1 |
请完成以下Java代码 | public class IntermediateCatchEventParseHandler extends AbstractFlowNodeBpmnParseHandler<IntermediateCatchEvent> {
private static final Logger logger = LoggerFactory.getLogger(IntermediateCatchEventParseHandler.class);
public Class<? extends BaseElement> getHandledType() {
return IntermediateCatchEvent.class;
}
protected void executeParse(BpmnParse bpmnParse, IntermediateCatchEvent event) {
EventDefinition eventDefinition = null;
if (!event.getEventDefinitions().isEmpty()) {
eventDefinition = event.getEventDefinitions().get(0);
}
if (eventDefinition == null) {
event.setBehavior( | bpmnParse.getActivityBehaviorFactory().createIntermediateCatchEventActivityBehavior(event)
);
} else {
if (
eventDefinition instanceof TimerEventDefinition ||
eventDefinition instanceof SignalEventDefinition ||
eventDefinition instanceof MessageEventDefinition ||
eventDefinition instanceof LinkEventDefinition
) {
bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition);
} else {
logger.warn("Unsupported intermediate catch event type for event " + event.getId());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\IntermediateCatchEventParseHandler.java | 1 |
请完成以下Java代码 | public class GrouperDataType {
@XmlAttribute(name = "number", required = true)
protected String number;
@XmlAttribute(name = "name", required = true)
protected String name;
/**
* Gets the value of the number property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNumber() {
return number;
}
/**
* Sets the value of the number property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNumber(String value) {
this.number = value;
}
/** | * Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\GrouperDataType.java | 1 |
请完成以下Java代码 | void setGreaterThan(Date date) {
query.duedateHigherThan(date);
}
@Override
void setLowerThan(Date date) {
query.duedateLowerThan(date);
}
@Override
String fieldName() {
return "due date";
}
}.run(dueDates);
}
if (createTimes != null) {
new ApplyDates() {
@Override
void setGreaterThan(Date date) {
query.createdAfter(date);
}
@Override
void setLowerThan(Date date) {
query.createdBefore(date);
}
@Override
String fieldName() {
return "create time";
}
}.run(createTimes);
}
if (!CollectionUtil.isEmpty(tenantIds)) {
query.tenantIdIn(tenantIds.toArray(new String[0]));
} | if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeJobsWithoutTenantId)) {
query.includeJobsWithoutTenantId();
}
if (TRUE.equals(acquired)) {
query.acquired();
}
}
@Override
protected void applySortBy(JobQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_JOB_ID_VALUE)) {
query.orderByJobId();
} else if (sortBy.equals(SORT_BY_EXECUTION_ID_VALUE)) {
query.orderByExecutionId();
} else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) {
query.orderByProcessInstanceId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID_VALUE)) {
query.orderByProcessDefinitionId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY_VALUE)) {
query.orderByProcessDefinitionKey();
} else if (sortBy.equals(SORT_BY_JOB_RETRIES_VALUE)) {
query.orderByJobRetries();
} else if (sortBy.equals(SORT_BY_JOB_DUEDATE_VALUE)) {
query.orderByJobDuedate();
} else if (sortBy.equals(SORT_BY_JOB_PRIORITY_VALUE)) {
query.orderByJobPriority();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UserDetails loadUserByUsername(String username) {
UmsMember member = getByUsername(username);
if(member!=null){
return new MemberDetails(member);
}
throw new UsernameNotFoundException("用户名或密码错误");
}
@Override
public String login(String username, String password) {
String token = null;
//密码需要客户端加密后传递
try {
UserDetails userDetails = loadUserByUsername(username);
if(!passwordEncoder.matches(password,userDetails.getPassword())){
throw new BadCredentialsException("密码不正确");
}
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
token = jwtTokenUtil.generateToken(userDetails); | } catch (AuthenticationException e) {
LOGGER.warn("登录异常:{}", e.getMessage());
}
return token;
}
@Override
public String refreshToken(String token) {
return jwtTokenUtil.refreshHeadToken(token);
}
//对输入的验证码进行校验
private boolean verifyAuthCode(String authCode, String telephone){
if(StrUtil.isEmpty(authCode)){
return false;
}
String realAuthCode = memberCacheService.getAuthCode(telephone);
return authCode.equals(realAuthCode);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberServiceImpl.java | 2 |
请完成以下Java代码 | public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getCaseExecutionId() {
return caseExecutionId;
} | public String getCaseInstanceId() {
return caseInstanceId;
}
public String getTenantId() {
return tenantId;
}
public static VariableInstanceDto fromVariableInstance(VariableInstance variableInstance) {
VariableInstanceDto dto = new VariableInstanceDto();
dto.id = variableInstance.getId();
dto.name = variableInstance.getName();
dto.processDefinitionId = variableInstance.getProcessDefinitionId();
dto.processInstanceId = variableInstance.getProcessInstanceId();
dto.executionId = variableInstance.getExecutionId();
dto.caseExecutionId = variableInstance.getCaseExecutionId();
dto.caseInstanceId = variableInstance.getCaseInstanceId();
dto.taskId = variableInstance.getTaskId();
dto.batchId = variableInstance.getBatchId();
dto.activityInstanceId = variableInstance.getActivityInstanceId();
dto.tenantId = variableInstance.getTenantId();
if(variableInstance.getErrorMessage() == null) {
VariableValueDto.fromTypedValue(dto, variableInstance.getTypedValue());
}
else {
dto.errorMessage = variableInstance.getErrorMessage();
dto.type = VariableValueDto.toRestApiTypeName(variableInstance.getTypeName());
}
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\VariableInstanceDto.java | 1 |
请完成以下Java代码 | protected void parseChildElements(XMLStreamReader xtr, DmnElement parentElement, Decision decision, BaseChildElementParser parser) throws Exception {
boolean readyWithChildElements = false;
while (!readyWithChildElements && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (parser.getElementName().equals(xtr.getLocalName())) {
parser.parseChildElement(xtr, parentElement, decision);
}
} else if (xtr.isEndElement() && getElementName().equalsIgnoreCase(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
}
public boolean accepts(DmnElement element) {
return element != null;
}
public List<Object> splitAndFormatInputOutputValues(String valuesText) {
if (StringUtils.isEmpty(valuesText)) {
return Collections.emptyList();
}
List<Object> result = new ArrayList<>();
int start = 0;
int subStart, subEnd;
boolean inQuotes = false;
for (int current = 0; current < valuesText.length(); current++) {
if (valuesText.charAt(current) == '\"') {
inQuotes = !inQuotes;
} else if (valuesText.charAt(current) == ',' && !inQuotes) {
subStart = getSubStringStartPos(start, valuesText);
subEnd = getSubStringEndPos(current, valuesText);
result.add(valuesText.substring(subStart, subEnd));
start = current + 1;
if (valuesText.charAt(start) == ' ') { | start++;
}
}
}
subStart = getSubStringStartPos(start, valuesText);
subEnd = getSubStringEndPos(valuesText.length(), valuesText);
result.add(valuesText.substring(subStart, subEnd));
return result;
}
protected int getSubStringStartPos(int initialStart, String searchString) {
if (searchString.charAt(initialStart) == '\"') {
return initialStart + 1;
}
return initialStart;
}
protected int getSubStringEndPos(int initialEnd, String searchString) {
if (searchString.charAt(initialEnd - 1) == '\"') {
return initialEnd - 1;
}
return initialEnd;
}
} | repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\converter\child\BaseChildElementParser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private DistributionDetail createCandidateDetailFromDDOrderAndLine(
@NonNull final DDOrder ddOrder,
@NonNull final DDOrderLine ddOrderLine)
{
return DistributionDetail.builder()
.ddOrderDocStatus(ddOrder.getDocStatus())
.ddOrderRef(DDOrderRef.ofNullableDDOrderAndLineId(ddOrder.getDdOrderId(), ddOrderLine.getDdOrderLineId()))
.forwardPPOrderRef(ddOrder.getForwardPPOrderRef())
.distributionNetworkAndLineId(ddOrderLine.getDistributionNetworkAndLineId())
.qty(ddOrderLine.getQtyToMove())
.plantId(ddOrder.getPlantId())
.productPlanningId(ddOrder.getProductPlanningId())
.shipperId(ddOrder.getShipperId())
.build();
}
private void handleMainDataUpdates(@NonNull final DDOrderCreatedEvent ddOrderCreatedEvent, @NonNull final DDOrderLine ddOrderLine)
{ | if (ddOrderCreatedEvent.getDdOrder().isSimulated())
{
return;
}
final OrgId orgId = ddOrderCreatedEvent.getOrgId();
final ZoneId timeZone = orgDAO.getTimeZone(orgId);
final DDOrderMainDataHandler mainDataUpdater = DDOrderMainDataHandler.builder()
.ddOrderDetailRequestHandler(ddOrderDetailRequestHandler)
.mainDataRequestHandler(mainDataRequestHandler)
.abstractDDOrderEvent(ddOrderCreatedEvent)
.ddOrderLine(ddOrderLine)
.orgZone(timeZone)
.build();
mainDataUpdater.handleUpdate();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\ddorder\DDOrderAdvisedOrCreatedHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int updateNavStatus(List<Long> ids, Integer navStatus) {
PmsProductCategory productCategory = new PmsProductCategory();
productCategory.setNavStatus(navStatus);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.createCriteria().andIdIn(ids);
return productCategoryMapper.updateByExampleSelective(productCategory, example);
}
@Override
public int updateShowStatus(List<Long> ids, Integer showStatus) {
PmsProductCategory productCategory = new PmsProductCategory();
productCategory.setShowStatus(showStatus);
PmsProductCategoryExample example = new PmsProductCategoryExample();
example.createCriteria().andIdIn(ids);
return productCategoryMapper.updateByExampleSelective(productCategory, example);
}
@Override
public List<PmsProductCategoryWithChildrenItem> listWithChildren() {
return productCategoryDao.listWithChildren();
}
/**
* 根据分类的parentId设置分类的level
*/ | private void setCategoryLevel(PmsProductCategory productCategory) {
//没有父分类时为一级分类
if (productCategory.getParentId() == 0) {
productCategory.setLevel(0);
} else {
//有父分类时选择根据父分类level设置
PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId());
if (parentCategory != null) {
productCategory.setLevel(parentCategory.getLevel() + 1);
} else {
productCategory.setLevel(0);
}
}
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductCategoryServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class WeeklyReportRestController
{
static final String ENDPOINT = Application.ENDPOINT_ROOT + "/weeklyReport";
private final ILoginService loginService;
private final IProductSuppliesService productSuppliesService;
private final UserConfirmationService userConfirmationService;
public WeeklyReportRestController(
@NonNull final ILoginService loginService,
@NonNull final IProductSuppliesService productSuppliesService,
@NonNull final UserConfirmationService userConfirmationService)
{
this.loginService = loginService;
this.productSuppliesService = productSuppliesService;
this.userConfirmationService = userConfirmationService;
}
@GetMapping("/{weekYear}")
public JsonWeeklyReport getWeeklyReport(@PathVariable("weekYear") @NonNull final String weekYearStr)
{
final YearWeek yearWeek = YearWeekUtil.parse(weekYearStr);
return getWeeklyReport(yearWeek, -1);
}
@GetMapping("/{weekYear}/{productId}")
public JsonWeeklyReport getWeeklyReport(
@PathVariable("weekYear") @NonNull final String weekYearStr,
@PathVariable("productId") final long productId)
{
final YearWeek yearWeek = YearWeekUtil.parse(weekYearStr);
return getWeeklyReport(yearWeek, productId);
}
private JsonWeeklyReport getWeeklyReport(
@NonNull final YearWeek yearWeek, | final long singleProductId)
{
final User user = loginService.getLoggedInUser();
return JsonWeeklyReportProducer.builder()
.productSuppliesService(productSuppliesService)
.userConfirmationService(userConfirmationService)
.user(user)
.locale(loginService.getLocale())
.week(yearWeek)
.singleProductId(singleProductId)
.build()
.execute();
}
@PostMapping("/nextWeekTrend")
public JsonSetNextWeekTrendResponse setNextWeekTrend(@RequestBody @NonNull final JsonSetNextWeekTrendRequest request)
{
final User user = loginService.getLoggedInUser();
final Product product = productSuppliesService.getProductById(Long.parseLong(request.getProductId()));
final YearWeek week = YearWeekUtil.parse(request.getWeek());
final @NonNull Trend trend = request.getTrend();
final WeekSupply weeklyForecast = productSuppliesService.setNextWeekTrend(
user.getBpartner(),
product,
week,
trend);
return JsonSetNextWeekTrendResponse.builder()
.productId(weeklyForecast.getProductIdAsString())
.week(YearWeekUtil.toJsonString(weeklyForecast.getWeek()))
.trend(weeklyForecast.getTrend())
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\rest\weeklyReport\WeeklyReportRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getRequestParamName() {
return requestParamName;
}
public void setRequestParamName(String requestParamName) {
this.requestParamName = requestParamName;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public List<String> getSupportedVersions() {
return supportedVersions;
}
public void setSupportedVersions(List<String> supportedVersions) {
this.supportedVersions = supportedVersions; | }
@Override
public String toString() {
// @formatter:off
return new ToStringCreator(this)
.append("defaultVersion", defaultVersion)
.append("detectSupportedVersions", detectSupportedVersions)
.append("headerName", headerName)
.append("mediaType", mediaType)
.append("mediaTypeParamName", mediaTypeParamName)
.append("pathSegment", pathSegment)
.append("requestParamName", requestParamName)
.append("required", required)
.append("supportedVersions", supportedVersions)
.toString();
// @formatter:on
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\VersionProperties.java | 2 |
请完成以下Java代码 | private void setEnabled(final boolean enabled)
{
DummyDeviceConfigPool.setEnabled(enabled);
deviceAccessorsHubFactory.cacheReset();
}
private Map<String, Object> getConfigInfo()
{
return ImmutableMap.<String, Object>builder()
.put("enabled", DummyDeviceConfigPool.isEnabled())
.put("responseMinValue", DummyDeviceConfigPool.getResponseMinValue().doubleValue())
.put("responseMaxValue", DummyDeviceConfigPool.getResponseMaxValue().doubleValue())
.build();
}
@GetMapping("/addOrUpdate")
public void addScale(
@RequestParam("deviceName") final String deviceName,
@RequestParam("attributes") final String attributesStr,
@RequestParam(name = "onlyForWarehouseIds", required = false) final String onlyForWarehouseIdsStr)
{
assertLoggedIn(); | final List<AttributeCode> attributes = CollectionUtils.ofCommaSeparatedList(attributesStr, AttributeCode::ofString);
final List<WarehouseId> onlyForWarehouseIds = RepoIdAwares.ofCommaSeparatedList(onlyForWarehouseIdsStr, WarehouseId.class);
DummyDeviceConfigPool.addDevice(DummyDeviceAddRequest.builder()
.deviceName(deviceName)
.assignedAttributeCodes(attributes)
.onlyWarehouseIds(onlyForWarehouseIds)
.build());
setEnabled(true);
}
@GetMapping("/removeDevice")
public void addScale(
@RequestParam("deviceName") final String deviceName)
{
assertLoggedIn();
DummyDeviceConfigPool.removeDeviceByName(deviceName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.device.webui\src\main\java\de\metas\device\rest\DummyDevicesRestControllerTemplate.java | 1 |
请完成以下Java代码 | protected List<IFacet<I_PMM_PurchaseCandidate>> collectFacets(final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder)
{
final Timestamp today = Env.getDate(queryBuilder.getCtx());
final List<Map<String, Object>> datePromised = queryBuilder
.addNotEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, null)
.addCompareFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, Operator.GREATER_OR_EQUAL, today)
.create()
.listDistinct(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised);
final List<IFacet<I_PMM_PurchaseCandidate>> facets = new ArrayList<>(datePromised.size() + 1);
for (final Map<String, Object> row : datePromised)
{
final IFacet<I_PMM_PurchaseCandidate> facet = createFacet(row);
facets.add(facet);
}
//
// Add Before Today facet
facets.add(0, Facet.<I_PMM_PurchaseCandidate> builder()
.setFacetCategory(getFacetCategory()) | .setDisplayName(" < " + dateFormat.format(today))
.setFilter(TypedSqlQueryFilter.of(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised + "<" + DB.TO_DATE(today)))
.build()
);
return facets;
}
private IFacet<I_PMM_PurchaseCandidate> createFacet(final Map<String, Object> row)
{
final Timestamp date = (Timestamp)row.get(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised);
return Facet.<I_PMM_PurchaseCandidate> builder()
.setFacetCategory(getFacetCategory())
.setDisplayName(dateFormat.format(date))
.setFilter(TypedSqlQueryFilter.of(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised + "=" + DB.TO_DATE(date)))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\facet\impl\PMM_PurchaseCandidate_DatePromised_FacetCollector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) { | this.url = url;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@Override
public String toString() {
return "MenuEntity{" +
"id='" + id + '\'' +
", menuName='" + menuName + '\'' +
", url='" + url + '\'' +
", parentId='" + parentId + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\user\MenuEntity.java | 2 |
请完成以下Java代码 | public ITableRecordReference getRecordToAttach()
{
return recordToAttach;
}
public I_DLM_Partition getPartitionToComplete()
{
return partitionToComplete;
}
@Override
public String toString()
{
return "CreatePartitionRequest [onNotDLMTable=" + onNotDLMTable + ", oldestFirst=" + oldestFirst + ", partitionToComplete=" + partitionToComplete + ", recordToAttach=" + recordToAttach + ", config=" + config + "]";
}
}
/**
* Passed to {@link DLMPartitionerWorkpackageProcessor#schedule(CreatePartitionAsyncRequest, int)} to create a workpackage to invoke {@link IPartitionerService#createPartition(CreatePartitionRequest)} asynchronously.
* The additional members of this class tell the work package processor if it shall enqueue another workpackage after it did its job.
*
* @author metas-dev <dev@metasfresh.com>
*
*/
@Immutable
public static class CreatePartitionAsyncRequest extends CreatePartitionRequest
{
private final int count;
private final Date dontReEnqueueAfter;
private final CreatePartitionRequest partitionRequest;
private CreatePartitionAsyncRequest(
final CreatePartitionRequest partitionRequest,
final int count,
final Date dontReEnqueueAfter)
{
super(partitionRequest.getConfig(),
partitionRequest.isOldestFirst(),
partitionRequest.getRecordToAttach(),
partitionRequest.getPartitionToComplete(),
partitionRequest.getOnNotDLMTable());
this.partitionRequest = partitionRequest; // we use it for the toString() method
this.count = count;
this.dontReEnqueueAfter = dontReEnqueueAfter;
}
/**
* Only enqueue the given number of work packages (one after each other).
*
* @return | */
public int getCount()
{
return count;
}
/**
* Don't enqueue another workpackage after the given time has passed. One intended usage scenario is to start partitioning in the evening and stop in the morning.
*
* @return never returns <code>null</code>, but might return <code>9999-12-31</code>.
*/
public Date getDontReEnqueueAfter()
{
return dontReEnqueueAfter;
}
@Override
public String toString()
{
return "CreatePartitionAsyncRequest [count=" + count + ", dontReEnqueueAfter=" + dontReEnqueueAfter + ", partitionRequest=" + partitionRequest + "]";
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\PartitionRequestFactory.java | 1 |
请完成以下Java代码 | public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
Object value = null;
Expression expressionObject = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getExpressionManager().createExpression(expression);
value = expressionObject.getValue(planItemInstanceEntity);
if (value instanceof CompletableFuture) {
CommandContextUtil.getAgenda(commandContext)
.planFutureOperation((CompletableFuture<Object>) value, new FutureExpressionCompleteAction(planItemInstanceEntity));
} else {
complete(value, planItemInstanceEntity);
}
}
protected void complete(Object value, PlanItemInstanceEntity planItemInstanceEntity) {
if (resultVariable != null) {
if (storeResultVariableAsTransient) {
planItemInstanceEntity.setTransientVariable(resultVariable, value);
} else {
planItemInstanceEntity.setVariable(resultVariable, value);
}
} | CommandContextUtil.getAgenda().planCompletePlanItemInstanceOperation(planItemInstanceEntity);
}
protected class FutureExpressionCompleteAction implements BiConsumer<Object, Throwable> {
protected final PlanItemInstanceEntity planItemInstanceEntity;
public FutureExpressionCompleteAction(PlanItemInstanceEntity planItemInstanceEntity) {
this.planItemInstanceEntity = planItemInstanceEntity;
}
@Override
public void accept(Object value, Throwable throwable) {
if (throwable == null) {
complete(value, planItemInstanceEntity);
} else {
sneakyThrow(throwable);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\PlanItemExpressionActivityBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void fetchAuthorByNameAsEntityJpql() {
Author author = authorRepository.findByName("Joana Nimar", Author.class);
System.out.println(author);
}
@Transactional(readOnly = true)
public void fetchAuthorByNameAsDtoNameEmailJpql() {
AuthorNameEmailDto author = authorRepository.findByName("Joana Nimar", AuthorNameEmailDto.class);
System.out.println(author.getEmail() + ", " + author.getName());
}
@Transactional(readOnly = true)
public void fetchAuthorByNameAsDtoGenreJpql() {
AuthorGenreDto author = authorRepository.findByName("Joana Nimar", AuthorGenreDto.class);
System.out.println(author.getGenre());
}
@Transactional(readOnly = true)
public void fetchAuthorByNameAndAgeAsEntityJpql() {
Author author = authorRepository.findByNameAndAge("Joana Nimar", 34, Author.class);
System.out.println(author);
}
@Transactional(readOnly = true)
public void fetchAuthorByNameAndAgeAsDtoNameEmailJpql() {
AuthorNameEmailDto author = authorRepository.findByNameAndAge("Joana Nimar", 34, AuthorNameEmailDto.class); | System.out.println(author.getEmail() + ", " + author.getName());
}
@Transactional(readOnly = true)
public void fetchAuthorByNameAndAgeAsDtoGenreJpql() {
AuthorGenreDto author = authorRepository.findByNameAndAge("Joana Nimar", 34, AuthorGenreDto.class);
System.out.println(author.getGenre());
}
@Transactional(readOnly = true)
public void fetchAuthorsAsEntitiesJpql() {
List<Author> authors = authorRepository.findByGenre("Anthology", Author.class);
System.out.println(authors);
}
@Transactional(readOnly = true)
public void fetchAuthorsAsDtoJpql() {
List<AuthorNameEmailDto> authors = authorRepository.findByGenre("Anthology", AuthorNameEmailDto.class);
authors.forEach(a -> System.out.println(a.getName() + ", " + a.getEmail()));
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDynamicProjection\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public VariableMap putValue(String name, Object value) {
put(name, value);
return this;
}
@Override
public VariableMap putValueTyped(String name, TypedValue value) {
if(name == null) {
throw new IllegalArgumentException("This map does not support 'null' names.");
}
setVariable(name, value);
return this;
}
@Override
public int size() {
throw new UnsupportedOperationException(getClass().getName()+".size() is not supported.");
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException(getClass().getName()+".isEmpty() is not supported.");
}
@Override
public boolean containsKey(Object key) {
throw new UnsupportedOperationException(getClass().getName()+".containsKey() is not supported.");
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException(getClass().getName()+".containsValue() is not supported.");
}
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException(getClass().getName()+".remove is unsupported. Use " + getClass().getName() + ".put(key, null)");
} | @Override
public void clear() {
throw new UnsupportedOperationException(getClass().getName()+".clear() is not supported.");
}
@Override
public Set<String> keySet() {
throw new UnsupportedOperationException(getClass().getName()+".keySet() is not supported.");
}
@Override
public Collection<Object> values() {
throw new UnsupportedOperationException(getClass().getName()+".values() is not supported.");
}
@Override
public Set<java.util.Map.Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException(getClass().getName()+".entrySet() is not supported.");
}
public VariableContext asVariableContext() {
throw new UnsupportedOperationException(getClass().getName()+".asVariableContext() is not supported.");
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\AbstractVariableMap.java | 1 |
请完成以下Java代码 | public final class ObjectValueExpression extends ValueExpression {
private static final long serialVersionUID = 1L;
private final TypeConverter converter;
private final Object object;
private final Class<?> type;
/**
* Wrap an object into a value expression.
* @param converter type converter
* @param object the object to wrap
* @param type the expected type this object will be coerced in {@link #getValue(ELContext)}.
*/
public ObjectValueExpression(TypeConverter converter, Object object, Class<?> type) {
super();
this.converter = converter;
this.object = object;
this.type = type;
if (type == null) {
throw new NullPointerException(LocalMessages.get("error.value.notype"));
}
}
/**
* Two object value expressions are equal if and only if their wrapped objects are equal.
*/
@Override
public boolean equals(Object obj) {
if (obj != null && obj.getClass() == getClass()) {
ObjectValueExpression other = (ObjectValueExpression) obj;
if (type != other.type) {
return false;
}
return (object == other.object || (object != null && object.equals(other.object)));
}
return false;
}
@Override
public int hashCode() {
return object == null ? 0 : object.hashCode();
}
/**
* Answer the wrapped object, coerced to the expected type.
*/
@Override
public Object getValue(ELContext context) {
return converter.convert(object, type);
}
/**
* Answer <code>null</code>.
*/
@Override
public String getExpressionString() {
return null;
}
/**
* Answer <code>false</code>.
*/
@Override
public boolean isLiteralText() { | return false;
}
/**
* Answer <code>null</code>.
*/
@Override
public Class<?> getType(ELContext context) {
return null;
}
/**
* Answer <code>true</code>.
*/
@Override
public boolean isReadOnly(ELContext context) {
return true;
}
/**
* Throw an exception.
*/
@Override
public void setValue(ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", "<object value expression>"));
}
@Override
public String toString() {
return "ValueExpression(" + object + ")";
}
@Override
public Class<?> getExpectedType() {
return type;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\ObjectValueExpression.java | 1 |
请完成以下Java代码 | protected AttributeSetInstanceId getM_AttributeSetInstance(final I_C_OrderLine documentLine)
{
return AttributeSetInstanceId.ofRepoIdOrNone(documentLine.getM_AttributeSetInstance_ID());
}
/**
* @param document
* In case the purchase order has a partner and product of one line belonging to a complete material tracking and that material tracking is not set into ASI, show an error message.
*/
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void verifyMaterialTracking(final I_C_Order document)
{
final IMaterialTrackingDAO materialTrackingDao = Services.get(IMaterialTrackingDAO.class);
final Properties ctx = InterfaceWrapperHelper.getCtx(document);
if (document.isSOTrx())
{
// nothing to do
return;
}
final List<I_C_OrderLine> documentLines = retrieveDocumentLines(document);
for (final I_C_OrderLine line : documentLines)
{
String msg;
if (getMaterialTrackingFromDocumentLineASI(line) != null) | {
continue; // a tracking is set, nothing to do
}
final IMaterialTrackingQuery queryVO = materialTrackingDao.createMaterialTrackingQuery();
queryVO.setCompleteFlatrateTerm(true);
queryVO.setProcessed(false);
queryVO.setC_BPartner_ID(document.getC_BPartner_ID());
queryVO.setM_Product_ID(line.getM_Product_ID());
// there can be many trackings for the given product and partner (different parcels), which is not a problem for this verification
queryVO.setOnMoreThanOneFound(OnMoreThanOneFound.ReturnFirst);
final I_M_Material_Tracking materialTracking = materialTrackingDao.retrieveMaterialTracking(ctx, queryVO);
if (materialTracking == null)
{
continue; // there is no tracking that could be selected, nothing to do
}
msg = Services.get(IMsgBL.class).getMsg(ctx, MSG_M_Material_Tracking_Set_In_Orderline, new Object[] { document.getDocumentNo(), line.getLine() });
throw new AdempiereException(msg);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_Order.java | 1 |
请完成以下Java代码 | static @Nullable List<X509Certificate> parse(@Nullable String text) {
if (text == null) {
return null;
}
CertificateFactory factory = getCertificateFactory();
List<X509Certificate> certs = new ArrayList<>();
readCertificates(text, factory, certs::add);
Assert.state(!CollectionUtils.isEmpty(certs), "Missing certificates or unrecognized format");
return List.copyOf(certs);
}
private static CertificateFactory getCertificateFactory() {
try {
return CertificateFactory.getInstance("X.509");
}
catch (CertificateException ex) {
throw new IllegalStateException("Unable to get X.509 certificate factory", ex);
}
}
private static void readCertificates(String text, CertificateFactory factory, Consumer<X509Certificate> consumer) {
try {
Matcher matcher = PATTERN.matcher(text);
while (matcher.find()) {
String encodedText = matcher.group(1);
byte[] decodedBytes = decodeBase64(encodedText); | ByteArrayInputStream inputStream = new ByteArrayInputStream(decodedBytes);
while (inputStream.available() > 0) {
consumer.accept((X509Certificate) factory.generateCertificate(inputStream));
}
}
}
catch (CertificateException ex) {
throw new IllegalStateException("Error reading certificate: " + ex.getMessage(), ex);
}
}
private static byte[] decodeBase64(String content) {
byte[] bytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes();
return Base64.getDecoder().decode(bytes);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemCertificateParser.java | 1 |
请完成以下Java代码 | public List<Long> fetchPartitions(String table) {
List<Long> partitions = new ArrayList<>();
List<String> partitionsTables = getJdbcTemplate().queryForList(SELECT_PARTITIONS_STMT, String.class, table);
for (String partitionTableName : partitionsTables) {
String partitionTsStr = partitionTableName.substring(table.length() + 1);
try {
partitions.add(Long.parseLong(partitionTsStr));
} catch (NumberFormatException nfe) {
log.debug("Failed to parse table name: {}", partitionTableName);
}
}
return partitions;
}
public long calculatePartitionStartTime(long ts, long partitionDuration) {
return ts - (ts % partitionDuration);
}
private synchronized int getCurrentServerVersion() { | if (currentServerVersion == null) {
try {
currentServerVersion = getJdbcTemplate().queryForObject("SELECT current_setting('server_version_num')", Integer.class);
} catch (Exception e) {
log.warn("Error occurred during fetch of the server version", e);
}
if (currentServerVersion == null) {
currentServerVersion = 0;
}
}
return currentServerVersion;
}
protected JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\insert\sql\SqlPartitioningRepository.java | 1 |
请完成以下Java代码 | public class WebSocketServerEndpoint {
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
*/
private static ConcurrentHashMap<String, Session> SESSION_POOLS = new ConcurrentHashMap<>();
/**
* 新的WebSocket请求开启
*/
@OnOpen
public void onOpen(@PathParam("key") String key, Session session) {
SESSION_POOLS.put(key, session);
log.info("[WebSocket] 连接成功,当前连接人数为:={}", SESSION_POOLS.size());
try {
session.getBasicRemote().sendText("Web socket 消息");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* WebSocket请求关闭
*/
@OnClose
public void onClose(@PathParam("key") String key) {
SESSION_POOLS.remove(key);
log.info("WebSocket请求关闭");
}
@OnError | public void onError(Throwable thr) {
log.info("WebSocket 异常");
}
/**
* 收到客户端信息
*/
@OnMessage
public void onMessage(@PathParam("key") String key, String message, Session session) throws IOException {
message = "客户端:" + message + ",已收到";
session.getBasicRemote().sendText("Web socket 消息::" + message);
log.info(message);
}
} | repos\spring-boot-student-master\spring-boot-student-websocket\src\main\java\com\xiaolyuh\controller\WebSocketServerEndpoint.java | 1 |
请完成以下Java代码 | private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler handler : handlers.values()) {
if (FilterInvocation.class
.equals(GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) {
return handler;
}
}
throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application "
+ "context. There must be at least one in order to support expressions in JSP 'authorize' tags.");
}
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
WebInvocationPrivilegeEvaluator privEvaluatorFromRequest = (WebInvocationPrivilegeEvaluator) getRequest() | .getAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE);
if (privEvaluatorFromRequest != null) {
return privEvaluatorFromRequest;
}
ApplicationContext ctx = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.isEmpty()) {
throw new IOException(
"No visible WebInvocationPrivilegeEvaluator instance could be found in the application "
+ "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags.");
}
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
}
} | repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AbstractAuthorizeTag.java | 1 |
请完成以下Java代码 | private void copyUserIdFromSalesToPurchaseOrderLine(
@NonNull final I_C_OrderLine salesOrderLine,
@NonNull final I_C_OrderLine purchaseOrderLine)
{
final int userID = create(salesOrderLine, de.metas.interfaces.I_C_OrderLine.class).getAD_User_ID();
create(purchaseOrderLine, de.metas.interfaces.I_C_OrderLine.class).setAD_User_ID(userID);
}
@Override
protected void closeGroup(final I_C_OrderLine purchaseOrderLine)
{
final List<I_C_OrderLine> salesOrderLines = purchaseOrderLine2saleOrderLines.get(purchaseOrderLine);
final Set<OrderId> salesOrdersToBeClosed = new HashSet<>();
final OrderId singleSalesOrderId = extractSingleOrderIdOrNull(salesOrderLines);
purchaseOrderLine.setC_OrderSO_ID(OrderId.toRepoId(singleSalesOrderId));
InterfaceWrapperHelper.save(purchaseOrderLine);
for (final I_C_OrderLine salesOrderLine : purchaseOrderLine2saleOrderLines.get(purchaseOrderLine))
{
orderDAO.allocatePOLineToSOLine(
OrderLineId.ofRepoId(purchaseOrderLine.getC_OrderLine_ID()),
OrderLineId.ofRepoId(salesOrderLine.getC_OrderLine_ID()));
salesOrdersToBeClosed.add(OrderId.ofRepoId(salesOrderLine.getC_Order_ID()));
}
if (PurchaseTypeEnum.MEDIATED.equals(purchaseType))
{
salesOrdersToBeClosed.forEach(orderBL::closeOrder);
}
}
@Override
protected void addItemToGroup(final I_C_OrderLine purchaseOrderLine, final I_C_OrderLine salesOrderLine)
{
final BigDecimal oldQtyEntered = purchaseOrderLine.getQtyEntered();
// the purchase order line's UOM is the internal stocking UOM, so we don't need to convert from qtyOrdered/qtyReserved to qtyEntered.
final BigDecimal purchaseQty;
if (I_C_OrderLine.COLUMNNAME_QtyOrdered.equals(purchaseQtySource))
{
purchaseQty = PurchaseTypeEnum.MEDIATED.equals(purchaseType)
? salesOrderLine.getQtyOrdered().subtract(salesOrderLine.getQtyDelivered())
: salesOrderLine.getQtyOrdered();
}
else if (I_C_OrderLine.COLUMNNAME_QtyReserved.equals(purchaseQtySource))
{ | purchaseQty = salesOrderLine.getQtyReserved();
}
else
{
Check.errorIf(true, "Unsupported purchaseQtySource={}", purchaseQtySource);
purchaseQty = null; // won't be reached
}
final BigDecimal newQtyEntered = oldQtyEntered.add(purchaseQty);
// setting QtyEntered, because qtyOrdered will be set from qtyEntered by a model interceptor
purchaseOrderLine.setQtyEntered(newQtyEntered);
purchaseOrderLine2saleOrderLines.get(purchaseOrderLine).add(salesOrderLine); // no NPE, because the list for this key was added in createGroup()
}
I_C_Order getPurchaseOrder()
{
return purchaseOrder;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Nullable
private static OrderId extractSingleOrderIdOrNull(final List<I_C_OrderLine> orderLines)
{
return CollectionUtils.extractSingleElementOrDefault(
orderLines,
orderLine -> OrderId.ofRepoId(orderLine.getC_Order_ID()),
null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\createFrom\po_from_so\impl\CreatePOLineFromSOLinesAggregator.java | 1 |
请完成以下Java代码 | public static InvoicePaySchedule ofList(@NonNull final List<InvoicePayScheduleLine> lines)
{
return new InvoicePaySchedule(lines);
}
public static Optional<InvoicePaySchedule> optionalOfList(@NonNull final List<InvoicePayScheduleLine> lines)
{
return lines.isEmpty() ? Optional.empty() : Optional.of(ofList(lines));
}
public static Collector<InvoicePayScheduleLine, ?, Optional<InvoicePaySchedule>> collect()
{
return GuavaCollectors.collectUsingListAccumulator(InvoicePaySchedule::optionalOfList);
}
public boolean isValid()
{
return lines.stream().allMatch(InvoicePayScheduleLine::isValid);
}
public boolean validate(@NonNull final Money invoiceGrandTotal)
{
final boolean isValid = computeIsValid(invoiceGrandTotal);
markAsValid(isValid);
return isValid;
}
private boolean computeIsValid(@NonNull final Money invoiceGrandTotal)
{
final Money totalDue = getTotalDueAmt();
return invoiceGrandTotal.isEqualByComparingTo(totalDue); | }
private void markAsValid(final boolean isValid)
{
lines.forEach(line -> line.setValid(isValid));
}
private Money getTotalDueAmt()
{
return getLines()
.stream()
.map(InvoicePayScheduleLine::getDueAmount)
.reduce(Money::add)
.orElseThrow(() -> new AdempiereException("No lines"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\InvoicePaySchedule.java | 1 |
请完成以下Java代码 | public void setQtyCUsPerLU (final @Nullable BigDecimal QtyCUsPerLU)
{
set_Value (COLUMNNAME_QtyCUsPerLU, QtyCUsPerLU);
}
@Override
public BigDecimal getQtyCUsPerLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerLU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerLU_InInvoiceUOM)
{
set_Value (COLUMNNAME_QtyCUsPerLU_InInvoiceUOM, QtyCUsPerLU_InInvoiceUOM);
}
@Override
public BigDecimal getQtyCUsPerLU_InInvoiceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerLU_InInvoiceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerTU (final @Nullable BigDecimal QtyCUsPerTU)
{
set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU);
}
@Override
public BigDecimal getQtyCUsPerTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyCUsPerTU_InInvoiceUOM (final @Nullable BigDecimal QtyCUsPerTU_InInvoiceUOM)
{
set_Value (COLUMNNAME_QtyCUsPerTU_InInvoiceUOM, QtyCUsPerTU_InInvoiceUOM);
}
@Override | public BigDecimal getQtyCUsPerTU_InInvoiceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU_InInvoiceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyItemCapacity (final @Nullable BigDecimal QtyItemCapacity)
{
set_Value (COLUMNNAME_QtyItemCapacity, QtyItemCapacity);
}
@Override
public BigDecimal getQtyItemCapacity()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyItemCapacity);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final int QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public int getQtyTU()
{
return get_ValueAsInt(COLUMNNAME_QtyTU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack_Item.java | 1 |
请完成以下Java代码 | public int getVersion() {
return version;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
} | @Override
public String getResourceName() {
return resourceName;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String toString() {
return "EventDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDefinitionEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReturnT<String> api(HttpServletRequest request, @PathVariable("uri") String uri, @RequestBody(required = false) String data) {
// valid
if (!"POST".equalsIgnoreCase(request.getMethod())) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, HttpMethod not support.");
}
if (uri==null || uri.trim().length()==0) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping empty.");
}
if (XxlJobAdminConfig.getAdminConfig().getAccessToken()!=null
&& XxlJobAdminConfig.getAdminConfig().getAccessToken().trim().length()>0
&& !XxlJobAdminConfig.getAdminConfig().getAccessToken().equals(request.getHeader(XxlJobRemotingUtil.XXL_JOB_ACCESS_TOKEN))) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "The access token is wrong.");
}
// services mapping | if ("callback".equals(uri)) {
List<HandleCallbackParam> callbackParamList = GsonTool.fromJson(data, List.class, HandleCallbackParam.class);
return adminBiz.callback(callbackParamList);
} else if ("registry".equals(uri)) {
RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class);
return adminBiz.registry(registryParam);
} else if ("registryRemove".equals(uri)) {
RegistryParam registryParam = GsonTool.fromJson(data, RegistryParam.class);
return adminBiz.registryRemove(registryParam);
} else {
return new ReturnT<String>(ReturnT.FAIL_CODE, "invalid request, uri-mapping("+ uri +") not found.");
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobApiController.java | 2 |
请完成以下Java代码 | public class IMP_Processors_StandaloneLauncher
{
public IMP_Processors_StandaloneLauncher()
{
super();
}
public void start()
{
System.out.println("Retrieving processor definitions...");
final List<I_IMP_Processor> processorDefs = retrieveProcessors();
if (processorDefs.isEmpty())
{
throw new RuntimeException("No import processors were found");
}
for (final I_IMP_Processor processorDef : processorDefs)
{
start(processorDef);
}
while (true)
{
try
{
Thread.sleep(Long.MAX_VALUE);
}
catch (InterruptedException e)
{
System.out.println("Interrupted!");
}
}
}
private void start(final I_IMP_Processor processorDef)
{
final AdempiereProcessor adempiereProcessorDef = Services.get(IIMPProcessorBL.class).asAdempiereProcessor(processorDef);
final ReplicationProcessor processorThread = new ReplicationProcessor(
adempiereProcessorDef,
0 // initialNap=0sec
); | processorThread.setDaemon(true);
processorThread.start();
System.out.println("Started " + processorThread);
}
private List<I_IMP_Processor> retrieveProcessors()
{
final Properties ctx = Env.getCtx();
final List<I_IMP_Processor> processorDefs = new Query(ctx, I_IMP_Processor.Table_Name, null, ITrx.TRXNAME_None)
.setOnlyActiveRecords(true)
.setOrderBy(I_IMP_Processor.COLUMNNAME_AD_Client_ID
+ ", " + I_IMP_Processor.COLUMNNAME_IMP_Processor_ID)
.list(I_IMP_Processor.class);
return processorDefs;
}
public static final void main(String[] args) throws InterruptedException
{
Env.getSingleAdempiereInstance(null).startup(RunMode.BACKEND);
final IMP_Processors_StandaloneLauncher launcher = new IMP_Processors_StandaloneLauncher();
launcher.start();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\org\adempiere\process\rpl\imp\IMP_Processors_StandaloneLauncher.java | 1 |
请完成以下Java代码 | public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public long getLastHeartbeat() {
return lastHeartbeat;
}
public void setLastHeartbeat(long lastHeartbeat) {
this.lastHeartbeat = lastHeartbeat;
}
public void setHeartbeatVersion(long heartbeatVersion) {
this.heartbeatVersion = heartbeatVersion;
}
public long getHeartbeatVersion() { | return heartbeatVersion;
}
public String getVersion() {
return version;
}
public MachineInfoVo setVersion(String version) {
this.version = version;
return this;
}
public boolean isHealthy() {
return healthy;
}
public void setHealthy(boolean healthy) {
this.healthy = healthy;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\MachineInfoVo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void resetPreviousDecisionDefinitionId() {
previousDecisionDefinitionId = null;
ensurePreviousDecisionDefinitionIdInitialized();
}
protected void ensurePreviousDecisionDefinitionIdInitialized() {
if (previousDecisionDefinitionId == null && !firstVersion) {
previousDecisionDefinitionId = Context
.getCommandContext()
.getDecisionDefinitionManager()
.findPreviousDecisionDefinitionId(key, version, tenantId);
if (previousDecisionDefinitionId == null) {
firstVersion = true;
}
}
}
@Override
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public void setHistoryTimeToLive(Integer historyTimeToLive) {
this.historyTimeToLive = historyTimeToLive;
}
@Override
public String getVersionTag() {
return versionTag;
}
public void setVersionTag(String versionTag) { | this.versionTag = versionTag;
}
@Override
public String toString() {
return "DecisionDefinitionEntity{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", category='" + category + '\'' +
", key='" + key + '\'' +
", version=" + version +
", versionTag=" + versionTag +
", decisionRequirementsDefinitionId='" + decisionRequirementsDefinitionId + '\'' +
", decisionRequirementsDefinitionKey='" + decisionRequirementsDefinitionKey + '\'' +
", deploymentId='" + deploymentId + '\'' +
", tenantId='" + tenantId + '\'' +
", historyTimeToLive=" + historyTimeToLive +
'}';
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private CommissionTriggerData createForRequest(
@NonNull final CommissionTriggerDocument commissionTriggerDocument,
final boolean documentDeleted)
{
final CommissionTriggerDataBuilder builder = CommissionTriggerData
.builder()
.orgId(commissionTriggerDocument.getOrgId())
.invoiceCandidateWasDeleted(documentDeleted)
.triggerType(commissionTriggerDocument.getTriggerType())
.triggerDocumentId(commissionTriggerDocument.getId())
.triggerDocumentDate(commissionTriggerDocument.getCommissionDate())
.timestamp(commissionTriggerDocument.getUpdated())
.productId(commissionTriggerDocument.getProductId())
.totalQtyInvolved(commissionTriggerDocument.getTotalQtyInvolved())
.documentCurrencyId(commissionTriggerDocument.getDocumentCurrencyId());
if (documentDeleted)
{
builder | .forecastedBasePoints(CommissionPoints.ZERO)
.invoiceableBasePoints(CommissionPoints.ZERO)
.invoicedBasePoints(CommissionPoints.ZERO);
}
else
{
builder
.forecastedBasePoints(commissionTriggerDocument.getForecastCommissionPoints())
.invoiceableBasePoints(commissionTriggerDocument.getCommissionPointsToInvoice())
.invoicedBasePoints(commissionTriggerDocument.getInvoicedCommissionPoints());
}
return builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionTriggerFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getSubscriptionConnectionPoolSize() {
return subscriptionConnectionPoolSize;
}
public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) {
this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize;
}
public int getConnectionMinimumIdleSize() {
return connectionMinimumIdleSize;
}
public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) {
this.connectionMinimumIdleSize = connectionMinimumIdleSize;
}
public int getConnectionPoolSize() {
return connectionPoolSize;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public int getDatabase() {
return database;
} | public void setDatabase(int database) {
this.database = database;
}
public boolean isDnsMonitoring() {
return dnsMonitoring;
}
public void setDnsMonitoring(boolean dnsMonitoring) {
this.dnsMonitoring = dnsMonitoring;
}
public int getDnsMonitoringInterval() {
return dnsMonitoringInterval;
}
public void setDnsMonitoringInterval(int dnsMonitoringInterval) {
this.dnsMonitoringInterval = dnsMonitoringInterval;
}
public String getCodec() {
return codec;
}
public void setCodec(String codec) {
this.codec = codec;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\config\RedissonConfig.java | 2 |
请完成以下Java代码 | public void subscribe(Set<TopicPartitionInfo> partitions) {
this.partitions = partitions;
subscribed = true;
}
@Override
public void stop() {
stopped = true;
}
@Override
public void unsubscribe() {
stopped = true;
subscribed = false;
}
@Override
public List<T> poll(long durationInMillis) {
if (subscribed) {
@SuppressWarnings("unchecked")
List<T> messages = partitions
.stream()
.map(tpi -> {
try {
return storage.get(tpi.getFullTopicName());
} catch (InterruptedException e) {
if (!stopped) {
log.error("Queue was interrupted.", e);
}
return Collections.emptyList();
}
})
.flatMap(List::stream)
.map(msg -> (T) msg).collect(Collectors.toList());
if (messages.size() > 0) {
return messages;
}
try {
Thread.sleep(durationInMillis);
} catch (InterruptedException e) {
if (!stopped) {
log.error("Failed to sleep.", e);
} | }
}
return Collections.emptyList();
}
@Override
public void commit() {
}
@Override
public boolean isStopped() {
return stopped;
}
@Override
public Set<TopicPartitionInfo> getPartitions() {
return partitions;
}
@Override
public List<String> getFullTopicNames() {
return partitions.stream().map(TopicPartitionInfo::getFullTopicName).collect(Collectors.toList());
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\memory\InMemoryTbQueueConsumer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
@ApiModelProperty(example = "active")
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@ApiModelProperty(example = "123")
public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
@ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case")
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) { | this.callbackType = callbackType;
}
@ApiModelProperty(example = "123")
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
@ApiModelProperty(example = "event-to-cmmn-1.1-case")
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java | 2 |
请完成以下Java代码 | private static String getSmsTemplateId(DySmsEnum dySmsEnum) {
JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class);
String templateCode = dySmsEnum.getTemplateCode();
if (StringUtils.isNotEmpty(baseConfig.getSignature())) {
Map<String, String> smsTemplate = baseConfig.getTemplateCode();
if (smsTemplate.containsKey(templateCode) &&
StringUtils.isNotEmpty(smsTemplate.get(templateCode))) {
templateCode = smsTemplate.get(templateCode);
logger.debug("yml中读取短信模板ID: {}", templateCode);
}
}
return templateCode;
}
/**
* 从JSONObject中提取模板参数(按原始顺序)
*
* @param templateParamJson 模板参数
*/
private static String[] extractTemplateParams(JSONObject templateParamJson) {
if (templateParamJson == null || templateParamJson.isEmpty()) { | return new String[0];
}
List<String> params = new ArrayList<>();
for (String key : templateParamJson.keySet()) {
Object value = templateParamJson.get(key);
if (value != null) {
params.add(value.toString());
} else {
// 处理null值
params.add("");
}
}
logger.debug("提取模板参数: {}", params);
return params.toArray(new String[0]);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\TencentSms.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static String getWatermarkFont() {
return WATERMARK_FONT;
}
public static void setWatermarkFontValue(String watermarkFont) {
WATERMARK_FONT = watermarkFont;
}
@Value("${watermark.font:微软雅黑}")
public void setWatermarkFont(String watermarkFont) {
setWatermarkFontValue(watermarkFont);
}
public static String getWatermarkFontsize() {
return WATERMARK_FONTSIZE;
}
public static void setWatermarkFontsizeValue(String watermarkFontsize) {
WATERMARK_FONTSIZE = watermarkFontsize;
}
@Value("${watermark.fontsize:18px}")
public void setWatermarkFontsize(String watermarkFontsize) {
setWatermarkFontsizeValue(watermarkFontsize);
}
public static String getWatermarkColor() {
return WATERMARK_COLOR;
}
public static void setWatermarkColorValue(String watermarkColor) {
WATERMARK_COLOR = watermarkColor;
}
@Value("${watermark.color:black}")
public void setWatermarkColor(String watermarkColor) {
setWatermarkColorValue(watermarkColor);
}
public static String getWatermarkAlpha() {
return WATERMARK_ALPHA;
}
public static void setWatermarkAlphaValue(String watermarkAlpha) {
WATERMARK_ALPHA = watermarkAlpha;
}
@Value("${watermark.alpha:0.2}")
public void setWatermarkAlpha(String watermarkAlpha) {
setWatermarkAlphaValue(watermarkAlpha);
}
public static String getWatermarkWidth() {
return WATERMARK_WIDTH;
}
public static void setWatermarkWidthValue(String watermarkWidth) {
WATERMARK_WIDTH = watermarkWidth;
}
@Value("${watermark.width:240}")
public void setWatermarkWidth(String watermarkWidth) {
WATERMARK_WIDTH = watermarkWidth;
} | public static String getWatermarkHeight() {
return WATERMARK_HEIGHT;
}
public static void setWatermarkHeightValue(String watermarkHeight) {
WATERMARK_HEIGHT = watermarkHeight;
}
@Value("${watermark.height:80}")
public void setWatermarkHeight(String watermarkHeight) {
WATERMARK_HEIGHT = watermarkHeight;
}
public static String getWatermarkAngle() {
return WATERMARK_ANGLE;
}
public static void setWatermarkAngleValue(String watermarkAngle) {
WATERMARK_ANGLE = watermarkAngle;
}
@Value("${watermark.angle:10}")
public void setWatermarkAngle(String watermarkAngle) {
WATERMARK_ANGLE = watermarkAngle;
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\config\WatermarkConfigConstants.java | 2 |
请完成以下Java代码 | protected Task getTaskById(String id, boolean withCommentAttachmentInfo) {
if (withCommentAttachmentInfo) {
return engine.getTaskService().createTaskQuery().taskId(id).withCommentAttachmentInfo().initializeFormKeys().singleResult();
}
else{
return engine.getTaskService().createTaskQuery().taskId(id).initializeFormKeys().singleResult();
}
}
protected String getTaskFormMediaType(String taskId) {
Task task = engine.getTaskService().createTaskQuery().initializeFormKeys().taskId(taskId).singleResult();
ensureNotNull("No task found for taskId '" + taskId + "'", "task", task);
String formKey = task.getFormKey();
if(formKey != null) {
return ContentTypeUtil.getFormContentType(formKey);
} else if(task.getCamundaFormRef() != null) {
return ContentTypeUtil.getFormContentType(task.getCamundaFormRef());
}
return MediaType.APPLICATION_XHTML_XML;
}
protected <V extends Object> V runWithoutAuthorization(Supplier<V> action) { | IdentityService identityService = engine.getIdentityService();
Authentication currentAuthentication = identityService.getCurrentAuthentication();
try {
identityService.clearAuthentication();
return action.get();
} catch (Exception e) {
throw e;
} finally {
identityService.setAuthentication(currentAuthentication);
}
}
private Map<String, VariableValueDto> getTaskVariables(boolean withTaskVariablesInReturn) {
VariableResource variableResource;
if (withTaskVariablesInReturn) {
variableResource = this.getVariables();
} else {
variableResource = this.getLocalVariables();
}
return variableResource.getVariables(true);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\task\impl\TaskResourceImpl.java | 1 |
请完成以下Java代码 | class DunningDocDocumentLocationAdapter implements IDocumentLocationAdapter
{
private final I_C_DunningDoc delegate;
public DunningDocDocumentLocationAdapter(@NonNull final I_C_DunningDoc delegate)
{
this.delegate = delegate;
}
@Override
public int getC_BPartner_ID()
{
return delegate.getC_BPartner_ID();
}
@Override
public void setC_BPartner_ID(final int C_BPartner_ID)
{
delegate.setC_BPartner_ID(C_BPartner_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return delegate.getC_BPartner_Location_ID();
}
@Override
public void setC_BPartner_Location_ID(final int C_BPartner_Location_ID)
{
delegate.setC_BPartner_Location_ID(C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_Value_ID()
{
return -1;
}
@Override | public void setC_BPartner_Location_Value_ID(final int C_BPartner_Location_Value_ID)
{
}
@Override
public int getAD_User_ID()
{
return delegate.getC_Dunning_Contact_ID();
}
@Override
public void setAD_User_ID(final int AD_User_ID)
{
delegate.setC_Dunning_Contact_ID(AD_User_ID);
}
@Override
public String getBPartnerAddress()
{
return delegate.getBPartnerAddress();
}
@Override
public void setBPartnerAddress(String address)
{
delegate.setBPartnerAddress(address);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningDocDocumentLocationAdapter.java | 1 |
请完成以下Java代码 | public void setRootId (final @Nullable java.lang.String RootId)
{
set_Value (COLUMNNAME_RootId, RootId);
}
@Override
public java.lang.String getRootId()
{
return get_ValueAsString(COLUMNNAME_RootId);
}
@Override
public void setSalesLineId (final @Nullable java.lang.String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
@Override
public java.lang.String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
} | @Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable java.lang.String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public java.lang.String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaOrder.java | 1 |
请完成以下Java代码 | public class CombiningByteArrays {
public byte[] combineArraysUsingArrayCopy(byte[] first, byte[] second) {
byte[] combined = new byte[first.length + second.length];
System.arraycopy(first, 0, combined, 0, first.length);
System.arraycopy(second, 0, combined, first.length, second.length);
return combined;
}
public byte[] combineArraysUsingByteBuffer(byte[] first, byte[] second, byte[] third) {
byte[] combined = new byte[first.length + second.length + third.length];
ByteBuffer buffer = ByteBuffer.wrap(combined);
buffer.put(first);
buffer.put(second);
buffer.put(third);
return buffer.array();
}
public byte[] combineArraysUsingCustomMethod(byte[] first, byte[] second) { | byte[] combined = new byte[first.length + second.length];
for (int i = 0; i < combined.length; ++i) {
combined[i] = i < first.length ? first[i] : second[i - first.length];
}
return combined;
}
public byte[] combineArraysUsingGuava(byte[] first, byte[] second, byte[] third) {
byte[] combined = Bytes.concat(first, second, third);
return combined;
}
public byte[] combineArraysUsingApacheCommons(byte[] first, byte[] second) {
byte[] combined = ArrayUtils.addAll(first, second);
return combined;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\arrayconcat\CombiningByteArrays.java | 1 |
请完成以下Java代码 | public FactLineBuilder projectId(@Nullable final ProjectId projectId)
{
assertNotBuild();
this.projectId = projectId;
return this;
}
public FactLineBuilder campaignId(final int campaignId)
{
assertNotBuild();
this.campaignId = campaignId;
return this;
}
public FactLineBuilder fromLocation(final Optional<LocationId> optionalLocationId)
{
optionalLocationId.ifPresent(locationId -> this.fromLocationId = locationId);
return this;
}
public FactLineBuilder fromLocationOfBPartner(@Nullable final BPartnerLocationId bpartnerLocationId)
{
return fromLocation(getServices().getLocationId(bpartnerLocationId));
}
public FactLineBuilder fromLocationOfLocator(final int locatorRepoId)
{
return fromLocation(getServices().getLocationIdByLocatorRepoId(locatorRepoId));
}
public FactLineBuilder fromLocationOfLocator(@Nullable final LocatorId locatorId)
{
return fromLocationOfLocator(locatorId != null ? locatorId.getRepoId() : -1);
}
public FactLineBuilder toLocation(final Optional<LocationId> optionalLocationId)
{
optionalLocationId.ifPresent(locationId -> this.toLocationId = locationId);
return this;
}
public FactLineBuilder toLocationOfBPartner(@Nullable final BPartnerLocationId bpartnerLocationId)
{
return toLocation(getServices().getLocationId(bpartnerLocationId));
}
public FactLineBuilder toLocationOfLocator(final int locatorRepoId)
{
return toLocation(getServices().getLocationIdByLocatorRepoId(locatorRepoId));
}
public FactLineBuilder costElement(@Nullable final CostElementId costElementId)
{
assertNotBuild();
this.costElementId = costElementId;
return this;
}
public FactLineBuilder costElement(@Nullable final CostElement costElement)
{ | return costElement(costElement != null ? costElement.getId() : null);
}
public FactLineBuilder description(@Nullable final String description)
{
assertNotBuild();
this.description = StringUtils.trimBlankToOptional(description);
return this;
}
public FactLineBuilder additionalDescription(@Nullable final String additionalDescription)
{
assertNotBuild();
this.additionalDescription = StringUtils.trimBlankToNull(additionalDescription);
return this;
}
public FactLineBuilder openItemKey(@Nullable FAOpenItemTrxInfo openItemTrxInfo)
{
assertNotBuild();
this.openItemTrxInfo = openItemTrxInfo;
return this;
}
public FactLineBuilder productId(@Nullable ProductId productId)
{
assertNotBuild();
this.productId = Optional.ofNullable(productId);
return this;
}
public FactLineBuilder userElementString1(@Nullable final String userElementString1)
{
assertNotBuild();
this.userElementString1 = StringUtils.trimBlankToOptional(userElementString1);
return this;
}
public FactLineBuilder salesOrderId(@Nullable final OrderId salesOrderId)
{
assertNotBuild();
this.salesOrderId = Optional.ofNullable(salesOrderId);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\FactLineBuilder.java | 1 |
请完成以下Java代码 | public static CmmnEngine getDefaultCmmnEngine() {
return getCmmnEngine(NAME_DEFAULT);
}
/**
* Obtain a cmmn engine by name.
*
* @param cmmnEngineName
* is the name of the cmmn engine or null for the default cmmn engine.
*/
public static CmmnEngine getCmmnEngine(String cmmnEngineName) {
if (!isInitialized()) {
init();
}
return cmmnEngines.get(cmmnEngineName);
}
/**
* retries to initialize a cmmn engine that previously failed.
*/
public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initCmmnEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to cmmn engine to application clients in a managed server environment.
*/
public static Map<String, CmmnEngine> getCmmnEngines() {
return cmmnEngines;
}
/**
* closes all cmmn engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines);
cmmnEngines = new HashMap<>();
for (String cmmnEngineName : engines.keySet()) { | CmmnEngine cmmnEngine = engines.get(cmmnEngineName);
try {
cmmnEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e);
}
}
cmmnEngineInfosByName.clear();
cmmnEngineInfosByResourceUrl.clear();
cmmnEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
CmmnEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java | 1 |
请完成以下Java代码 | public class StockFilters
{
public static IQuery<I_MD_Stock> createStockQueryFor(@NonNull final DocumentFilterList filters)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_MD_Stock> queryBuilder = queryBL
.createQueryBuilder(I_MD_Stock.class)
.addOnlyActiveRecordsFilter()
.addCompareFilter(I_MD_Stock.COLUMN_QtyOnHand, Operator.GREATER, ZERO);
augmentQueryBuilder(queryBuilder, ProductFilterUtil.extractProductFilterVO(filters));
// note: need to afford loading *all* MD_Stock records for the material cockpit; afaik there isn't a product-related restriction there.
// it's OK because they are aggregated on product, locator and attributesKey, so we won't have a million of them | return queryBuilder.create();
}
private static boolean augmentQueryBuilder(final IQueryBuilder<I_MD_Stock> queryBuilder, final ProductFilterVO productFilterVO)
{
final IQuery<I_M_Product> productQuery = ProductFilterUtil.createProductQueryOrNull(productFilterVO);
if (productQuery == null)
{
return false;
}
queryBuilder.addInSubQueryFilter(I_MD_Stock.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_M_Product_ID, productQuery);
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\filters\StockFilters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void customize(LDAPConfiguration configuration) {
configuration.setUserIdAttribute(getUserId());
configuration.setUserFirstNameAttribute(getFirstName());
configuration.setUserLastNameAttribute(getLastName());
configuration.setUserEmailAttribute(getEmail());
configuration.setGroupIdAttribute(getGroupId());
configuration.setGroupNameAttribute(getGroupName());
configuration.setGroupTypeAttribute(getGroupType());
}
}
public static class Cache {
/**
* Allows to set the size of the {@link org.flowable.ldap.LDAPGroupCache}. This is an LRU cache that caches groups for users and thus avoids hitting
* the LDAP system each time the groups of a user needs to be known.
* <p>
* The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done.
* <p>
* Note that the group cache is instantiated on the {@link org.flowable.ldap.LDAPIdentityServiceImpl}. As such, if you have a custom implementation of
* the {@link org.flowable.ldap.LDAPIdentityServiceImpl}, do not forget to add the group cache functionality.
*/
private int groupSize = -1;
/**
* Sets the expiration time of the {@link org.flowable.ldap.LDAPGroupCache} in milliseconds. When groups for a specific user are fetched, and if the
* group cache exists (see {@link #groupSize}), the
* groups will be stored in this cache for the time set in this property. ie. when the groups were fetched at 00:00 and the expiration time is 30 mins, any fetch of the groups for that user after
* 00:30 will not come from the cache, but do a fetch again from the LDAP system. Likewise, everything group fetch for that user done between 00:00 - 00:30 will come from the cache.
* <p>
* By default set to one hour.
*/
//TODO once we move to Boot 2.0 we can use Duration as a parameter’
private long groupExpiration = Duration.of(1, ChronoUnit.HOURS).toMillis();
public int getGroupSize() {
return groupSize;
} | public void setGroupSize(int groupSize) {
this.groupSize = groupSize;
}
public long getGroupExpiration() {
return groupExpiration;
}
public void setGroupExpiration(int groupExpiration) {
this.groupExpiration = groupExpiration;
}
public void customize(LDAPConfiguration configuration) {
configuration.setGroupCacheSize(getGroupSize());
configuration.setGroupCacheExpirationTime(getGroupExpiration());
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ldap\FlowableLdapProperties.java | 2 |
请完成以下Java代码 | private LocalDate computeNextDailyInvoiceDate(@NonNull final LocalDate deliveryDate, final int offset)
{
return deliveryDate.plus(offset, ChronoUnit.DAYS);
}
private LocalDate computeNextWeeklyInvoiceDate(@NonNull final LocalDate deliveryDate, final int offset)
{
final LocalDate dateToInvoice;
final LocalDate nextDateWithInvoiceWeekDay = deliveryDate.with(nextOrSame(getInvoiceDayOfWeek()));
if (!nextDateWithInvoiceWeekDay.isAfter(deliveryDate))
{
dateToInvoice = nextDateWithInvoiceWeekDay.plus(1 + offset, ChronoUnit.WEEKS);
}
else
{
dateToInvoice = nextDateWithInvoiceWeekDay.plus(offset, ChronoUnit.WEEKS);
}
return dateToInvoice;
}
private LocalDate computeNextTwiceMonthlyInvoiceDate(@NonNull final LocalDate deliveryDate)
{
final LocalDate dateToInvoice;
final LocalDate middleDayOfMonth = deliveryDate.withDayOfMonth(15);
// tasks 08484, 08869
if (deliveryDate.isAfter(middleDayOfMonth))
{
dateToInvoice = deliveryDate.with(lastDayOfMonth()); | }
else
{
dateToInvoice = middleDayOfMonth;
}
return dateToInvoice;
}
private LocalDate computeNextMonthlyInvoiceDate(
@NonNull final LocalDate deliveryDate,
final int offset)
{
final LocalDate dateToInvoice;
final int invoiceDayOfMonthToUse = Integer.min(deliveryDate.lengthOfMonth(), getInvoiceDayOfMonth());
final LocalDate deliveryDateWithDayOfMonth = deliveryDate.withDayOfMonth(invoiceDayOfMonthToUse);
if (!deliveryDateWithDayOfMonth.isAfter(deliveryDate))
{
dateToInvoice = deliveryDateWithDayOfMonth.plus(1 + offset, ChronoUnit.MONTHS);
}
else
{
dateToInvoice = deliveryDateWithDayOfMonth.plus(offset, ChronoUnit.MONTHS);
}
return dateToInvoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\InvoiceSchedule.java | 1 |
请完成以下Java代码 | public class ScriptInfoParser extends BaseChildElementParser {
@Override
public String getElementName() {
return ELEMENT_SCRIPT;
}
@Override
public boolean accepts(BaseElement element) {
return element instanceof HasScriptInfo;
}
@Override
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model) throws Exception {
if (!accepts(parentElement)) {
return;
}
if (xtr.isStartElement() && BpmnXMLConstants.ELEMENT_SCRIPT.equals(xtr.getLocalName())) { | ScriptInfo script = new ScriptInfo();
BpmnXMLUtil.addXMLLocation(script, xtr);
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_SCRIPT_LANGUAGE))) {
script.setLanguage(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_SCRIPT_LANGUAGE));
}
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_SCRIPT_RESULTVARIABLE))) {
script.setResultVariable(xtr.getAttributeValue(null, BpmnXMLConstants.ATTRIBUTE_SCRIPT_RESULTVARIABLE));
}
String elementText = xtr.getElementText();
if (StringUtils.isNotEmpty(elementText)) {
script.setScript(StringUtils.trim(elementText));
}
if (parentElement instanceof HasScriptInfo) {
((HasScriptInfo) parentElement).setScriptInfo(script);
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\child\ScriptInfoParser.java | 1 |
请完成以下Java代码 | public Date getCompletedAfter() {
return completedAfter;
}
public Date getTerminatedBefore() {
return terminatedBefore;
}
public Date getTerminatedAfter() {
return terminatedAfter;
}
public Date getOccurredBefore() {
return occurredBefore;
}
public Date getOccurredAfter() {
return occurredAfter;
}
public Date getExitBefore() {
return exitBefore;
}
public Date getExitAfter() {
return exitAfter;
}
public Date getEndedBefore() {
return endedBefore;
}
public Date getEndedAfter() {
return endedAfter;
}
public String getStartUserId() {
return startUserId;
}
public String getAssignee() {
return assignee;
}
public String getCompletedBy() {
return completedBy;
}
public String getReferenceId() {
return referenceId;
}
public String getReferenceType() {
return referenceType;
}
public boolean isEnded() {
return ended;
}
public boolean isNotEnded() {
return notEnded;
}
public String getEntryCriterionId() {
return entryCriterionId;
}
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 class ExceptionUtil {
@SuppressWarnings("unchecked")
public static <T extends Exception> T lookupException(Throwable source, Class<T> clazz) {
Exception e = lookupExceptionInCause(source, clazz);
if (e != null) {
return (T) e;
} else {
return null;
}
}
public static Exception lookupExceptionInCause(Throwable source, Class<? extends Exception>... clazzes) {
while (source != null) {
for (Class<? extends Exception> clazz : clazzes) {
if (clazz.isAssignableFrom(source.getClass())) {
return (Exception) source;
}
}
source = source.getCause();
}
return null;
}
public static String toString(Exception e, EntityId componentId, boolean stackTraceEnabled) {
Exception exception = lookupExceptionInCause(e, ScriptException.class, JsonParseException.class);
if (exception != null && StringUtils.isNotEmpty(exception.getMessage())) {
return exception.getMessage(); | } else {
if (stackTraceEnabled) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return sw.toString();
} else {
log.debug("[{}] Unknown error during message processing", componentId, e);
return "Please contact system administrator";
}
}
}
public static String getMessage(Throwable t) {
String message = t.getMessage();
if (StringUtils.isNotEmpty(message)) {
return message;
} else {
return t.getClass().getSimpleName();
}
}
} | repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\ExceptionUtil.java | 1 |
请完成以下Java代码 | public void setProcessDefinitionIdIn(String[] processDefinitionIdIn) {
this.processDefinitionIdIn = processDefinitionIdIn;
}
@CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class)
public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) {
this.processDefinitionKeyIn = processDefinitionKeyIn;
}
@CamundaQueryParam(value = "startedAfter", converter = DateConverter.class)
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
@CamundaQueryParam(value = "startedBefore", converter = DateConverter.class)
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
@Override
protected HistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricProcessInstanceReport();
} | @Override
protected void applyFilters(HistoricProcessInstanceReport reportQuery) {
if (processDefinitionIdIn != null && processDefinitionIdIn.length > 0) {
reportQuery.processDefinitionIdIn(processDefinitionIdIn);
}
if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) {
reportQuery.processDefinitionKeyIn(processDefinitionKeyIn);
}
if (startedAfter != null) {
reportQuery.startedAfter(startedAfter);
}
if (startedBefore != null) {
reportQuery.startedBefore(startedBefore);
}
if (!REPORT_TYPE_DURATION.equals(reportType)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Unknown report type " + reportType);
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricProcessInstanceReportDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GODraftDeliveryOrderCreator implements DraftDeliveryOrderCreator
{
private static final BigDecimal DEFAULT_PackageWeightInKg = BigDecimal.ONE;
@Override
public ShipperGatewayId getShipperGatewayId()
{
return GOConstants.SHIPPER_GATEWAY_ID;
}
@Override
public @NotNull DeliveryOrder createDraftDeliveryOrder(@NonNull final CreateDraftDeliveryOrderRequest request)
{
final DeliveryOrderKey deliveryOrderKey = request.getDeliveryOrderKey();
final Set<PackageId> mpackageIds = request.getPackageIds();
final IBPartnerOrgBL bpartnerOrgBL = Services.get(IBPartnerOrgBL.class);
final I_C_BPartner pickupFromBPartner = bpartnerOrgBL.retrieveLinkedBPartner(deliveryOrderKey.getFromOrgId());
final I_C_Location pickupFromLocation = bpartnerOrgBL.retrieveOrgLocation(OrgId.ofRepoId(deliveryOrderKey.getFromOrgId()));
final LocalDate pickupDate = deliveryOrderKey.getPickupDate();
final int deliverToBPartnerId = deliveryOrderKey.getDeliverToBPartnerId();
final I_C_BPartner deliverToBPartner = load(deliverToBPartnerId, I_C_BPartner.class);
final int deliverToBPartnerLocationId = deliveryOrderKey.getDeliverToBPartnerLocationId();
final I_C_BPartner_Location deliverToBPLocation = load(deliverToBPartnerLocationId, I_C_BPartner_Location.class);
final I_C_Location deliverToLocation = deliverToBPLocation.getC_Location();
final GoDeliveryOrderData goDeliveryOrderData = GoDeliveryOrderData.builder()
.receiptConfirmationPhoneNumber(null)
.paidMode(GOPaidMode.Prepaid)
.selfPickup(GOSelfPickup.Delivery)
.selfDelivery(GOSelfDelivery.Pickup)
.build();
return DeliveryOrder.builder()
.shipperId(deliveryOrderKey.getShipperId())
.shipperTransportationId(deliveryOrderKey.getShipperTransportationId()) | //
.shipperProduct(GOShipperProduct.Overnight)
.customDeliveryData(goDeliveryOrderData)
//
// Pickup
.pickupAddress(DeliveryOrderUtil.prepareAddressFromLocationBP(pickupFromLocation, pickupFromBPartner)
.build())
.pickupDate(PickupDate.builder()
.date(pickupDate)
.build())
//
// Delivery
.deliveryAddress(DeliveryOrderUtil.prepareAddressFromLocationBP(deliverToLocation,deliverToBPartner)
.companyDepartment("-") // N/A
.bpartnerId(deliverToBPartnerId)
.build())
//
// Delivery content
.deliveryPosition(DeliveryPosition.builder()
.numberOfPackages(mpackageIds.size())
.packageIds(mpackageIds)
.grossWeightKg(request.getAllPackagesGrossWeightInKg(DEFAULT_PackageWeightInKg))
.content(request.getAllPackagesContentDescription().orElse("-"))
.build())
// .customerReference(null)
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\GODraftDeliveryOrderCreator.java | 2 |
请完成以下Java代码 | public class X_K_Source extends PO implements I_K_Source, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_K_Source (Properties ctx, int K_Source_ID, String trxName)
{
super (ctx, K_Source_ID, trxName);
/** if (K_Source_ID == 0)
{
setK_Source_ID (0);
setName (null);
} */
}
/** Load Constructor */
public X_K_Source (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_K_Source[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description URL.
@param DescriptionURL
URL for the description
*/
public void setDescriptionURL (String DescriptionURL)
{
set_Value (COLUMNNAME_DescriptionURL, DescriptionURL);
}
/** Get Description URL.
@return URL for the description
*/
public String getDescriptionURL ()
{
return (String)get_Value(COLUMNNAME_DescriptionURL);
}
/** Set Knowledge Source.
@param K_Source_ID
Source of a Knowledge Entry
*/
public void setK_Source_ID (int K_Source_ID) | {
if (K_Source_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Source_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Source_ID, Integer.valueOf(K_Source_ID));
}
/** Get Knowledge Source.
@return Source of a Knowledge Entry
*/
public int getK_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Source_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Source.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.