instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public class TriggerCmd extends NeedsActiveExecutionCmd<Object> {
private static final long serialVersionUID = 1L;
protected Map<String, Object> processVariables;
protected Map<String, Object> transientVariables;
private Map<String, Object> availableVariables;
private VariablesPropagator variablesPropagator;
public TriggerCmd(String executionId, Map<String, Object> processVariables) {
super(executionId);
this.processVariables = processVariables;
}
public TriggerCmd(
String executionId,
Map<String, Object> processVariables,
Map<String, Object> transientVariables
) {
this(executionId, processVariables);
this.transientVariables = transientVariables;
}
public TriggerCmd(
String executionId,
Map<String, Object> availableVariables,
VariablesPropagator variablesPropagator
) {
super(executionId);
this.availableVariables = availableVariables;
this.variablesPropagator = variablesPropagator;
}
protected Object execute(CommandContext commandContext, ExecutionEntity execution) {
if (processVariables != null) {
|
execution.setVariables(processVariables);
}
if (transientVariables != null) {
execution.setTransientVariables(transientVariables);
}
if (variablesPropagator != null) {
variablesPropagator.propagate(execution, availableVariables);
}
Context.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createActivitiySignalledEvent(execution, null, null));
Context.getAgenda().planTriggerExecutionOperation(execution);
return null;
}
@Override
protected String getSuspendedExceptionMessage() {
return "Cannot trigger an execution that is suspended";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\TriggerCmd.java
| 1
|
请完成以下Java代码
|
public void setVariablesLocal(Map<String, ? extends Object> variables) {
wrappedScope.setVariablesLocal(variables);
}
public boolean hasVariables() {
return hasVariablesLocal();
}
public boolean hasVariablesLocal() {
return wrappedScope.hasVariablesLocal();
}
public boolean hasVariable(String variableName) {
return hasVariableLocal(variableName);
}
public boolean hasVariableLocal(String variableName) {
return wrappedScope.hasVariableLocal(variableName);
}
public void removeVariable(String variableName) {
removeVariableLocal(variableName);
}
public void removeVariableLocal(String variableName) {
wrappedScope.removeVariableLocal(variableName);
}
public void removeVariables(Collection<String> variableNames) {
|
removeVariablesLocal(variableNames);
}
public void removeVariablesLocal(Collection<String> variableNames) {
wrappedScope.removeVariablesLocal(variableNames);
}
public void removeVariables() {
removeVariablesLocal();
}
public void removeVariablesLocal() {
wrappedScope.removeVariablesLocal();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableScopeLocalAdapter.java
| 1
|
请完成以下Java代码
|
private MRequisition getParent()
{
if (m_parent == null)
m_parent = new MRequisition(getCtx(), getM_Requisition_ID(), get_TrxName());
return m_parent;
} // getParent
private RequisitionService getRequisitionService()
{
return Adempiere.getBean(RequisitionService.class);
}
@Override
public I_M_Requisition getM_Requisition()
{
return getParent();
}
public void setPrice()
{
final BigDecimal price = getRequisitionService().computePrice(getParent(), this);
if (price != null)
{
setPriceActual(price);
}
}
@Override
protected boolean beforeSave(boolean newRecord)
{
if (newRecord && getParent().isComplete())
{
throw new AdempiereException("@ParentComplete@ @M_RequisitionLine_ID@");
}
if (getLine() == 0)
{
String sql = "SELECT COALESCE(MAX(Line),0)+10 FROM M_RequisitionLine WHERE M_Requisition_ID=?";
int line = DB.getSQLValueEx(get_TrxName(), sql, getM_Requisition_ID());
setLine(line);
}
// Product & ASI - Charge
if (getM_Product_ID() > 0 && getC_Charge_ID() > 0)
{
setC_Charge_ID(0);
}
if (getM_AttributeSetInstance_ID() > 0 && getC_Charge_ID() > 0)
{
setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId());
}
// Product UOM
if (getM_Product_ID() > 0 && getC_UOM_ID() <= 0)
{
final UomId productUomId = Services.get(IProductBL.class).getStockUOMId(getM_Product_ID());
setC_UOM_ID(productUomId.getRepoId());
|
}
//
if (getPriceActual().signum() == 0)
{
setPrice();
}
getRequisitionService().updateLineNetAmt(this);
return true;
} // beforeSave
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
return success;
updateHeader();
return true;
} // afterSave
@Override
protected boolean afterDelete(boolean success)
{
if (!success)
return success;
updateHeader();
return true;
} // afterDelete
private void updateHeader()
{
String sql = "UPDATE M_Requisition r"
+ " SET TotalLines="
+ "(SELECT COALESCE(SUM(LineNetAmt),0) FROM M_RequisitionLine rl "
+ "WHERE r.M_Requisition_ID=rl.M_Requisition_ID) "
+ "WHERE M_Requisition_ID=?";
DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { getM_Requisition_ID() }, ITrx.TRXNAME_ThreadInherited);
m_parent = null;
}
} // MRequisitionLine
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequisitionLine.java
| 1
|
请完成以下Java代码
|
private final List<I_C_OrderLine> getOrderLines()
{
return _orderLines;
}
public OrderCheckupBuilder setWarehouseId(@Nullable final WarehouseId warehouseId)
{
this._warehouseId = warehouseId;
return this;
}
private WarehouseId getWarehouseId()
{
return _warehouseId;
}
public OrderCheckupBuilder setPlantId(ResourceId plantId)
{
this._plantId = plantId;
return this;
}
private ResourceId getPlantId()
{
return _plantId;
}
public OrderCheckupBuilder setReponsibleUserId(UserId reponsibleUserId)
{
this._reponsibleUserId = reponsibleUserId;
return this;
}
private UserId getReponsibleUserId()
|
{
return _reponsibleUserId;
}
public OrderCheckupBuilder setDocumentType(String documentType)
{
this._documentType = documentType;
return this;
}
private String getDocumentType()
{
Check.assumeNotEmpty(_documentType, "documentType not empty");
return _documentType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\ordercheckup\impl\OrderCheckupBuilder.java
| 1
|
请完成以下Java代码
|
public class UnlockExclusiveJobCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(UnlockExclusiveJobCmd.class);
protected Job job;
public UnlockExclusiveJobCmd(Job job) {
this.job = job;
}
public Object execute(CommandContext commandContext) {
if (job == null) {
throw new ActivitiIllegalArgumentException("job is null");
}
if (log.isDebugEnabled()) {
log.debug("Unlocking exclusive job {}", job.getId());
|
}
if (job.isExclusive()) {
if (job.getProcessInstanceId() != null) {
ExecutionEntity execution = commandContext
.getExecutionEntityManager()
.findById(job.getProcessInstanceId());
if (execution != null) {
commandContext.getExecutionEntityManager().clearProcessInstanceLockTime(execution.getId());
}
}
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\UnlockExclusiveJobCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setupResolver(ApplicationContext applicationContext, AmazonS3 amazonS3) {
this.resourcePatternResolver = new PathMatchingSimpleStorageResourcePatternResolver(amazonS3, applicationContext);
}
public void downloadS3Object(String s3Url) throws IOException {
Resource resource = resourceLoader.getResource(s3Url);
File downloadedS3Object = new File(resource.getFilename());
try (InputStream inputStream = resource.getInputStream()) {
Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
public void uploadFileToS3(File file, String s3Url) throws IOException {
WritableResource resource = (WritableResource) resourceLoader.getResource(s3Url);
try (OutputStream outputStream = resource.getOutputStream()) {
|
Files.copy(file.toPath(), outputStream);
}
}
public void downloadMultipleS3Objects(String s3UrlPattern) throws IOException {
Resource[] allFileMatchingPatten = this.resourcePatternResolver.getResources(s3UrlPattern);
for (Resource resource : allFileMatchingPatten) {
String fileName = resource.getFilename();
fileName = fileName.substring(0, fileName.lastIndexOf("/") + 1);
File downloadedS3Object = new File(fileName);
try (InputStream inputStream = resource.getInputStream()) {
Files.copy(inputStream, downloadedS3Object.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws\src\main\java\com\baeldung\spring\cloud\aws\s3\SpringCloudS3.java
| 2
|
请完成以下Java代码
|
public @NonNull ClientId getClientId() {return node.getClientId();}
public @NonNull WFNodeAction getAction() {return node.getAction();}
public @NonNull ITranslatableString getName() {return node.getName();}
@NonNull
public ITranslatableString getDescription() {return node.getDescription();}
@NonNull
public ITranslatableString getHelp() {return node.getHelp();}
public @NonNull WFNodeJoinType getJoinType() {return node.getJoinType();}
public int getXPosition() {return xPosition != null ? xPosition : node.getXPosition();}
public void setXPosition(final int x) { this.xPosition = x; }
public int getYPosition() {return yPosition != null ? yPosition : node.getYPosition();}
public void setYPosition(final int y) { this.yPosition = y; }
public @NonNull ImmutableList<WorkflowNodeTransitionModel> getTransitions(@NonNull final ClientId clientId)
|
{
return node.getTransitions(clientId)
.stream()
.map(transition -> new WorkflowNodeTransitionModel(workflowModel, node.getId(), transition))
.collect(ImmutableList.toImmutableList());
}
public void saveEx()
{
workflowDAO.changeNodeLayout(WFNodeLayoutChangeRequest.builder()
.nodeId(getId())
.xPosition(getXPosition())
.yPosition(getYPosition())
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WorkflowNodeModel.java
| 1
|
请完成以下Java代码
|
private ProductId getBOMProductId(ICablesOrderLineQuickInput quickInputModel)
{
final ProductId plugProduct1Id = ProductId.ofRepoId(quickInputModel.getPlug1_Product_ID());
final ProductId plugProduct2Id = ProductId.ofRepoId(quickInputModel.getPlug2_Product_ID());
final ProductId cableProductId = ProductId.ofRepoId(quickInputModel.getCable_Product_ID());
final IProductBOMDAO productBOMsRepo = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOM> boms = productBOMsRepo.retrieveBOMsContainingExactProducts(plugProduct1Id.getRepoId(), cableProductId.getRepoId(), plugProduct2Id.getRepoId());
if (boms.isEmpty())
{
throw new AdempiereException("@NotFound@ @PP_Product_BOM_ID@");
}
else if (boms.size() > 1)
{
final String bomValues = boms.stream().map(I_PP_Product_BOM::getValue).collect(Collectors.joining(", "));
throw new AdempiereException("More than one BOMs found: " + bomValues);
|
}
else
{
final I_PP_Product_BOM bom = boms.get(0);
return ProductId.ofRepoId(bom.getM_Product_ID());
}
}
private boolean isCableProduct(final ICablesOrderLineQuickInput quickInputModel)
{
return quickInputModel.getPlug1_Product_ID() > 0
&& quickInputModel.getCable_Product_ID() > 0
&& quickInputModel.getPlug2_Product_ID() > 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\vertical\cables\webui\quickinput\CableSalesOrderLineQuickInputProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("discUser").password("{noop}discPassword").roles("SYSTEM");
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.ALWAYS))
.authorizeHttpRequests(authorizeRequests ->
authorizeRequests
.requestMatchers(HttpMethod.GET, "/eureka/**").hasRole("SYSTEM")
.requestMatchers(HttpMethod.POST, "/eureka/**").hasRole("SYSTEM")
.requestMatchers(HttpMethod.PUT, "/eureka/**").hasRole("SYSTEM")
.requestMatchers(HttpMethod.DELETE, "/eureka/**").hasRole("SYSTEM")
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
|
@Configuration
// no order tag means this is the last security filter to be evaluated
public static class AdminSecurityConfig {
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
}
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)).httpBasic(basic -> basic.disable()).authorizeRequests().requestMatchers(HttpMethod.GET, "/").hasRole("ADMIN").requestMatchers("/info", "/health").authenticated().anyRequest().denyAll()
.and().csrf(csrf -> csrf.disable());
}
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-bootstrap\discovery\src\main\java\com\baeldung\spring\cloud\bootstrap\discovery\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
@Override
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
|
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public String toEventMessage(String message) {
String eventMessage = message.replaceAll("\\s+", " ");
if (eventMessage.length() > 163) {
eventMessage = eventMessage.substring(0, 160) + "...";
}
return eventMessage;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", type=" + type
+ ", userId=" + userId
+ ", time=" + time
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", revision= "+ revision
+ ", removalTime=" + removalTime
+ ", action=" + action
+ ", message=" + message
+ ", fullMessage=" + fullMessage
+ ", tenantId=" + tenantId
+ "]";
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
@Override
public int getRevision() {
return revision;
}
@Override
public int getRevisionNext() {
return revision + 1;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\CommentEntity.java
| 1
|
请完成以下Java代码
|
class MigrationDataHandler implements IXMLHandler<I_AD_MigrationData>
{
private final transient Logger logger = LogManager.getLogger(getClass());
public static final String NODENAME = "Data";
/**
* Node: Column - Column Name
*/
private static final String NODE_Column = "Column";
private static final String NODE_AD_Column_ID = "AD_Column_ID";
private static final String NODE_isOldNull = "isOldNull";
private static final String NODE_oldValue = "oldValue";
private static final String NODE_isNewNull = "isNewNull";
@Override
public Node toXmlNode(Document document, I_AD_MigrationData data)
{
logger.info("Exporting data: " + data);
final I_AD_Column column = data.getAD_Column();
final Element dataNode = document.createElement(NODENAME);
dataNode.setAttribute(NODE_Column, column.getColumnName());
// TODO: handle the case when AD_Column_ID is not present in our database.
// Idea: export/import also the column name. In this way we can configure to not import if the column does not exist
dataNode.setAttribute(NODE_AD_Column_ID, Integer.toString(data.getAD_Column_ID()));
final I_AD_MigrationStep step = data.getAD_MigrationStep();
if (!X_AD_MigrationStep.ACTION_Insert.equals(step.getAction()))
{
if (data.isOldNull())
dataNode.setAttribute(NODE_isOldNull, "true");
else
dataNode.setAttribute(NODE_oldValue, data.getOldValue());
}
if (data.isNewNull() || data.getNewValue() == null)
{
dataNode.setAttribute(NODE_isNewNull, "true");
}
else
{
dataNode.appendChild(document.createTextNode(data.getNewValue()));
}
return dataNode;
}
@Override
public boolean fromXmlNode(I_AD_MigrationData data, Element element)
{
data.setColumnName(element.getAttribute(NODE_Column));
|
data.setAD_Column_ID(Integer.parseInt(element.getAttribute(NODE_AD_Column_ID)));
data.setIsOldNull("true".equals(element.getAttribute(NODE_isOldNull)));
data.setOldValue(element.getAttribute(NODE_oldValue));
data.setIsNewNull("true".equals(element.getAttribute(NODE_isNewNull)));
data.setNewValue(getText(element));
InterfaceWrapperHelper.save(data);
logger.info("Imported data: " + data);
return true;
}
// thx to http://www.java2s.com/Code/Java/XML/DOMUtilgetElementText.htm
private String getText(Element element)
{
StringBuffer buf = new StringBuffer();
NodeList list = element.getChildNodes();
boolean found = false;
for (int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
if (node.getNodeType() == Node.TEXT_NODE)
{
buf.append(node.getNodeValue());
found = true;
}
}
return found ? buf.toString() : null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\impl\MigrationDataHandler.java
| 1
|
请完成以下Java代码
|
public static final Builder builder()
{
return new Builder();
}
private final String docBaseType;
private final String docSubType;
private final boolean soTrx;
private final boolean hasChanges;
private final boolean docNoControlled;
private final String documentNo;
private DocumentNoInfo(final Builder builder)
{
super();
this.documentNo = builder.documentNo;
this.docBaseType = builder.docBaseType;
this.docSubType = builder.docSubType;
this.soTrx = builder.soTrx;
this.hasChanges = builder.hasChanges;
this.docNoControlled = builder.docNoControlled;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("documentNo", documentNo)
.add("docBaseType", docBaseType)
.add("docSubType", docSubType)
.add("IsSOTrx", soTrx)
.add("hasChanges", hasChanges)
.add("docNoControlled", docNoControlled)
.toString();
}
@Override
public String getDocBaseType()
{
return docBaseType;
}
@Override
public String getDocSubType()
{
return docSubType;
}
@Override
public boolean isSOTrx()
{
return soTrx;
}
@Override
public boolean isHasChanges()
{
return hasChanges;
}
@Override
public boolean isDocNoControlled()
{
return docNoControlled;
}
@Override
public String getDocumentNo()
{
return documentNo;
}
public static final class Builder
{
private String docBaseType;
private String docSubType;
private boolean soTrx;
private boolean hasChanges;
private boolean docNoControlled;
private String documentNo;
private Builder()
{
super();
}
|
public DocumentNoInfo build()
{
return new DocumentNoInfo(this);
}
public Builder setDocumentNo(final String documentNo)
{
this.documentNo = documentNo;
return this;
}
public Builder setDocBaseType(final String docBaseType)
{
this.docBaseType = docBaseType;
return this;
}
public Builder setDocSubType(final String docSubType)
{
this.docSubType = docSubType;
return this;
}
public Builder setHasChanges(final boolean hasChanges)
{
this.hasChanges = hasChanges;
return this;
}
public Builder setDocNoControlled(final boolean docNoControlled)
{
this.docNoControlled = docNoControlled;
return this;
}
public Builder setIsSOTrx(final boolean isSOTrx)
{
soTrx = isSOTrx;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoInfo.java
| 1
|
请完成以下Java代码
|
public int getStateCode() {
return stateCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stateCode;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
|
return false;
if (getClass() != obj.getClass())
return false;
ActivityInstanceStateImpl other = (ActivityInstanceStateImpl) obj;
if (stateCode != other.stateCode)
return false;
return true;
}
@Override
public String toString() {
return name;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\ActivityInstanceState.java
| 1
|
请完成以下Java代码
|
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastUpdatedTime() {
return lastUpdatedTime;
}
public void setLastUpdatedTime(Date lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public Date getTime() {
return getCreateTime();
}
public ByteArrayRef getByteArrayRef() {
return byteArrayRef;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
|
sb.append("HistoricVariableInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", revision=").append(revision);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricVariableInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public int getM_AttributeSetInstance_ID()
{
return AttributeSetInstanceId.toRepoId(getAsiId());
}
@Override
@Deprecated
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
setAsiId(AttributeSetInstanceId.ofRepoIdOrNull(M_AttributeSetInstance_ID));
}
@Override
@Deprecated
public int getC_BPartner_ID()
{
return BPartnerId.toRepoId(getBpartnerId());
}
@Override
@Deprecated
public void setC_BPartner_ID(final int bpartnerId)
{
|
setBpartnerId(BPartnerId.ofRepoIdOrNull(bpartnerId));
}
@Override
public Optional<BigDecimal> getQtyCUsPerTU()
{
return Optional.ofNullable(qtyCUsPerTU);
}
@Override
public void setQtyCUsPerTU(final BigDecimal qtyCUsPerTU)
{
this.qtyCUsPerTU = qtyCUsPerTU;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\PlainHUPackingAware.java
| 1
|
请完成以下Java代码
|
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsDirectEnqueue (final boolean IsDirectEnqueue)
{
set_Value (COLUMNNAME_IsDirectEnqueue, IsDirectEnqueue);
}
@Override
public boolean isDirectEnqueue()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectEnqueue);
}
@Override
public void setIsDirectProcessQueueItem (final boolean IsDirectProcessQueueItem)
{
set_Value (COLUMNNAME_IsDirectProcessQueueItem, IsDirectProcessQueueItem);
}
@Override
public boolean isDirectProcessQueueItem()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem);
}
@Override
public void setIsFileSystem (final boolean IsFileSystem)
{
set_Value (COLUMNNAME_IsFileSystem, IsFileSystem);
}
@Override
public boolean isFileSystem()
{
return get_ValueAsBoolean(COLUMNNAME_IsFileSystem);
}
@Override
public void setIsReport (final boolean IsReport)
{
set_Value (COLUMNNAME_IsReport, IsReport);
}
@Override
public boolean isReport()
|
{
return get_ValueAsBoolean(COLUMNNAME_IsReport);
}
@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);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public long getProfileThreshold(ApiUsageRecordKey key) {
return tenantProfileData.getConfiguration().getProfileThreshold(key);
}
public boolean getProfileFeatureEnabled(ApiUsageRecordKey key) {
return tenantProfileData.getConfiguration().getProfileFeatureEnabled(key);
}
public long getProfileWarnThreshold(ApiUsageRecordKey key) {
return tenantProfileData.getConfiguration().getWarnThreshold(key);
}
private Pair<ApiFeature, ApiUsageStateValue> checkStateUpdatedDueToThreshold(ApiFeature feature) {
ApiUsageStateValue featureValue = ApiUsageStateValue.ENABLED;
for (ApiUsageRecordKey recordKey : ApiUsageRecordKey.getKeys(feature)) {
long value = get(recordKey);
boolean featureEnabled = getProfileFeatureEnabled(recordKey);
ApiUsageStateValue tmpValue;
if (featureEnabled) {
long threshold = getProfileThreshold(recordKey);
long warnThreshold = getProfileWarnThreshold(recordKey);
if (threshold == 0 || value == 0 || value < warnThreshold) {
tmpValue = ApiUsageStateValue.ENABLED;
} else if (value < threshold) {
tmpValue = ApiUsageStateValue.WARNING;
} else {
tmpValue = ApiUsageStateValue.DISABLED;
}
} else {
tmpValue = ApiUsageStateValue.DISABLED;
}
featureValue = ApiUsageStateValue.toMoreRestricted(featureValue, tmpValue);
}
|
return setFeatureValue(feature, featureValue) ? Pair.of(feature, featureValue) : null;
}
public Map<ApiFeature, ApiUsageStateValue> checkStateUpdatedDueToThresholds() {
return checkStateUpdatedDueToThreshold(new HashSet<>(Arrays.asList(ApiFeature.values())));
}
public Map<ApiFeature, ApiUsageStateValue> checkStateUpdatedDueToThreshold(Set<ApiFeature> features) {
Map<ApiFeature, ApiUsageStateValue> result = new HashMap<>();
for (ApiFeature feature : features) {
Pair<ApiFeature, ApiUsageStateValue> tmp = checkStateUpdatedDueToThreshold(feature);
if (tmp != null) {
result.put(tmp.getFirst(), tmp.getSecond());
}
}
return result;
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\TenantApiUsageState.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
/**
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return USERNAME
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
/**
* @return PASSWD
*/
public String getPasswd() {
return passwd;
}
/**
* @param passwd
*/
public void setPasswd(String passwd) {
this.passwd = passwd == null ? null : passwd.trim();
}
/**
* @return CREATE_TIME
*/
public Date getCreateTime() {
return createTime;
}
|
/**
* @param createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* @return STATUS
*/
public String getStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(String status) {
this.status = status == null ? null : status.trim();
}
}
|
repos\SpringAll-master\27.Spring-Boot-Mapper-PageHelper\src\main\java\com\springboot\bean\User.java
| 1
|
请完成以下Java代码
|
long calculateIntervalMin(long reconnectIntervalMinSeconds) {
return Math.min((reconnectIntervalMinSeconds > 0 ? reconnectIntervalMinSeconds : DEFAULT_RECONNECT_INTERVAL_SEC), this.reconnectIntervalMaxSeconds);
}
@Override
synchronized public long getNextReconnectDelay() {
final long currentNanoTime = getNanoTime();
final long coolDownSpentNanos = currentNanoTime - lastDisconnectNanoTime;
lastDisconnectNanoTime = currentNanoTime;
if (isCooledDown(coolDownSpentNanos)) {
retryCount = 0;
return reconnectIntervalMinSeconds;
}
return calculateNextReconnectDelay() + calculateJitter();
}
long calculateJitter() {
return ThreadLocalRandom.current().nextInt() >= 0 ? JITTER_MAX : 0;
}
|
long calculateNextReconnectDelay() {
return Math.min(reconnectIntervalMaxSeconds, reconnectIntervalMinSeconds + calculateExp(retryCount++));
}
long calculateExp(long e) {
return 1L << Math.min(e, EXP_MAX);
}
boolean isCooledDown(long coolDownSpentNanos) {
return TimeUnit.NANOSECONDS.toSeconds(coolDownSpentNanos) > reconnectIntervalMaxSeconds + reconnectIntervalMinSeconds;
}
long getNanoTime() {
return System.nanoTime();
}
}
|
repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\ReconnectStrategyExponential.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static EncodingConfigurer withDecoded(String decoded) {
return new EncodingConfigurer(decoded);
}
static DecodingConfigurer withEncoded(String encoded) {
return new DecodingConfigurer(encoded);
}
static final class EncodingConfigurer {
private final String decoded;
private boolean deflate;
private EncodingConfigurer(String decoded) {
this.decoded = decoded;
}
EncodingConfigurer deflate(boolean deflate) {
this.deflate = deflate;
return this;
}
String encode() {
byte[] bytes = (this.deflate) ? Saml2Utils.samlDeflate(this.decoded)
: this.decoded.getBytes(StandardCharsets.UTF_8);
return Saml2Utils.samlEncode(bytes);
}
}
static final class DecodingConfigurer {
private static final Base64Checker BASE_64_CHECKER = new Base64Checker();
private final String encoded;
private boolean inflate;
private boolean requireBase64;
private DecodingConfigurer(String encoded) {
this.encoded = encoded;
}
DecodingConfigurer inflate(boolean inflate) {
this.inflate = inflate;
return this;
}
DecodingConfigurer requireBase64(boolean requireBase64) {
this.requireBase64 = requireBase64;
return this;
}
String decode() {
if (this.requireBase64) {
BASE_64_CHECKER.checkAcceptable(this.encoded);
}
byte[] bytes = Saml2Utils.samlDecode(this.encoded);
return (this.inflate) ? Saml2Utils.samlInflate(bytes) : new String(bytes, StandardCharsets.UTF_8);
}
static class Base64Checker {
private static final int[] values = genValueMapping();
Base64Checker() {
}
private static int[] genValueMapping() {
byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.getBytes(StandardCharsets.ISO_8859_1);
|
int[] values = new int[256];
Arrays.fill(values, -1);
for (int i = 0; i < alphabet.length; i++) {
values[alphabet[i] & 0xff] = i;
}
return values;
}
boolean isAcceptable(String s) {
int goodChars = 0;
int lastGoodCharVal = -1;
// count number of characters from Base64 alphabet
for (int i = 0; i < s.length(); i++) {
int val = values[0xff & s.charAt(i)];
if (val != -1) {
lastGoodCharVal = val;
goodChars++;
}
}
// in cases of an incomplete final chunk, ensure the unused bits are zero
switch (goodChars % 4) {
case 0:
return true;
case 2:
return (lastGoodCharVal & 0b1111) == 0;
case 3:
return (lastGoodCharVal & 0b11) == 0;
default:
return false;
}
}
void checkAcceptable(String ins) {
if (!isAcceptable(ins)) {
throw new IllegalArgumentException("Failed to decode SAMLResponse");
}
}
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\internal\Saml2Utils.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public T delete(Long id) {
T entity = allRules.remove(id);
if (entity != null) {
if (appRules.get(entity.getApp()) != null) {
appRules.get(entity.getApp()).remove(id);
}
machineRules.get(MachineInfo.of(entity.getApp(), entity.getIp(), entity.getPort())).remove(id);
}
return entity;
}
@Override
public T findById(Long id) {
return allRules.get(id);
}
@Override
public List<T> findAllByMachine(MachineInfo machineInfo) {
Map<Long, T> entities = machineRules.get(machineInfo);
if (entities == null) {
return new ArrayList<>();
}
return new ArrayList<>(entities.values());
}
@Override
public List<T> findAllByApp(String appName) {
AssertUtil.notEmpty(appName, "appName cannot be empty");
Map<Long, T> entities = appRules.get(appName);
if (entities == null) {
return new ArrayList<>();
}
return new ArrayList<>(entities.values());
|
}
public void clearAll() {
allRules.clear();
machineRules.clear();
appRules.clear();
}
protected T preProcess(T entity) {
return entity;
}
/**
* Get next unused id.
*
* @return next unused id
*/
abstract protected long nextId();
}
|
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\repository\rule\InMemoryRuleRepositoryAdapter.java
| 2
|
请完成以下Java代码
|
private Quantity extractCatchWeight(final @NonNull RemotePOSOrderLine remoteOrderLine)
{
return remoteOrderLine.getCatchWeight() != null && remoteOrderLine.getCatchWeightUomId() != null
? Quantitys.of(remoteOrderLine.getCatchWeight(), remoteOrderLine.getCatchWeightUomId())
: null;
}
private Tax findTax(final POSOrder order, final TaxCategoryId taxCategoryId)
{
final TaxQuery taxQuery = TaxQuery.builder()
.fromCountryId(order.getShipFrom().getCountryId())
.orgId(order.getShipFrom().getOrgId())
.bPartnerLocationId(order.getShipToCustomerAndLocationId())
.dateOfInterest(Timestamp.from(order.getDate()))
.taxCategoryId(taxCategoryId)
.soTrx(SOTrx.SALES)
.build();
final Tax tax = taxDAO.getByIfPresent(taxQuery).orElseThrow(() -> TaxNotFoundException.ofQuery(taxQuery));
if (tax.isDocumentLevel())
{
throw new AdempiereException("POS tax shall be all line level")
.setParameter("tax", tax);
}
return tax;
}
private void createOrUpdatePaymentFromRemote(final RemotePOSPayment remotePayment)
{
order.createOrUpdatePayment(remotePayment.getUuid(), existingPayment -> {
final Money amount = toMoney(currencyPrecision.round(remotePayment.getAmount()));
if (existingPayment != null)
{
// don't update
Check.assumeEquals(existingPayment.getPaymentMethod(), remotePayment.getPaymentMethod(), "paymentMethod");
Check.assumeEquals(existingPayment.getAmount(), amount, "amount");
|
return existingPayment;
}
else
{
return POSPayment.builder()
.externalId(remotePayment.getUuid())
.paymentMethod(remotePayment.getPaymentMethod())
.amount(amount)
.paymentProcessingStatus(POSPaymentProcessingStatus.NEW)
.build();
}
});
}
private Money toMoney(final BigDecimal amount)
{
return Money.of(amount, order.getCurrencyId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderUpdateFromRemoteCommand.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty() {
return operations.isEmpty();
}
@Override
public Runnable getNextOperation() {
return operations.poll();
}
/**
* Generic method to plan a {@link Runnable}.
*/
@Override
public void planOperation(Runnable operation) {
operations.add(operation);
if (operation instanceof AbstractOperation) {
ExecutionEntity execution = ((AbstractOperation) operation).getExecution();
if (execution != null) {
commandContext.addInvolvedExecution(execution);
}
}
logger.debug("Operation {} added to agenda", operation.getClass());
}
@Override
public void planContinueProcessOperation(ExecutionEntity execution) {
planOperation(new ContinueProcessOperation(commandContext, execution));
}
@Override
public void planContinueProcessSynchronousOperation(ExecutionEntity execution) {
planOperation(new ContinueProcessOperation(commandContext, execution, true, false));
}
|
@Override
public void planContinueProcessInCompensation(ExecutionEntity execution) {
planOperation(new ContinueProcessOperation(commandContext, execution, false, true));
}
@Override
public void planContinueMultiInstanceOperation(ExecutionEntity execution) {
planOperation(new ContinueMultiInstanceOperation(commandContext, execution));
}
@Override
public void planTakeOutgoingSequenceFlowsOperation(ExecutionEntity execution, boolean evaluateConditions) {
planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions));
}
@Override
public void planEndExecutionOperation(ExecutionEntity execution) {
planOperation(new EndExecutionOperation(commandContext, execution));
}
@Override
public void planTriggerExecutionOperation(ExecutionEntity execution) {
planOperation(new TriggerExecutionOperation(commandContext, execution));
}
@Override
public void planDestroyScopeOperation(ExecutionEntity execution) {
planOperation(new DestroyScopeOperation(commandContext, execution));
}
@Override
public void planExecuteInactiveBehaviorsOperation() {
planOperation(new ExecuteInactiveBehaviorsOperation(commandContext));
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\DefaultActivitiEngineAgenda.java
| 1
|
请完成以下Java代码
|
public CaseInstanceChangeState setChangePlanItemDefinitionWithNewTargetIds(Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> changePlanItemDefinitionWithNewTargetIds) {
this.changePlanItemDefinitionWithNewTargetIds = changePlanItemDefinitionWithNewTargetIds;
return this;
}
public Map<String, Map<String, Object>> getChildInstanceTaskVariables() {
return childInstanceTaskVariables;
}
public CaseInstanceChangeState setChildInstanceTaskVariables(Map<String, Map<String, Object>> childInstanceTaskVariables) {
this.childInstanceTaskVariables = childInstanceTaskVariables;
return this;
}
public Map<String, PlanItemInstanceEntity> getCreatedStageInstances() {
return createdStageInstances;
}
public CaseInstanceChangeState setCreatedStageInstances(HashMap<String, PlanItemInstanceEntity> createdStageInstances) {
this.createdStageInstances = createdStageInstances;
return this;
|
}
public void addCreatedStageInstance(String key, PlanItemInstanceEntity planItemInstance) {
this.createdStageInstances.put(key, planItemInstance);
}
public Map<String, PlanItemInstanceEntity> getTerminatedPlanItemInstances() {
return terminatedPlanItemInstances;
}
public CaseInstanceChangeState setTerminatedPlanItemInstances(HashMap<String, PlanItemInstanceEntity> terminatedPlanItemInstances) {
this.terminatedPlanItemInstances = terminatedPlanItemInstances;
return this;
}
public void addTerminatedPlanItemInstance(String key, PlanItemInstanceEntity planItemInstance) {
this.terminatedPlanItemInstances.put(key, planItemInstance);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceChangeState.java
| 1
|
请完成以下Java代码
|
static void assertNoLoopInTree(final I_M_Product_Category productCategory)
{
if (hasLoopInTree(productCategory))
{
throw new AdempiereException("@ProductCategoryLoopDetected@");
}
}
/**
* Loop detection of product category tree.
*/
private static boolean hasLoopInTree (final I_M_Product_Category productCategory)
{
final int productCategoryId = productCategory.getM_Product_Category_ID();
final int newParentCategoryId = productCategory.getM_Product_Category_Parent_ID();
// get values
ResultSet rs = null;
PreparedStatement pstmt = null;
final String sql = " SELECT M_Product_Category_ID, M_Product_Category_Parent_ID FROM M_Product_Category";
final Vector<SimpleTreeNode> categories = new Vector<>(100);
try {
pstmt = DB.prepareStatement(sql, null);
rs = pstmt.executeQuery();
while (rs.next()) {
if (rs.getInt(1) == productCategoryId)
categories.add(new SimpleTreeNode(rs.getInt(1), newParentCategoryId));
categories.add(new SimpleTreeNode(rs.getInt(1), rs.getInt(2)));
}
if (hasLoop(newParentCategoryId, categories, productCategoryId))
return true;
} catch (final SQLException e) {
log.error(sql, e);
return true;
}
finally
{
DB.close(rs, pstmt);
}
return false;
} // hasLoopInTree
/**
* Recursive search for parent nodes - climbs the to the root.
* If there is a circle there is no root but it comes back to the start node.
*/
private static boolean hasLoop(final int parentCategoryId, final Vector<SimpleTreeNode> categories, final int loopIndicatorId) {
final Iterator<SimpleTreeNode> iter = categories.iterator();
boolean ret = false;
while (iter.hasNext()) {
final SimpleTreeNode node = iter.next();
if(node.getNodeId()==parentCategoryId){
if (node.getParentId()==0) {
//root node, all fine
return false;
}
if(node.getNodeId()==loopIndicatorId){
//loop found
return true;
}
ret = hasLoop(node.getParentId(), categories, loopIndicatorId);
|
}
}
return ret;
} //hasLoop
/**
* Simple class for tree nodes.
* @author Karsten Thiemann, kthiemann@adempiere.org
*
*/
private static class SimpleTreeNode {
/** id of the node */
private final int nodeId;
/** id of the nodes parent */
private final int parentId;
public SimpleTreeNode(final int nodeId, final int parentId) {
this.nodeId = nodeId;
this.parentId = parentId;
}
public int getNodeId() {
return nodeId;
}
public int getParentId() {
return parentId;
}
}
} // MProductCategory
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MProductCategory.java
| 1
|
请完成以下Java代码
|
public Integer load(TableAndLookupKey key)
{
return retrieveRecordId(key);
}
});
public int getRecordId(@NonNull final AdTableId adTableId, @NonNull final String lookupKey)
{
final TableAndLookupKey key = new TableAndLookupKey(adTableId, lookupKey);
try
{
return recordIdsByExternalIdCache.get(key);
}
catch (ExecutionException e)
{
throw AdempiereException.wrapIfNeeded(e)
.setParameter("key", key);
}
}
private int retrieveRecordId(@NonNull final TableAndLookupKey key)
{
final POInfo poInfo = POInfo.getPOInfo(key.getAdTableId());
final String lookupKey = key.getLookupKey();
int recordId = retrieveRecordIdByExternalId(poInfo, lookupKey);
if (recordId < 0)
{
recordId = retrieveRecordIdByValue(poInfo, lookupKey);
}
if (recordId < 0)
{
throw new AdempiereException("@NotFound@ @Record_ID@: " + key);
}
return recordId;
}
private int retrieveRecordIdByExternalId(@NonNull final POInfo poInfo, @NonNull final String externalId)
{
if (!poInfo.hasColumnName(COLUMNNAME_ExternalId))
{
return -1;
}
final String tableName = poInfo.getTableName();
final String keyColumnName = poInfo.getKeyColumnName();
if (keyColumnName == null)
{
throw new AdempiereException("No key column found: " + tableName);
}
final String sql = "SELECT " + keyColumnName
+ " FROM " + tableName
+ " WHERE " + I_I_DataEntry_Record.COLUMNNAME_ExternalId + "=?"
+ " ORDER BY " + keyColumnName;
final int recordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, externalId);
return recordId;
}
private int retrieveRecordIdByValue(@NonNull final POInfo poInfo, @NonNull final String value)
{
if (!poInfo.hasColumnName(COLUMNNAME_Value))
{
return -1;
}
|
final String tableName = poInfo.getTableName();
final String keyColumnName = poInfo.getKeyColumnName();
if (keyColumnName == null)
{
throw new AdempiereException("No key column found: " + tableName);
}
final String sql = "SELECT " + keyColumnName
+ " FROM " + tableName
+ " WHERE " + COLUMNNAME_Value + "=?"
+ " ORDER BY " + keyColumnName;
final int recordId = DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, value);
return recordId;
}
@Value
private static class TableAndLookupKey
{
@NonNull
AdTableId adTableId;
@NonNull
String lookupKey;
private TableAndLookupKey(
@NonNull final AdTableId adTableId,
@NonNull final String lookupKey)
{
Check.assumeNotEmpty(lookupKey, "lookupKey is not empty");
this.adTableId = adTableId;
this.lookupKey = lookupKey.trim();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\RecordIdLookup.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getArangoId() {
return arangoId;
}
public void setArangoId(String arangoId) {
this.arangoId = arangoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public ZonedDateTime getPublishDate() {
|
return publishDate;
}
public void setPublishDate(ZonedDateTime publishDate) {
this.publishDate = publishDate;
}
public String getHtmlContent() {
return htmlContent;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-arangodb\src\main\java\com\baeldung\arangodb\model\Article.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class GrpcServerAutoConfiguration {
/**
* A scope that is valid for the duration of a grpc request.
*
* @return The grpc request scope bean.
*/
@Bean
public static GrpcRequestScope grpcRequestScope() {
return new GrpcRequestScope();
}
@ConditionalOnMissingBean
@Bean
public GrpcServerProperties defaultGrpcServerProperties() {
return new GrpcServerProperties();
}
/**
* Lazily creates a {@link SelfNameResolverFactory} bean, that can be used by the client to connect to the server
* itself.
*
* @param properties The properties to derive the address from.
* @return The newly created {@link SelfNameResolverFactory} bean.
*/
@ConditionalOnMissingBean
@Bean
@Lazy
public SelfNameResolverFactory selfNameResolverFactory(final GrpcServerProperties properties) {
return new SelfNameResolverFactory(properties);
}
@ConditionalOnMissingBean
@Bean
GlobalServerInterceptorRegistry globalServerInterceptorRegistry(
final ApplicationContext applicationContext) {
return new GlobalServerInterceptorRegistry(applicationContext);
}
@Bean
@Lazy
AnnotationGlobalServerInterceptorConfigurer annotationGlobalServerInterceptorConfigurer(
final ApplicationContext applicationContext) {
return new AnnotationGlobalServerInterceptorConfigurer(applicationContext);
}
@ConditionalOnMissingBean
@Bean
public GrpcServiceDiscoverer defaultGrpcServiceDiscoverer() {
return new AnnotationGrpcServiceDiscoverer();
}
|
@ConditionalOnBean(CompressorRegistry.class)
@Bean
public GrpcServerConfigurer compressionServerConfigurer(final CompressorRegistry registry) {
return builder -> builder.compressorRegistry(registry);
}
@ConditionalOnBean(DecompressorRegistry.class)
@Bean
public GrpcServerConfigurer decompressionServerConfigurer(final DecompressorRegistry registry) {
return builder -> builder.decompressorRegistry(registry);
}
@ConditionalOnMissingBean(GrpcServerConfigurer.class)
@Bean
public List<GrpcServerConfigurer> defaultServerConfigurers() {
return Collections.emptyList();
}
@ConditionalOnMissingBean
@ConditionalOnBean(GrpcServerFactory.class)
@Bean
public GrpcServerLifecycle grpcServerLifecycle(
final GrpcServerFactory factory,
final GrpcServerProperties properties,
final ApplicationEventPublisher eventPublisher) {
return new GrpcServerLifecycle(factory, properties.getShutdownGracePeriod(), eventPublisher);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> edit(@RequestBody SysFormFile sysFormFile) {
sysFormFileService.updateById(sysFormFile);
return Result.OK("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "表单评论文件-通过id删除")
@Operation(summary = "表单评论文件-通过id删除")
@DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
sysFormFileService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "表单评论文件-批量删除")
@Operation(summary = "表单评论文件-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysFormFileService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@AutoLog(value = "表单评论文件-通过id查询")
@Operation(summary = "表单评论文件-通过id查询")
@GetMapping(value = "/queryById")
public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
SysFormFile sysFormFile = sysFormFileService.getById(id);
|
return Result.OK(sysFormFile);
}
/**
* 导出excel
*
* @param request
* @param sysFormFile
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysFormFile sysFormFile) {
return super.exportXls(request, sysFormFile, SysFormFile.class, "表单评论文件");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysFormFile.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysFormFileController.java
| 2
|
请完成以下Java代码
|
public class BpmnURLHandler extends AbstractURLStreamHandlerService {
private static final Logger LOGGER = LoggerFactory.getLogger(BpmnURLHandler.class);
private static final String SYNTAX = "bpmn: bpmn-xml-uri";
private URL bpmnXmlURL;
/**
* Open the connection for the given URL.
*
* @param url
* the url from which to open a connection.
* @return a connection on the specified URL.
* @throws IOException
* if an error occurs or if the URL is malformed.
*/
@Override
public URLConnection openConnection(URL url) throws IOException {
if (url.getPath() == null || url.getPath().trim().length() == 0) {
throw new MalformedURLException("Path can not be null or empty. Syntax: " + SYNTAX);
}
bpmnXmlURL = new URL(url.getPath());
LOGGER.debug("BPMN xml URL is: [{}]", bpmnXmlURL);
return new Connection(url);
}
|
public URL getBpmnXmlURL() {
return bpmnXmlURL;
}
public class Connection extends URLConnection {
public Connection(URL url) {
super(url);
}
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BpmnTransformer.transform(bpmnXmlURL, os);
os.close();
return new ByteArrayInputStream(os.toByteArray());
} catch (Exception e) {
LOGGER.error("Error opening spring xml url", e);
throw (IOException) new IOException("Error opening spring xml url").initCause(e);
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BpmnURLHandler.java
| 1
|
请完成以下Java代码
|
public boolean isMultiRowOnly ()
{
Object oo = get_Value(COLUMNNAME_IsMultiRowOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Read Only.
@param IsReadOnly
Field is read only
*/
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Single Row Layout.
@param IsSingleRow
Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public void setIsSingleRow (boolean IsSingleRow)
{
set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow));
}
/** Get Single Row Layout.
@return Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public boolean isSingleRow ()
{
Object oo = get_Value(COLUMNNAME_IsSingleRow);
if (oo != null)
|
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Tab.java
| 1
|
请完成以下Java代码
|
public class ObservationReactiveAuthenticationManager implements ReactiveAuthenticationManager {
private final ObservationRegistry registry;
private final ReactiveAuthenticationManager delegate;
private ObservationConvention<AuthenticationObservationContext> convention = new AuthenticationObservationConvention();
public ObservationReactiveAuthenticationManager(ObservationRegistry registry,
ReactiveAuthenticationManager delegate) {
this.registry = registry;
this.delegate = delegate;
}
@Override
public Mono<Authentication> authenticate(Authentication authentication) throws AuthenticationException {
AuthenticationObservationContext context = new AuthenticationObservationContext();
context.setAuthenticationRequest(authentication);
context.setAuthenticationManagerClass(this.delegate.getClass());
return Mono.deferContextual((contextView) -> {
Observation observation = Observation.createNotStarted(this.convention, () -> context, this.registry)
.parentObservation(contextView.getOrDefault(ObservationThreadLocalAccessor.KEY, null))
.start();
return this.delegate.authenticate(authentication).doOnSuccess((result) -> {
context.setAuthenticationResult(result);
observation.stop();
}).doOnCancel(observation::stop).doOnError((t) -> {
observation.error(t);
observation.stop();
|
});
});
}
/**
* Use the provided convention for reporting observation data
* @param convention The provided convention
*
* @since 6.1
*/
public void setObservationConvention(ObservationConvention<AuthenticationObservationContext> convention) {
Assert.notNull(convention, "The observation convention cannot be null");
this.convention = convention;
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ObservationReactiveAuthenticationManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BankAccountService
{
private final IBPBankAccountDAO bankAccountDAO = Services.get(IBPBankAccountDAO.class);
private final BankRepository bankRepo;
private final CurrencyRepository currencyRepo;
public BankAccountService(
@NonNull final BankRepository bankRepo,
@NonNull final CurrencyRepository currencyRepo)
{
this.bankRepo = bankRepo;
this.currencyRepo = currencyRepo;
}
public static BankAccountService newInstanceForUnitTesting()
{
return new BankAccountService(
new BankRepository(),
new CurrencyRepository());
}
public boolean isCashBank(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankId != null && bankRepo.isCashBank(bankId);
}
public BankAccount getById(@NonNull final BankAccountId bankAccountId)
{
return bankAccountDAO.getById(bankAccountId);
}
@NonNull
public BankAccount getByIdNotNull(@NonNull final BankAccountId bankAccountId)
{
return Optional.ofNullable(getById(bankAccountId))
.orElseThrow(() -> new AdempiereException("No Bank Account found for " + bankAccountId));
}
public String createBankAccountName(@NonNull final BankAccountId bankAccountId)
{
final BankAccount bankAccount = getById(bankAccountId);
final CurrencyCode currencyCode = currencyRepo.getCurrencyCodeById(bankAccount.getCurrencyId());
final BankId bankId = bankAccount.getBankId();
if (bankId != null)
{
final Bank bank = bankRepo.getById(bankId);
|
return bank.getBankName() + "_" + currencyCode.toThreeLetterCode();
}
return currencyCode.toThreeLetterCode();
}
public DataImportConfigId getDataImportConfigIdForBankAccount(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankRepo.retrieveDataImportConfigIdForBank(bankId);
}
public boolean isImportAsSingleSummaryLine(@NonNull final BankAccountId bankAccountId)
{
final BankId bankId = bankAccountDAO.getBankId(bankAccountId);
return bankRepo.isImportAsSingleSummaryLine(bankId);
}
@NonNull
public Optional<BankId> getBankIdBySwiftCode(@NonNull final String swiftCode)
{
return bankRepo.getBankIdBySwiftCode(swiftCode);
}
@NonNull
public Optional<BankAccountId> getBankAccountId(
@NonNull final BankId bankId,
@NonNull final String accountNo)
{
return bankAccountDAO.getBankAccountId(bankId, accountNo);
}
@NonNull
public Optional<BankAccountId> getBankAccountIdByIBAN(@NonNull final String iban)
{
return bankAccountDAO.getBankAccountIdByIBAN(iban);
}
@NonNull
public Optional<String> getBankName(@NonNull final BankAccountId bankAccountId)
{
return Optional.of(bankAccountDAO.getById(bankAccountId))
.map(BankAccount::getBankId)
.map(bankRepo::getById)
.map(Bank::getBankName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\api\BankAccountService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ShopCartEntity implements Serializable {
/** 主键 */
private String id;
/** 用户id */
private String userId;
/** 产品详情(在数据库中以product_id表示) */
private ProductEntity productEntity;
/** 数量 */
private int count;
/** 添加时间 */
private Timestamp time;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public ProductEntity getProductEntity() {
return productEntity;
}
public void setProductEntity(ProductEntity productEntity) {
this.productEntity = productEntity;
}
public int getCount() {
|
return count;
}
public void setCount(int count) {
this.count = count;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
@Override
public String toString() {
return "ShopCartEntity{" +
"id='" + id + '\'' +
", userId='" + userId + '\'' +
", productEntity=" + productEntity +
", count=" + count +
", time=" + time +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\ShopCartEntity.java
| 2
|
请完成以下Java代码
|
public class FlowableException extends RuntimeException {
private static final long serialVersionUID = 1L;
protected boolean isLogged;
protected boolean reduceLogLevel;
public FlowableException(String message, Throwable cause) {
super(message, cause);
}
public FlowableException(String message) {
super(message);
}
public boolean isLogged() {
return isLogged;
|
}
public void setLogged(boolean isLogged) {
this.isLogged = isLogged;
}
public boolean isReduceLogLevel() {
return reduceLogLevel;
}
public void setReduceLogLevel(boolean reduceLogLevel) {
this.reduceLogLevel = reduceLogLevel;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common-api\src\main\java\org\flowable\common\engine\api\FlowableException.java
| 1
|
请完成以下Java代码
|
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getUser2() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
|
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_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\eevolution\model\X_HR_Concept_Acct.java
| 1
|
请完成以下Java代码
|
private static class OAuth2ErrorConverter implements Converter<Map<String, String>, OAuth2Error> {
@Override
public OAuth2Error convert(Map<String, String> parameters) {
String errorCode = parameters.get(OAuth2ParameterNames.ERROR);
String errorDescription = parameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = parameters.get(OAuth2ParameterNames.ERROR_URI);
return new OAuth2Error(errorCode, errorDescription, errorUri);
}
}
/**
* A {@link Converter} that converts the provided {@link OAuth2Error} to a {@code Map}
* representation of OAuth 2.0 Error parameters.
*/
private static class OAuth2ErrorParametersConverter implements Converter<OAuth2Error, Map<String, String>> {
|
@Override
public Map<String, String> convert(OAuth2Error oauth2Error) {
Map<String, String> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.ERROR, oauth2Error.getErrorCode());
if (StringUtils.hasText(oauth2Error.getDescription())) {
parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, oauth2Error.getDescription());
}
if (StringUtils.hasText(oauth2Error.getUri())) {
parameters.put(OAuth2ParameterNames.ERROR_URI, oauth2Error.getUri());
}
return parameters;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2ErrorHttpMessageConverter.java
| 1
|
请完成以下Spring Boot application配置
|
#服务器端口
server:
port: 8010
oss:
enable: true
name: qiniu
tenant-mode: true
endpoint: http://prt1thnw3.bkt.clouddn.com
access-key: N_Loh1ngBqcJovwiAJqR91Ifj2vgOWHOf8AwBA
|
_h
secret-key: AuzuA1KHAbkIndCU0dB3Zfii2O3crHNODDmpxHRS
bucket-name: blade
|
repos\SpringBlade-master\blade-ops\blade-resource\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
@Value("${spring.cloud.nacos.config.namespace:#{null}}")
public void setNamespace(String namespace) {
this.namespace = namespace;
}
@Value("${spring.cloud.nacos.config.username:#{null}}")
public void setUsername(String username) {
this.username = username;
}
@Value("${spring.cloud.nacos.config.password:#{null}}")
public void setPassword(String password) {
this.password = password;
}
public String getDataType() {
return dataType;
}
public String getServerAddr() {
return serverAddr;
}
public String getNamespace() {
return namespace;
}
public String getDataId() {
|
return dataId;
}
public String getRouteGroup() {
return routeGroup;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-cloud-gateway\src\main\java\org\jeecg\config\GatewayRoutersConfig.java
| 2
|
请完成以下Java代码
|
public Collection<MessageBatch> releaseBatches() {
MessageBatch batch = doReleaseBatch();
if (batch == null) {
return Collections.emptyList();
}
return Collections.singletonList(batch);
}
private @Nullable MessageBatch doReleaseBatch() {
if (this.messages.isEmpty()) {
return null;
}
Message message = assembleMessage();
MessageBatch messageBatch = new MessageBatch(this.exchange, this.routingKey, message);
this.messages.clear();
this.currentSize = 0;
this.exchange = null;
this.routingKey = null;
return messageBatch;
}
private Message assembleMessage() {
if (this.messages.size() == 1) {
return this.messages.get(0);
}
MessageProperties messageProperties = this.messages.get(0).getMessageProperties();
byte[] body = new byte[this.currentSize];
ByteBuffer bytes = ByteBuffer.wrap(body);
for (Message message : this.messages) {
bytes.putInt(message.getBody().length);
bytes.put(message.getBody());
}
messageProperties.getHeaders().put(MessageProperties.SPRING_BATCH_FORMAT,
MessageProperties.BATCH_FORMAT_LENGTH_HEADER4);
messageProperties.getHeaders().put(AmqpHeaders.BATCH_SIZE, this.messages.size());
return new Message(body, messageProperties);
}
@Override
public boolean canDebatch(MessageProperties properties) {
return MessageProperties.BATCH_FORMAT_LENGTH_HEADER4.equals(properties
.getHeaders()
|
.get(MessageProperties.SPRING_BATCH_FORMAT));
}
/**
* Debatch a message that has a header with {@link MessageProperties#SPRING_BATCH_FORMAT}
* set to {@link MessageProperties#BATCH_FORMAT_LENGTH_HEADER4}.
* @param message the batched message.
* @param fragmentConsumer a consumer for each fragment.
* @since 2.2
*/
@Override
public void deBatch(Message message, Consumer<Message> fragmentConsumer) {
ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBody());
MessageProperties messageProperties = message.getMessageProperties();
messageProperties.getHeaders().remove(MessageProperties.SPRING_BATCH_FORMAT);
while (byteBuffer.hasRemaining()) {
int length = byteBuffer.getInt();
if (length < 0 || length > byteBuffer.remaining()) {
throw new ListenerExecutionFailedException("Bad batched message received",
new MessageConversionException("Insufficient batch data at offset " + byteBuffer.position()),
message);
}
byte[] body = new byte[length];
byteBuffer.get(body);
messageProperties.setContentLength(length);
// Caveat - shared MessageProperties, except for last
Message fragment;
if (byteBuffer.hasRemaining()) {
fragment = new Message(body, messageProperties);
}
else {
MessageProperties lastProperties = new MessageProperties();
BeanUtils.copyProperties(messageProperties, lastProperties);
lastProperties.setLastInBatch(true);
fragment = new Message(body, lastProperties);
}
fragmentConsumer.accept(fragment);
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\batch\SimpleBatchingStrategy.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DoubleType implements VariableType {
public static final String TYPE_NAME = "double";
private static final long serialVersionUID = 1L;
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
|
return valueFields.getDoubleValue();
}
@Override
public void setValue(Object value, ValueFields valueFields) {
valueFields.setDoubleValue((Double) value);
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Double.class.isAssignableFrom(value.getClass());
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\DoubleType.java
| 2
|
请完成以下Java代码
|
public Object getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DoubleDataEntry)) return false;
if (!super.equals(o)) return false;
DoubleDataEntry that = (DoubleDataEntry) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
|
return Objects.hash(super.hashCode(), value);
}
@Override
public String toString() {
return "DoubleDataEntry{" +
"value=" + value +
"} " + super.toString();
}
@Override
public String getValueAsString() {
return Double.toString(value);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\kv\DoubleDataEntry.java
| 1
|
请完成以下Java代码
|
public void setPaySelectionTrxType (java.lang.String PaySelectionTrxType)
{
set_Value (COLUMNNAME_PaySelectionTrxType, PaySelectionTrxType);
}
/** Get Transaktionsart.
@return Transaktionsart */
@Override
public java.lang.String getPaySelectionTrxType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PaySelectionTrxType);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Datensatz verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Datensatz verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
|
/** Set Gesamtbetrag.
@param TotalAmt Gesamtbetrag */
@Override
public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Gesamtbetrag.
@return Gesamtbetrag */
@Override
public java.math.BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySelection.java
| 1
|
请完成以下Java代码
|
public @Nullable Token verifyToken(String key) {
if (key == null || "".equals(key)) {
return null;
}
String[] tokens = StringUtils
.delimitedListToStringArray(Utf8.decode(Base64.getDecoder().decode(Utf8.encode(key))), ":");
Assert.isTrue(tokens.length >= 4, () -> "Expected 4 or more tokens but found " + tokens.length);
long creationTime;
try {
creationTime = Long.decode(tokens[0]);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException("Expected number but found " + tokens[0]);
}
String serverSecret = computeServerSecretApplicableAt(creationTime);
String pseudoRandomNumber = tokens[1];
// Permit extendedInfo to itself contain ":" characters
StringBuilder extendedInfo = new StringBuilder();
for (int i = 2; i < tokens.length - 1; i++) {
if (i > 2) {
extendedInfo.append(":");
}
extendedInfo.append(tokens[i]);
}
String sha1Hex = tokens[tokens.length - 1];
// Verification
String content = creationTime + ":" + pseudoRandomNumber + ":" + extendedInfo.toString();
String expectedSha512Hex = Sha512DigestUtils.shaHex(content + ":" + serverSecret);
Assert.isTrue(expectedSha512Hex.equals(sha1Hex), "Key verification failure");
return new DefaultToken(key, creationTime, extendedInfo.toString());
}
/**
* @return a pseudo random number (hex encoded)
*/
private String generatePseudoRandomNumber() {
byte[] randomBytes = new byte[this.pseudoRandomNumberBytes];
this.secureRandom.nextBytes(randomBytes);
return new String(Hex.encode(randomBytes));
}
private String computeServerSecretApplicableAt(long time) {
return this.serverSecret + ":" + Long.valueOf(time % this.serverInteger).intValue();
}
/**
* @param serverSecret the new secret, which can contain a ":" if desired (never being
* sent to the client)
*/
public void setServerSecret(String serverSecret) {
this.serverSecret = serverSecret;
}
|
public void setSecureRandom(SecureRandom secureRandom) {
this.secureRandom = secureRandom;
}
/**
* @param pseudoRandomNumberBytes changes the number of bytes issued (must be >= 0;
* defaults to 256)
*/
public void setPseudoRandomNumberBytes(int pseudoRandomNumberBytes) {
Assert.isTrue(pseudoRandomNumberBytes >= 0, "Must have a positive pseudo random number bit size");
this.pseudoRandomNumberBytes = pseudoRandomNumberBytes;
}
public void setServerInteger(Integer serverInteger) {
this.serverInteger = serverInteger;
}
@Override
public void afterPropertiesSet() {
Assert.hasText(this.serverSecret, "Server secret required");
Assert.notNull(this.serverInteger, "Server integer required");
Assert.notNull(this.secureRandom, "SecureRandom instance required");
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\token\KeyBasedPersistenceTokenService.java
| 1
|
请完成以下Java代码
|
public static int getPMM_Product_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
public static String toUUIDString(final I_C_Flatrate_Term contract)
{
return UUIDs.fromIdAsString(contract.getC_Flatrate_Term_ID());
}
public static int getC_Flatrate_Term_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
|
public static String toUUIDString(final I_C_RfQResponseLine rfqResponseLine)
{
return toC_RfQReponseLine_UUID(rfqResponseLine.getC_RfQResponseLine_ID());
}
public static String toC_RfQReponseLine_UUID(final int C_RfQResponseLine_ID)
{
return UUIDs.fromIdAsString(C_RfQResponseLine_ID);
}
public static int getC_RfQResponseLine_ID(final String uuid)
{
return UUIDs.toId(uuid);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\impl\SyncUUIDs.java
| 1
|
请完成以下Java代码
|
public final class MixedQuantity
{
public static final MixedQuantity EMPTY = new MixedQuantity(ImmutableMap.of());
@NonNull private final ImmutableMap<UomId, Quantity> map;
private MixedQuantity(@NonNull final Map<UomId, Quantity> map)
{
this.map = ImmutableMap.copyOf(map);
}
public static Collector<Quantity, ?, MixedQuantity> collectAndSum()
{
return GuavaCollectors.collectUsingListAccumulator(de.metas.quantity.MixedQuantity::sumOf);
}
public static MixedQuantity sumOf(@NonNull final Collection<Quantity> collection)
{
if (collection.isEmpty())
{
return EMPTY;
}
final HashMap<UomId, Quantity> map = new HashMap<>();
for (final Quantity qty : collection)
{
map.compute(qty.getUomId(), (currencyId, currentQty) -> currentQty == null ? qty : currentQty.add(qty));
}
return new MixedQuantity(map);
}
@Override
public String toString()
{
if (map.isEmpty())
{
return "0";
}
return map.values()
|
.stream()
.map(Quantity::toShortString)
.collect(Collectors.joining("+"));
}
public Optional<Quantity> toNoneOrSingleValue()
{
if (map.isEmpty())
{
return Optional.empty();
}
else if (map.size() == 1)
{
return map.values().stream().findFirst();
}
else
{
throw new AdempiereException("Expected none or single value but got many: " + map.values());
}
}
public MixedQuantity add(@NonNull final Quantity qtyToAdd)
{
if (qtyToAdd.isZero())
{
return this;
}
return new MixedQuantity(
CollectionUtils.merge(map, qtyToAdd.getUomId(), qtyToAdd, Quantity::add)
);
}
public Quantity getByUOM(@NonNull final UomId uomId)
{
final Quantity qty = map.get(uomId);
return qty != null ? qty : Quantitys.zero(uomId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\MixedQuantity.java
| 1
|
请完成以下Java代码
|
public void setM_InventoryLine(final org.compiere.model.I_M_InventoryLine M_InventoryLine)
{
set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine);
}
@Override
public void setM_InventoryLine_ID (final int M_InventoryLine_ID)
{
if (M_InventoryLine_ID < 1)
set_Value (COLUMNNAME_M_InventoryLine_ID, null);
else
set_Value (COLUMNNAME_M_InventoryLine_ID, M_InventoryLine_ID);
}
@Override
public int getM_InventoryLine_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID);
}
@Override
public de.metas.material.dispo.model.I_MD_Candidate getMD_Candidate()
{
return get_ValueAsPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class);
}
@Override
public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate)
{
set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate);
}
@Override
public void setMD_Candidate_ID (final int MD_Candidate_ID)
{
if (MD_Candidate_ID < 1)
set_Value (COLUMNNAME_MD_Candidate_ID, null);
else
set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID);
}
|
@Override
public int getMD_Candidate_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID);
}
@Override
public void setMD_Candidate_StockChange_Detail_ID (final int MD_Candidate_StockChange_Detail_ID)
{
if (MD_Candidate_StockChange_Detail_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, MD_Candidate_StockChange_Detail_ID);
}
@Override
public int getMD_Candidate_StockChange_Detail_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_Candidate_StockChange_Detail_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_StockChange_Detail.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EmailConfiguration {
@Value("${spring.mail.host}")
private String mailServerHost;
@Value("${spring.mail.port}")
private Integer mailServerPort;
@Value("${spring.mail.username}")
private String mailServerUsername;
@Value("${spring.mail.password}")
private String mailServerPassword;
@Value("${spring.mail.properties.mail.smtp.auth}")
private String mailServerAuth;
@Value("${spring.mail.properties.mail.smtp.starttls.enable}")
private String mailServerStartTls;
@Bean
public JavaMailSender getJavaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(mailServerHost);
mailSender.setPort(mailServerPort);
mailSender.setUsername(mailServerUsername);
mailSender.setPassword(mailServerPassword);
Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", mailServerAuth);
|
props.put("mail.smtp.starttls.enable", mailServerStartTls);
props.put("mail.debug", "true");
return mailSender;
}
@Bean
public SimpleMailMessage templateSimpleMessage() {
SimpleMailMessage message = new SimpleMailMessage();
message.setText("This is the test email template for your email:\n%s\n");
return message;
}
@Bean
public ResourceBundleMessageSource emailMessageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("mailMessages");
return messageSource;
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\mail\EmailConfiguration.java
| 2
|
请完成以下Java代码
|
public class DelegatingSecurityContextAsyncTaskExecutor extends DelegatingSecurityContextTaskExecutor
implements AsyncTaskExecutor {
/**
* Creates a new {@link DelegatingSecurityContextAsyncTaskExecutor} that uses the
* specified {@link SecurityContext}.
* @param delegateAsyncTaskExecutor the {@link AsyncTaskExecutor} to delegate to.
* Cannot be null.
* @param securityContext the {@link SecurityContext} to use for each
* {@link DelegatingSecurityContextRunnable} and
* {@link DelegatingSecurityContextCallable}
*/
public DelegatingSecurityContextAsyncTaskExecutor(AsyncTaskExecutor delegateAsyncTaskExecutor,
@Nullable SecurityContext securityContext) {
super(delegateAsyncTaskExecutor, securityContext);
}
/**
* Creates a new {@link DelegatingSecurityContextAsyncTaskExecutor} that uses the
* current {@link SecurityContext}.
* @param delegateAsyncTaskExecutor the {@link AsyncTaskExecutor} to delegate to.
* Cannot be null.
*/
|
public DelegatingSecurityContextAsyncTaskExecutor(AsyncTaskExecutor delegateAsyncTaskExecutor) {
this(delegateAsyncTaskExecutor, null);
}
@Override
public final void execute(Runnable task, long startTimeout) {
getDelegate().execute(wrap(task), startTimeout);
}
@Override
public final Future<?> submit(Runnable task) {
return getDelegate().submit(wrap(task));
}
@Override
public final <T> Future<T> submit(Callable<T> task) {
return getDelegate().submit(wrap(task));
}
private AsyncTaskExecutor getDelegate() {
return (AsyncTaskExecutor) getDelegateExecutor();
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\task\DelegatingSecurityContextAsyncTaskExecutor.java
| 1
|
请完成以下Java代码
|
public T removeVariable(String variableName) {
if (!getVariablesMap().containsKey(variableName)) {
return null;
}
T value = getVariablesMap().remove(variableName);
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(value);
}
removedVariables.put(variableName, value);
return value;
}
public void removeVariables() {
Iterator<T> valuesIt = getVariablesMap().values().iterator();
removedVariables.putAll(variables);
while (valuesIt.hasNext()) {
T nextVariable = valuesIt.next();
valuesIt.remove();
for (VariableStoreObserver<T> observer : observers) {
observer.onRemove(nextVariable);
}
}
}
public void addObserver(VariableStoreObserver<T> observer) {
observers.add(observer);
}
public void removeObserver(VariableStoreObserver<T> observer) {
observers.remove(observer);
}
|
public static interface VariableStoreObserver<T extends CoreVariableInstance> {
void onAdd(T variable);
void onRemove(T variable);
}
public static interface VariablesProvider<T extends CoreVariableInstance> {
Collection<T> provideVariables();
Collection<T> provideVariables(Collection<String> variableNames);
}
public boolean isRemoved(String variableName) {
return removedVariables.containsKey(variableName);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\VariableStore.java
| 1
|
请完成以下Java代码
|
private static ImmutableListMultimap<AdTableId, BusinessRuleAndTriggers> indexByTriggerTableId(final List<BusinessRule> list)
{
final HashMap<AdTableId, HashMap<BusinessRuleId, BusinessRuleAndTriggersBuilder>> buildersByTriggerTableId = new HashMap<>();
for (final BusinessRule rule : list)
{
for (final BusinessRuleTrigger trigger : rule.getTriggers())
{
buildersByTriggerTableId.computeIfAbsent(trigger.getTriggerTableId(), triggerTableId -> new HashMap<>())
.computeIfAbsent(rule.getId(), ruleId -> BusinessRuleAndTriggers.builderFrom(rule))
.trigger(trigger);
}
}
final ImmutableListMultimap.Builder<AdTableId, BusinessRuleAndTriggers> result = ImmutableListMultimap.builder();
buildersByTriggerTableId.forEach((triggerTableId, ruleBuilders) -> ruleBuilders.values()
.stream().map(BusinessRuleAndTriggersBuilder::build)
.forEach(ruleAndTriggers -> result.put(triggerTableId, ruleAndTriggers))
);
return result.build();
}
public static BusinessRulesCollection ofList(List<BusinessRule> list)
{
|
return !list.isEmpty() ? new BusinessRulesCollection(list) : EMPTY;
}
public ImmutableSet<AdTableId> getTriggerTableIds() {return byTriggerTableId.keySet();}
public ImmutableList<BusinessRuleAndTriggers> getByTriggerTableId(@NonNull final AdTableId triggerTableId) {return this.byTriggerTableId.get(triggerTableId);}
public BusinessRule getById(@NonNull final BusinessRuleId id)
{
final BusinessRule rule = getByIdOrNull(id);
if (rule == null)
{
throw new AdempiereException("No rule found for id=" + id);
}
return rule;
}
@Nullable
public BusinessRule getByIdOrNull(@Nullable final BusinessRuleId id)
{
return id == null ? null : byId.get(id);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\model\BusinessRulesCollection.java
| 1
|
请完成以下Java代码
|
public CandidateBusinessCase getCandidateBusinessCase()
{
return CandidateBusinessCase.PRODUCTION;
}
@Nullable
public PPOrderCandidateId getPpOrderCandidateId() {return ppOrderRef != null ? ppOrderRef.getPpOrderCandidateId() : null;}
public int getPpOrderLineCandidateId() {return ppOrderRef != null ? ppOrderRef.getPpOrderLineCandidateId() : -1;}
@Nullable
public PPOrderId getPpOrderId() {return ppOrderRef != null ? ppOrderRef.getPpOrderId() : null;}
@Nullable
public PPOrderBOMLineId getPpOrderBOMLineId() {return ppOrderRef != null ? ppOrderRef.getPpOrderBOMLineId() : null;}
@Nullable
public PPOrderAndBOMLineId getPpOrderAndBOMLineId() {return ppOrderRef != null ? ppOrderRef.getPpOrderAndBOMLineId() : null;}
public boolean isFinishedGoods()
{
return this.ppOrderRef != null && this.ppOrderRef.isFinishedGoods();
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isBOMLine()
{
|
return this.ppOrderRef != null && this.ppOrderRef.isBOMLine();
}
public ProductionDetail withPPOrderId(@Nullable final PPOrderId newPPOrderId)
{
final PPOrderRef ppOrderRefNew = PPOrderRef.withPPOrderId(ppOrderRef, newPPOrderId);
if (Objects.equals(this.ppOrderRef, ppOrderRefNew))
{
return this;
}
return toBuilder().ppOrderRef(ppOrderRefNew).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\businesscase\ProductionDetail.java
| 1
|
请完成以下Java代码
|
public class FlowableEventRegistryEvent implements EventRegistryEvent {
protected String type;
protected EventInstance eventInstance;
public FlowableEventRegistryEvent(EventInstance eventInstance) {
this.type = eventInstance.getEventKey();
this.eventInstance = eventInstance;
}
public EventInstance getEventInstance() {
return eventInstance;
}
public void setEventInstance(EventInstance eventInstance) {
this.eventInstance = eventInstance;
}
@Override
public String getType() {
return type;
}
|
public void setType(String type) {
this.type = type;
}
@Override
public EventInstance getEventObject() {
return eventInstance;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("type='" + type + "'")
.add("eventInstance=" + eventInstance)
.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\event\FlowableEventRegistryEvent.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PurchaseErrorItem implements PurchaseItem
{
public static PurchaseErrorItem cast(final PurchaseItem purchaseItem)
{
return (PurchaseErrorItem)purchaseItem;
}
PurchaseItemId purchaseItemId;
ITableRecordReference transactionReference;
PurchaseCandidateId purchaseCandidateId;
OrgId orgId;
Throwable throwable;
AdIssueId adIssueId;
@Builder
private PurchaseErrorItem(
final PurchaseItemId purchaseItemId,
@Nullable final Throwable throwable,
|
@Nullable final AdIssueId adIssueId,
@NonNull final PurchaseCandidateId purchaseCandidateId,
@NonNull final OrgId orgId,
@Nullable final ITableRecordReference transactionReference)
{
this.purchaseItemId = purchaseItemId;
Check.assume(adIssueId != null || throwable != null, "At least one of the given issue or thorwable need to be non-null");
this.throwable = throwable;
this.adIssueId = adIssueId;
this.purchaseCandidateId = purchaseCandidateId;
this.orgId = orgId;
this.transactionReference = transactionReference;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseErrorItem.java
| 2
|
请完成以下Java代码
|
public String toString()
{
String toString = this._toString;
if (toString == null)
{
final StringBuilder sb = new StringBuilder();
sb.append(valid ? "Valid" : "Invalid");
if (initialValue != null && initialValue)
{
sb.append("-Initial");
}
if (!TranslatableStrings.isBlank(reason))
{
sb.append("('").append(reason).append("')");
}
toString = this._toString = sb.toString();
}
return toString;
}
@Override
public int hashCode()
{
Integer hashcode = this._hashcode;
if (hashcode == null)
{
hashcode = this._hashcode = Objects.hash(valid, initialValue, reason, fieldName);
}
return hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
|
{
return true;
}
if (!(obj instanceof DocumentValidStatus))
{
return false;
}
final DocumentValidStatus other = (DocumentValidStatus)obj;
return valid == other.valid
&& Objects.equals(initialValue, other.initialValue)
&& Objects.equals(reason, other.reason)
&& Objects.equals(fieldName, other.fieldName)
&& Objects.equals(errorCode, other.errorCode);
}
public boolean isInitialInvalid()
{
return this == STATE_InitialInvalid;
}
public void throwIfInvalid()
{
if (isValid())
{
return;
}
if (exception != null)
{
throw AdempiereException.wrapIfNeeded(exception);
}
else
{
throw new AdempiereException(reason != null ? reason : TranslatableStrings.anyLanguage("Invalid"));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentValidStatus.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void reply(VersionControlRequestCtx ctx, Optional<Exception> e) {
reply(ctx, e, null);
}
private void reply(VersionControlRequestCtx ctx, Function<VersionControlResponseMsg.Builder, VersionControlResponseMsg.Builder> enrichFunction) {
reply(ctx, Optional.empty(), enrichFunction);
}
private void reply(VersionControlRequestCtx ctx, Optional<Exception> e, Function<VersionControlResponseMsg.Builder, VersionControlResponseMsg.Builder> enrichFunction) {
TopicPartitionInfo tpi = topicService.getNotificationsTopic(ServiceType.TB_CORE, ctx.getNodeId());
VersionControlResponseMsg.Builder builder = VersionControlResponseMsg.newBuilder()
.setRequestIdMSB(ctx.getRequestId().getMostSignificantBits())
.setRequestIdLSB(ctx.getRequestId().getLeastSignificantBits());
if (e.isPresent()) {
log.debug("[{}][{}] Failed to process task", ctx.getTenantId(), ctx.getRequestId(), e.get());
var message = e.get().getMessage();
builder.setError(message != null ? message : e.get().getClass().getSimpleName());
} else {
if (enrichFunction != null) {
builder = enrichFunction.apply(builder);
} else {
builder.setGenericResponse(TransportProtos.GenericRepositoryResponseMsg.newBuilder().build());
}
log.debug("[{}][{}] Processed task", ctx.getTenantId(), ctx.getRequestId());
}
ToCoreNotificationMsg msg = ToCoreNotificationMsg.newBuilder().setVcResponseMsg(builder).build();
log.trace("[{}][{}] PUSHING reply: {} to: {}", ctx.getTenantId(), ctx.getRequestId(), msg, tpi);
producer.send(tpi, new TbProtoQueueMsg<>(UUID.randomUUID(), msg), null);
}
private String getRelativePath(EntityType entityType, String entityId) {
String path = entityType.name().toLowerCase();
if (entityId != null) {
path += "/" + entityId + ".json";
|
}
return path;
}
private Lock getRepoLock(TenantId tenantId) {
return tenantRepoLocks.computeIfAbsent(tenantId, t -> new ReentrantLock(true));
}
private void logTaskExecution(VersionControlRequestCtx ctx, ListenableFuture<Void> future, long startTs) {
if (log.isTraceEnabled()) {
Futures.addCallback(future, new FutureCallback<Object>() {
@Override
public void onSuccess(@Nullable Object result) {
log.trace("[{}][{}] Task processing took: {}ms", ctx.getTenantId(), ctx.getRequestId(), (System.currentTimeMillis() - startTs));
}
@Override
public void onFailure(Throwable t) {
log.trace("[{}][{}] Task failed: ", ctx.getTenantId(), ctx.getRequestId(), t);
}
}, MoreExecutors.directExecutor());
}
}
}
|
repos\thingsboard-master\common\version-control\src\main\java\org\thingsboard\server\service\sync\vc\DefaultClusterVersionControlService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public int getAsyncExecutorNumberOfRetries() {
return asyncExecutorNumberOfRetries;
}
public JobServiceConfiguration setAsyncExecutorNumberOfRetries(int asyncExecutorNumberOfRetries) {
this.asyncExecutorNumberOfRetries = asyncExecutorNumberOfRetries;
return this;
}
public int getAsyncExecutorResetExpiredJobsMaxTimeout() {
return asyncExecutorResetExpiredJobsMaxTimeout;
}
public JobServiceConfiguration setAsyncExecutorResetExpiredJobsMaxTimeout(int asyncExecutorResetExpiredJobsMaxTimeout) {
this.asyncExecutorResetExpiredJobsMaxTimeout = asyncExecutorResetExpiredJobsMaxTimeout;
return this;
}
@Override
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public JobServiceConfiguration setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
}
public List<JobProcessor> getJobProcessors() {
return jobProcessors;
}
public JobServiceConfiguration setJobProcessors(List<JobProcessor> jobProcessors) {
this.jobProcessors = Collections.unmodifiableList(jobProcessors);
return this;
}
public List<HistoryJobProcessor> getHistoryJobProcessors() {
return historyJobProcessors;
}
public JobServiceConfiguration setHistoryJobProcessors(List<HistoryJobProcessor> historyJobProcessors) {
this.historyJobProcessors = Collections.unmodifiableList(historyJobProcessors);
return this;
}
|
public void setJobParentStateResolver(InternalJobParentStateResolver jobParentStateResolver) {
this.jobParentStateResolver = jobParentStateResolver;
}
public InternalJobParentStateResolver getJobParentStateResolver() {
return jobParentStateResolver;
}
public List<String> getEnabledJobCategories() {
return enabledJobCategories;
}
public void setEnabledJobCategories(List<String> enabledJobCategories) {
this.enabledJobCategories = enabledJobCategories;
}
public void addEnabledJobCategory(String jobCategory) {
if (enabledJobCategories == null) {
enabledJobCategories = new ArrayList<>();
}
enabledJobCategories.add(jobCategory);
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\JobServiceConfiguration.java
| 2
|
请完成以下Java代码
|
private CreateShipmentInfoCandidate buildCreateShipmentCandidate(@NonNull final JsonCreateShipmentInfo jsonCreateShipmentInfo)
{
final ShipmentScheduleId shipmentScheduleId = extractShipmentScheduleId(jsonCreateShipmentInfo);
return CreateShipmentInfoCandidate.builder()
.createShipmentInfo(jsonCreateShipmentInfo)
.shipmentScheduleId(shipmentScheduleId)
.build();
}
private ShippingInfoCache newShippingInfoCache()
{
return ShippingInfoCache.builder()
.shipmentScheduleBL(shipmentScheduleBL)
.scheduleEffectiveBL(scheduleEffectiveBL)
|
.shipperDAO(shipperDAO)
.productDAO(productDAO)
.build();
}
@Value
@Builder
private static class CreateShipmentInfoCandidate
{
@NonNull
ShipmentScheduleId shipmentScheduleId;
@NonNull
JsonCreateShipmentInfo createShipmentInfo;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\JsonShipmentService.java
| 1
|
请完成以下Java代码
|
public CaseFileModel getCaseFileModel() {
return caseFileModelChild.getChild(this);
}
public void setCaseFileModel(CaseFileModel caseFileModel) {
caseFileModelChild.setChild(this, caseFileModel);
}
public Integer getCamundaHistoryTimeToLive() {
String ttl = getCamundaHistoryTimeToLiveString();
if (ttl != null) {
return Integer.parseInt(ttl);
}
return null;
}
public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) {
setCamundaHistoryTimeToLiveString(String.valueOf(historyTimeToLive));
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Case.class, CMMN_ELEMENT_CASE)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Case>() {
public Case newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
camundaHistoryTimeToLive = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_HISTORY_TIME_TO_LIVE)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
caseFileModelChild = sequenceBuilder.element(CaseFileModel.class)
.build();
casePlanModelChild = sequenceBuilder.element(CasePlanModel.class)
|
.build();
caseRolesCollection = sequenceBuilder.elementCollection(CaseRole.class)
.build();
caseRolesChild = sequenceBuilder.element(CaseRoles.class)
.build();
inputCollection = sequenceBuilder.elementCollection(InputCaseParameter.class)
.build();
outputCollection = sequenceBuilder.elementCollection(OutputCaseParameter.class)
.build();
typeBuilder.build();
}
@Override
public String getCamundaHistoryTimeToLiveString() {
return camundaHistoryTimeToLive.getValue(this);
}
@Override
public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) {
camundaHistoryTimeToLive.setValue(this, historyTimeToLive);
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseImpl.java
| 1
|
请完成以下Java代码
|
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_PA_ReportColumnSet[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
|
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Report Column Set.
@param PA_ReportColumnSet_ID
Collection of Columns for Report
*/
public void setPA_ReportColumnSet_ID (int PA_ReportColumnSet_ID)
{
if (PA_ReportColumnSet_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportColumnSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportColumnSet_ID, Integer.valueOf(PA_ReportColumnSet_ID));
}
/** Get Report Column Set.
@return Collection of Columns for Report
*/
public int getPA_ReportColumnSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportColumnSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportColumnSet.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static List toList() {
SettRecordStatusEnum[] ary = SettRecordStatusEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list;
}
/**
* 判断填入审核状态
*
* @param enumName
* @return
*/
public static boolean checkConfirm(String enumName) {
SettRecordStatusEnum[] enumAry = { SettRecordStatusEnum.CANCEL, SettRecordStatusEnum.CONFIRMED };
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
return true;
}
}
return false;
|
}
/**
* 判断填入打款状态
*
* @param enumName
* @return
*/
public static boolean checkRemit(String enumName) {
SettRecordStatusEnum[] enumAry = { SettRecordStatusEnum.REMIT_FAIL, SettRecordStatusEnum.REMIT_SUCCESS };
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
return true;
}
}
return false;
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\SettRecordStatusEnum.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DRIVER);
dataSource.setUrl(URL);
dataSource.setUsername(USERNAME);
dataSource.setPassword(PASSWORD);
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
|
hibernateProperties.put("hibernate.dialect", DIALECT);
hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
sessionFactory.setHibernateProperties(hibernateProperties);
return sessionFactory;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
|
repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\HibernateConfiguration.java
| 2
|
请完成以下Java代码
|
public void run(Runnable runnable) {
run(null, runnable);
}
/**
* Execute a {@link Runnable} binding the given {@link ConnectionFactory} and finally unbinding it.
* @param contextName the name of the context. In null, empty or blank, default context is bound.
* @param runnable the {@link Runnable} object to be executed.
* @throws RuntimeException when a RuntimeException is thrown by the {@link Runnable}.
*/
public void run(@Nullable String contextName, Runnable runnable) {
try {
bind(contextName);
runnable.run();
}
finally {
unbind(contextName);
}
}
/**
* Bind the context.
* @param contextName the name of the context for the connection factory.
*/
private void bind(@Nullable String contextName) {
|
if (StringUtils.hasText(contextName)) {
SimpleResourceHolder.bind(this.connectionFactory, contextName);
}
}
/**
* Unbind the context.
* @param contextName the name of the context for the connection factory.
*/
private void unbind(@Nullable String contextName) {
if (StringUtils.hasText(contextName)) {
SimpleResourceHolder.unbind(this.connectionFactory);
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\ConnectionFactoryContextWrapper.java
| 1
|
请完成以下Java代码
|
class HazelcastDockerComposeConnectionDetailsFactory
extends DockerComposeConnectionDetailsFactory<HazelcastConnectionDetails> {
private static final int DEFAULT_PORT = 5701;
protected HazelcastDockerComposeConnectionDetailsFactory() {
super("hazelcast/hazelcast", "com.hazelcast.client.config.ClientConfig");
}
@Override
protected HazelcastConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new HazelcastDockerComposeConnectionDetails(source.getRunningService());
}
/**
* {@link HazelcastConnectionDetails} backed by a {@code hazelcast}
* {@link RunningService}.
*/
static class HazelcastDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements HazelcastConnectionDetails {
private final String host;
private final int port;
private final HazelcastEnvironment environment;
HazelcastDockerComposeConnectionDetails(RunningService service) {
super(service);
|
this.host = service.host();
this.port = service.ports().get(DEFAULT_PORT);
this.environment = new HazelcastEnvironment(service.env());
}
@Override
public ClientConfig getClientConfig() {
ClientConfig config = new ClientConfig();
if (this.environment.getClusterName() != null) {
config.setClusterName(this.environment.getClusterName());
}
config.getNetworkConfig().addAddress(this.host + ":" + this.port);
return config;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-hazelcast\src\main\java\org\springframework\boot\hazelcast\docker\compose\HazelcastDockerComposeConnectionDetailsFactory.java
| 1
|
请完成以下Java代码
|
public PageData<Device> findDevicesByTenantIdAndEdgeIdAndType(UUID tenantId, UUID edgeId, String type, PageLink pageLink) {
log.debug("Try to find devices by tenantId [{}], edgeId [{}], type [{}] and pageLink [{}]", tenantId, edgeId, type, pageLink);
return DaoUtil.toPageData(deviceRepository
.findByTenantIdAndEdgeIdAndType(
tenantId,
edgeId,
type,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<DeviceIdInfo> findDeviceIdInfos(PageLink pageLink) {
log.debug("Try to find tenant device id infos by pageLink [{}]", pageLink);
return nativeDeviceRepository.findDeviceIdInfos(DaoUtil.toPageable(pageLink));
}
@Override
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfos(PageLink pageLink) {
log.debug("Find profile device id infos by pageLink [{}]", pageLink);
return nativeDeviceRepository.findProfileEntityIdInfos(DaoUtil.toPageable(pageLink));
}
@Override
public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, PageLink pageLink) {
log.debug("Find profile device id infos by tenantId[{}], pageLink [{}]", tenantId, pageLink);
return nativeDeviceRepository.findProfileEntityIdInfosByTenantId(tenantId, DaoUtil.toPageable(pageLink));
}
@Override
public Device findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(deviceRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public Device findByTenantIdAndName(UUID tenantId, String name) {
return findDeviceByTenantIdAndName(tenantId, name).orElse(null);
|
}
@Override
public PageData<Device> findByTenantId(UUID tenantId, PageLink pageLink) {
return findDevicesByTenantId(tenantId, pageLink);
}
@Override
public DeviceId getExternalIdByInternal(DeviceId internalId) {
return Optional.ofNullable(deviceRepository.getExternalIdById(internalId.getId()))
.map(DeviceId::new).orElse(null);
}
@Override
public PageData<Device> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<DeviceFields> findNextBatch(UUID id, int batchSize) {
return deviceRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceDao.java
| 1
|
请完成以下Java代码
|
public ImmutableSetMultimap<ShipmentScheduleId, CarrierServiceId> getAssignedServiceIdsMapByShipmentScheduleIds(@NonNull final ImmutableSet<ShipmentScheduleId> shipmentScheduleIds)
{
if (shipmentScheduleIds.isEmpty())
{
return ImmutableSetMultimap.of();
}
return queryBL.createQueryBuilder(I_M_ShipmentSchedule_Carrier_Service.class)
.addInArrayFilter(I_M_ShipmentSchedule_Carrier_Service.COLUMNNAME_M_ShipmentSchedule_ID, shipmentScheduleIds)
.create()
.stream()
.collect(ImmutableSetMultimap.toImmutableSetMultimap(
s -> ShipmentScheduleId.ofRepoId(s.getM_ShipmentSchedule_ID()),
s -> CarrierServiceId.ofRepoId(s.getCarrier_Service_ID())));
}
public void assignServicesToShipmentSchedule(@NonNull final ShipmentScheduleId shipmentScheduleId, final @NonNull Set<CarrierServiceId> serviceIds)
|
{
queryBL.createQueryBuilder(I_M_ShipmentSchedule_Carrier_Service.class)
.addEqualsFilter(I_M_ShipmentSchedule_Carrier_Service.COLUMNNAME_M_ShipmentSchedule_ID, shipmentScheduleId)
.create()
.delete();
final ImmutableSet<I_M_ShipmentSchedule_Carrier_Service> assignedCarrierServices = serviceIds.stream()
.map(serviceId -> {
final I_M_ShipmentSchedule_Carrier_Service po = InterfaceWrapperHelper.newInstance(I_M_ShipmentSchedule_Carrier_Service.class);
po.setM_ShipmentSchedule_ID(ShipmentScheduleId.toRepoId(shipmentScheduleId));
po.setCarrier_Service_ID(CarrierServiceId.toRepoId(serviceId));
return po;
})
.collect(ImmutableSet.toImmutableSet());
InterfaceWrapperHelper.saveAll(assignedCarrierServices);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\ShipmentScheduleCarrierServiceRepository.java
| 1
|
请完成以下Java代码
|
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
|
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public String toString() {
return "title: " + this.title
+ "\npost: " + this.post
+ "\nauthor: " + this.author
+"\ncreatetdAt: " + this.createdAt
+ "\nupdatedAt: " + this.updatedAt;
}
}
|
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\models\Post.java
| 1
|
请完成以下Java代码
|
public class SetUserInfoCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String userId;
protected String userPassword;
protected String type;
protected String key;
protected String value;
protected String accountPassword;
protected Map<String, String> accountDetails;
public SetUserInfoCmd(String userId, String key, String value) {
this.userId = userId;
this.type = IdentityInfoEntity.TYPE_USERINFO;
this.key = key;
this.value = value;
}
public SetUserInfoCmd(String userId, String userPassword, String accountName, String accountUsername, String accountPassword, Map<String, String> accountDetails) {
|
this.userId = userId;
this.userPassword = userPassword;
this.type = IdentityInfoEntity.TYPE_USERACCOUNT;
this.key = accountName;
this.value = accountUsername;
this.accountPassword = accountPassword;
this.accountDetails = accountDetails;
}
public Object execute(CommandContext commandContext) {
commandContext
.getIdentityInfoManager()
.setUserInfo(userId, userPassword, type, key, value, accountPassword, accountDetails);
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetUserInfoCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<AuthorityRuleEntity> apiUpdateParamFlowRule(@PathVariable("id") Long id,
@RequestBody AuthorityRuleEntity entity) {
if (id == null || id <= 0) {
return Result.ofFail(-1, "Invalid id");
}
Result<AuthorityRuleEntity> checkResult = checkEntityInternal(entity);
if (checkResult != null) {
return checkResult;
}
entity.setId(id);
Date date = new Date();
entity.setGmtCreate(null);
entity.setGmtModified(date);
try {
entity = repository.save(entity);
if (entity == null) {
return Result.ofFail(-1, "Failed to save authority rule");
}
publishRules(entity.getApp());
} catch (Throwable throwable) {
logger.error("Failed to save authority rule", throwable);
return Result.ofThrowable(-1, throwable);
}
return Result.ofSuccess(entity);
}
@DeleteMapping("/rule/{id}")
@AuthAction(PrivilegeType.DELETE_RULE)
public Result<Long> apiDeleteRule(@PathVariable("id") Long id) {
if (id == null) {
|
return Result.ofFail(-1, "id cannot be null");
}
AuthorityRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
publishRules(oldEntity.getApp());
} catch (Exception e) {
return Result.ofFail(-1, e.getMessage());
}
return Result.ofSuccess(id);
}
private void publishRules(String app) throws Exception {
List<AuthorityRuleEntity> rules = repository.findAllByApp(app);
rulePublisher.publish(app, rules);
//延迟加载
delayTime();
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\AuthorityRuleController.java
| 2
|
请完成以下Java代码
|
public String getDValue() {
return "M 10 0 C 4.4771525 0 0 4.4771525 0 10 C 0 15.522847 4.4771525 20 10 20 C 15.522847 20 20 15.522847 20 10 C 20 4.4771525 15.522847 1.1842379e-15 10 0 z M 9.09375 1.03125 C 9.2292164 1.0174926 9.362825 1.0389311 9.5 1.03125 L 9.5 3.5 L 10.5 3.5 L 10.5 1.03125 C 15.063526 1.2867831 18.713217 4.9364738 18.96875 9.5 L 16.5 9.5 L 16.5 10.5 L 18.96875 10.5 C 18.713217 15.063526 15.063526 18.713217 10.5 18.96875 L 10.5 16.5 L 9.5 16.5 L 9.5 18.96875 C 4.9364738 18.713217 1.2867831 15.063526 1.03125 10.5 L 3.5 10.5 L 3.5 9.5 L 1.03125 9.5 C 1.279102 5.0736488 4.7225326 1.4751713 9.09375 1.03125 z M 9.5 5 L 9.5 8.0625 C 8.6373007 8.2844627 8 9.0680195 8 10 C 8 11.104569 8.8954305 12 10 12 C 10.931981 12 11.715537 11.362699 11.9375 10.5 L 14 10.5 L 14 9.5 L 11.9375 9.5 C 11.756642 8.7970599 11.20294 8.2433585 10.5 8.0625 L 10.5 5 L 9.5 5 z ";
}
public void drawIcon(
final int imageX,
final int imageYo,
final int iconPadding,
final ProcessDiagramSVGGraphics2D svgGenerator
) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX) + "," + (imageYo) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getAnchorValue() {
return null;
}
@Override
public String getStyleValue() {
return null;
|
}
@Override
public Integer getWidth() {
return 20;
}
@Override
public Integer getHeight() {
return 20;
}
@Override
public String getStrokeWidth() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\TimerIconType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static Map<String, Object> updateAttributesFromRequestParams(HttpServletRequest request, Map<String, Object> attributes) {
Map<String, Object> updated = attributes;
MultiValueMap<String, String> params = toMultiMap(request.getParameterMap());
String userValue = params.getFirst(USER);
if (StringUtils.hasText(userValue)) {
JsonNode user = null;
try {
user = JacksonUtil.toJsonNode(userValue);
} catch (Exception e) {}
if (user != null) {
updated = new HashMap<>(attributes);
if (user.has(NAME)) {
JsonNode name = user.get(NAME);
if (name.isObject()) {
JsonNode firstName = name.get(FIRST_NAME);
if (firstName != null && firstName.isTextual()) {
updated.put(FIRST_NAME, firstName.asText());
}
JsonNode lastName = name.get(LAST_NAME);
if (lastName != null && lastName.isTextual()) {
updated.put(LAST_NAME, lastName.asText());
}
}
}
if (user.has(EMAIL)) {
JsonNode email = user.get(EMAIL);
if (email != null && email.isTextual()) {
updated.put(EMAIL, email.asText());
}
}
|
}
}
return updated;
}
private static MultiValueMap<String, String> toMultiMap(Map<String, String[]> map) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(map.size());
map.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
params.add(key, value);
}
}
});
return params;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\AppleOAuth2ClientMapper.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Comparator<I_C_BPartner_CreditLimit> createComparator()
{
final Comparator<I_C_BPartner_CreditLimit> byTypeSeqNoReversed = //
Comparator.<I_C_BPartner_CreditLimit, SeqNo>comparing(bpCreditLimit -> getCreditLimitTypeById(bpCreditLimit.getC_CreditLimit_Type_ID()).getSeqNo()).reversed();
final Comparator<I_C_BPartner_CreditLimit> byDateFromRevesed = //
Comparator.<I_C_BPartner_CreditLimit, Date>comparing(I_C_BPartner_CreditLimit::getDateFrom).reversed();
return byDateFromRevesed.thenComparing(byTypeSeqNoReversed);
}
public CreditLimitType getCreditLimitTypeById(final int C_CreditLimit_Type_ID)
{
return cache_creditLimitById.getOrLoad(C_CreditLimit_Type_ID, () -> retrieveCreditLimitTypePOJO(C_CreditLimit_Type_ID));
}
private CreditLimitType retrieveCreditLimitTypePOJO(final int C_CreditLimit_Type_ID)
{
final I_C_CreditLimit_Type type = queryBL
.createQueryBuilder(I_C_CreditLimit_Type.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_CreditLimit_Type.COLUMN_C_CreditLimit_Type_ID, C_CreditLimit_Type_ID)
.create()
.firstOnlyNotNull(I_C_CreditLimit_Type.class);
|
return CreditLimitType.builder()
.creditLimitTypeId(CreditLimitTypeId.ofRepoId(type.getC_CreditLimit_Type_ID()))
.seqNo(SeqNo.ofInt(type.getSeqNo()))
.name(type.getName())
.autoApproval(type.isAutoApproval())
.build();
}
public Optional<I_C_BPartner_CreditLimit> retrieveCreditLimitByBPartnerId(final int bpartnerId, final int typeId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_CreditLimit.class)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_Processed, true)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_C_CreditLimit_Type_ID, typeId)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.create()
.stream().min(comparator);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerCreditLimitRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Notification createNotification() {
return new Notification();
}
/**
* Create an instance of {@link Cod }
*
*/
public Cod createCod() {
return new Cod();
}
/**
* Create an instance of {@link Hazardous }
*
*/
public Hazardous createHazardous() {
return new Hazardous();
}
/**
* Create an instance of {@link PersonalDelivery }
*
*/
public PersonalDelivery createPersonalDelivery() {
return new PersonalDelivery();
}
/**
* Create an instance of {@link Pickup }
*
*/
public Pickup createPickup() {
return new Pickup();
}
/**
* Create an instance of {@link ParcelInformationType }
*
*/
public ParcelInformationType createParcelInformationType() {
return new ParcelInformationType();
}
/**
* Create an instance of {@link FaultCodeType }
*
*/
public FaultCodeType createFaultCodeType() {
return new FaultCodeType();
}
/**
* Create an instance of {@link HigherInsurance }
*
*/
public HigherInsurance createHigherInsurance() {
return new HigherInsurance();
}
/**
* Create an instance of {@link ParcelShopDelivery }
*
*/
public ParcelShopDelivery createParcelShopDelivery() {
|
return new ParcelShopDelivery();
}
/**
* Create an instance of {@link PrintOptions }
*
*/
public PrintOptions createPrintOptions() {
return new PrintOptions();
}
/**
* Create an instance of {@link Printer }
*
*/
public Printer createPrinter() {
return new Printer();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StoreOrders }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link StoreOrders }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/ShipmentService/3.2", name = "storeOrders")
public JAXBElement<StoreOrders> createStoreOrders(StoreOrders value) {
return new JAXBElement<StoreOrders>(_StoreOrders_QNAME, StoreOrders.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StoreOrdersResponse }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link StoreOrdersResponse }{@code >}
*/
@XmlElementDecl(namespace = "http://dpd.com/common/service/types/ShipmentService/3.2", name = "storeOrdersResponse")
public JAXBElement<StoreOrdersResponse> createStoreOrdersResponse(StoreOrdersResponse value) {
return new JAXBElement<StoreOrdersResponse>(_StoreOrdersResponse_QNAME, StoreOrdersResponse.class, null, value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ObjectFactory.java
| 2
|
请完成以下Java代码
|
public String createJWT(Authentication authentication, Boolean rememberMe) {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
return createJWT(rememberMe, userPrincipal.getId(), userPrincipal.getUsername(), userPrincipal.getRoles(), userPrincipal.getAuthorities());
}
/**
* 解析JWT
*
* @param jwt JWT
* @return {@link Claims}
*/
public Claims parseJWT(String jwt) {
try {
Claims claims = Jwts.parser().setSigningKey(jwtConfig.getKey()).parseClaimsJws(jwt).getBody();
String username = claims.getSubject();
String redisKey = Consts.REDIS_JWT_KEY_PREFIX + username;
// 校验redis中的JWT是否存在
Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.MILLISECONDS);
if (Objects.isNull(expire) || expire <= 0) {
throw new SecurityException(Status.TOKEN_EXPIRED);
}
// 校验redis中的JWT是否与当前的一致,不一致则代表用户已注销/用户在不同设备登录,均代表JWT已过期
String redisToken = stringRedisTemplate.opsForValue().get(redisKey);
if (!StrUtil.equals(jwt, redisToken)) {
throw new SecurityException(Status.TOKEN_OUT_OF_CTRL);
}
return claims;
} catch (ExpiredJwtException e) {
log.error("Token 已过期");
throw new SecurityException(Status.TOKEN_EXPIRED);
} catch (UnsupportedJwtException e) {
log.error("不支持的 Token");
throw new SecurityException(Status.TOKEN_PARSE_ERROR);
} catch (MalformedJwtException e) {
log.error("Token 无效");
throw new SecurityException(Status.TOKEN_PARSE_ERROR);
} catch (SignatureException e) {
log.error("无效的 Token 签名");
throw new SecurityException(Status.TOKEN_PARSE_ERROR);
} catch (IllegalArgumentException e) {
log.error("Token 参数不存在");
throw new SecurityException(Status.TOKEN_PARSE_ERROR);
}
}
|
/**
* 设置JWT过期
*
* @param request 请求
*/
public void invalidateJWT(HttpServletRequest request) {
String jwt = getJwtFromRequest(request);
String username = getUsernameFromJWT(jwt);
// 从redis中清除JWT
stringRedisTemplate.delete(Consts.REDIS_JWT_KEY_PREFIX + username);
}
/**
* 根据 jwt 获取用户名
*
* @param jwt JWT
* @return 用户名
*/
public String getUsernameFromJWT(String jwt) {
Claims claims = parseJWT(jwt);
return claims.getSubject();
}
/**
* 从 request 的 header 中获取 JWT
*
* @param request 请求
* @return JWT
*/
public String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StrUtil.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}
|
repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\util\JwtUtil.java
| 1
|
请完成以下Java代码
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
cause.printStackTrace();
ctx.close();
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2HeadersFrame) {
Http2HeadersFrame msgHeader = (Http2HeadersFrame) msg;
if (msgHeader.isEndStream()) {
ByteBuf content = ctx.alloc()
.buffer();
content.writeBytes(RESPONSE_BYTES.duplicate());
|
Http2Headers headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText());
ctx.write(new DefaultHttp2HeadersFrame(headers).stream(msgHeader.stream()));
ctx.write(new DefaultHttp2DataFrame(content, true).stream(msgHeader.stream()));
}
} else {
super.channelRead(ctx, msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
|
repos\tutorials-master\server-modules\netty\src\main\java\com\baeldung\netty\http2\server\Http2ServerResponseHandler.java
| 1
|
请完成以下Java代码
|
private ExplainedOptional<Plan> creatPlan()
{
return createPlan(getInvoiceRowsSelectedForAllocation(), action);
}
private static ITranslatableString computeCaption(@NonNull final Plan plan)
{
return TranslatableStrings.builder()
.appendADElement(plan.getAction().getColumnName()).append(": ").append(plan.getAmountToDiscountOrWriteOff())
.build();
}
@Override
protected String doIt()
{
final Plan plan = creatPlan().orElseThrow();
final I_C_Invoice invoice = invoiceBL.getById(plan.getInvoiceId());
final InvoiceAmtMultiplier amtMultiplier = plan.getAmtMultiplier();
final Money amountToDiscountOrWriteOff = amtMultiplier.convertToRealValue(plan.getAmountToDiscountOrWriteOff())
.toMoney(moneyService::getCurrencyIdByCurrencyCode);
allocationBL.invoiceDiscountAndWriteOff(
IAllocationBL.InvoiceDiscountAndWriteOffRequest.builder()
.invoice(invoice)
.dateTrx(TimeUtil.asInstant(p_DateTrx))
.discountAmt(plan.getAction() == PlanAction.Discount ? amountToDiscountOrWriteOff : null)
.writeOffAmt(plan.getAction() == PlanAction.WriteOff ? amountToDiscountOrWriteOff : null)
.build());
return MSG_OK;
}
//
//
//
private static ExplainedOptional<Plan> createPlan(@NonNull final ImmutableList<InvoiceRow> invoiceRows, final PlanAction action)
{
if (invoiceRows.size() != 1)
{
return ExplainedOptional.emptyBecause("Only one invoice row can be selected");
}
final InvoiceRow invoiceRow = CollectionUtils.singleElement(invoiceRows);
if (invoiceRow.getDocBaseType().isCreditMemo())
{
return ExplainedOptional.emptyBecause("Credit Memos are not eligible");
}
final Amount openAmt = invoiceRow.getOpenAmt();
if (openAmt.signum() == 0)
{
return ExplainedOptional.emptyBecause("Zero open amount");
}
return ExplainedOptional.of(
Plan.builder()
|
.invoiceId(invoiceRow.getInvoiceId())
.action(action)
.amtMultiplier(invoiceRow.getInvoiceAmtMultiplier())
.amountToDiscountOrWriteOff(openAmt)
.build());
}
@AllArgsConstructor
enum PlanAction
{
Discount("DiscountAmt"),
WriteOff("WriteOffAmt"),
;
// used mainly to build the action caption
@Getter
private final String columnName;
}
@Value
@Builder
private static class Plan
{
@NonNull InvoiceId invoiceId;
@NonNull PlanAction action;
@NonNull InvoiceAmtMultiplier amtMultiplier;
@NonNull Amount amountToDiscountOrWriteOff;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsView_InvoiceDiscountOrWriteOff.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQty(final I_C_UOM uomTo)
{
final ProductId productId = getProductId();
final I_C_UOM uomFrom = getC_UOM();
final BigDecimal qtySrc = getQty();
final BigDecimal qty = Services.get(IUOMConversionBL.class).convertQty(productId, qtySrc, uomFrom, uomTo);
return qty;
}
/**
*
* @return packing materials amount (qty) converted to given stocking unit of measure.
* @see IProductBL#getStockingUOM(I_M_Product)
*/
public BigDecimal getQtyInStockingUOM()
{
final I_C_UOM uomTo = Services.get(IProductBL.class).getStockUOM(product);
return getQty(uomTo);
}
protected void addQty(final int qtyToAdd)
{
qty = qty.add(BigDecimal.valueOf(qtyToAdd));
}
protected void subtractQty(final int qtyToSubtract)
{
qty = qty.subtract(BigDecimal.valueOf(qtyToSubtract));
}
/**
*
* @return packing materials amount(qty)'s unit of measure
*/
public I_C_UOM getC_UOM()
{
return uom;
}
private int getC_UOM_ID()
{
final int uomId = uom == null ? -1 : uom.getC_UOM_ID();
return uomId > 0 ? uomId : -1;
}
public I_M_Locator getM_Locator()
{
return locator;
}
private int getM_Locator_ID()
{
final int locatorId = locator == null ? -1 : locator.getM_Locator_ID();
return locatorId > 0 ? locatorId : -1;
}
public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1;
}
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
|
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID()
|| getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{
throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different
addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String deleteAll(@PathVariable String id) {
esSearchService.deleteAll();
return "success";
}
/**
* 根据ID获取
* @return
*/
@RequestMapping("get/{id}")
public ProductDocument getById(@PathVariable String id){
return esSearchService.getById(id);
}
/**
* 根据获取全部
* @return
*/
@RequestMapping("get_all")
public List<ProductDocument> getAll(){
return esSearchService.getAll();
}
/**
* 搜索
* @param keyword
* @return
*/
@RequestMapping("query/{keyword}")
public List<ProductDocument> query(@PathVariable String keyword){
return esSearchService.query(keyword,ProductDocument.class);
}
/**
* 搜索,命中关键字高亮
* http://localhost:8080/query_hit?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc
* @param keyword 关键字
* @param indexName 索引库名称
* @param fields 搜索字段名称,多个以“,”分割
* @return
*/
@RequestMapping("query_hit")
public List<Map<String,Object>> queryHit(@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){
String[] fieldNames = {};
if(fields.contains(",")) fieldNames = fields.split(",");
else fieldNames[0] = fields;
return esSearchService.queryHit(keyword,indexName,fieldNames);
|
}
/**
* 搜索,命中关键字高亮
* http://localhost:8080/query_hit_page?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc&pageNo=1&pageSize=1
* @param pageNo 当前页
* @param pageSize 每页显示的数据条数
* @param keyword 关键字
* @param indexName 索引库名称
* @param fields 搜索字段名称,多个以“,”分割
* @return
*/
@RequestMapping("query_hit_page")
public Page<Map<String,Object>> queryHitByPage(@RequestParam int pageNo,@RequestParam int pageSize
,@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){
String[] fieldNames = {};
if(fields.contains(",")) fieldNames = fields.split(",");
else fieldNames[0] = fields;
return esSearchService.queryHitByPage(pageNo,pageSize,keyword,indexName,fieldNames);
}
/**
* 删除索引库
* @param indexName
* @return
*/
@RequestMapping("delete_index/{indexName}")
public String deleteIndex(@PathVariable String indexName){
esSearchService.deleteIndex(indexName);
return "success";
}
}
|
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\controller\EsSearchController.java
| 2
|
请完成以下Java代码
|
public Builder setC_BPartner_ID(final int bpartnerId)
{
C_BPartner_ID = bpartnerId;
return this;
}
public Builder setC_Currency_ID(final int C_Currency_ID)
{
this.C_Currency_ID = C_Currency_ID;
return this;
}
public Builder setMultiCurrency(final boolean multiCurrency)
{
this.multiCurrency = multiCurrency;
return this;
}
public Builder setDate(final Date date)
{
this.date = date;
return this;
}
/**
* @param allowedWriteOffTypes allowed write-off types, in the same order they were enabled
*/
public Builder setAllowedWriteOffTypes(final Set<InvoiceWriteOffAmountType> allowedWriteOffTypes)
{
this.allowedWriteOffTypes.clear();
if (allowedWriteOffTypes != null)
{
this.allowedWriteOffTypes.addAll(allowedWriteOffTypes);
}
return this;
}
public Builder addAllowedWriteOffType(final InvoiceWriteOffAmountType allowedWriteOffType)
{
Check.assumeNotNull(allowedWriteOffType, "allowedWriteOffType not null");
|
allowedWriteOffTypes.add(allowedWriteOffType);
return this;
}
public Builder setWarningsConsumer(final IProcessor<Exception> warningsConsumer)
{
this.warningsConsumer = warningsConsumer;
return this;
}
public Builder setDocumentIdsToIncludeWhenQuering(final Multimap<AllocableDocType, Integer> documentIds)
{
this.documentIds = documentIds;
return this;
}
public Builder setFilter_Payment_ID(int filter_Payment_ID)
{
this.filterPaymentId = filter_Payment_ID;
return this;
}
public Builder setFilter_POReference(String filterPOReference)
{
this.filterPOReference = filterPOReference;
return this;
}
public Builder allowPurchaseSalesInvoiceCompensation(final boolean allowPurchaseSalesInvoiceCompensation)
{
this.allowPurchaseSalesInvoiceCompensation = allowPurchaseSalesInvoiceCompensation;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public EDICBPartnerLookupBPLGLNVType getCBPartnerID() {
return cbPartnerID;
}
/**
* Sets the value of the cbPartnerID property.
*
* @param value
* allowed object is
* {@link EDICBPartnerLookupBPLGLNVType }
*
*/
public void setCBPartnerID(EDICBPartnerLookupBPLGLNVType value) {
this.cbPartnerID = value;
}
/**
* Gets the value of the gln property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGLN() {
return gln;
|
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGLN(String value) {
this.gln = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIImpCBPartnerLocationLookupGLNType.java
| 2
|
请完成以下Java代码
|
public ImmutableList<UserDashboardItemDataResponse> getChangesFromOldVersion(@Nullable final Result oldResult)
{
if (oldResult == null)
{
return toList();
}
final ImmutableList.Builder<UserDashboardItemDataResponse> resultEffective = ImmutableList.builder();
for (final Map.Entry<UserDashboardItemId, UserDashboardItemDataResponse> e : map.entrySet())
{
final UserDashboardItemId itemId = e.getKey();
final UserDashboardItemDataResponse newValue = e.getValue();
final UserDashboardItemDataResponse oldValue = oldResult.get(itemId);
if (oldValue == null || !newValue.isSameDataAs(oldValue))
{
resultEffective.add(newValue);
}
}
|
return resultEffective.build();
}
@Nullable
private UserDashboardItemDataResponse get(final UserDashboardItemId itemId)
{
return map.get(itemId);
}
public ImmutableList<UserDashboardItemDataResponse> toList()
{
return ImmutableList.copyOf(map.values());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketProducer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
BigDecimal totalAmount = new BigDecimal("0");
for (OmsOrderItem item : orderItemList) {
totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
}
return totalAmount;
}
/**
* 锁定下单商品的所有库存
*/
private void lockStock(List<CartPromotionItem> cartPromotionItemList) {
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId());
skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
int count = portalOrderDao.lockStockBySkuId(cartPromotionItem.getProductSkuId(),cartPromotionItem.getQuantity());
if(count==0){
Asserts.fail("库存不足,无法下单");
}
}
}
/**
* 判断下单商品是否都有库存
*/
private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
if (cartPromotionItem.getRealStock()==null //判断真实库存是否为空
||cartPromotionItem.getRealStock() <= 0 //判断真实库存是否小于0
|| cartPromotionItem.getRealStock() < cartPromotionItem.getQuantity()) //判断真实库存是否小于下单的数量
{
return false;
}
|
}
return true;
}
/**
* 计算购物车中商品的价格
*/
private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
calcAmount.setFreightAmount(new BigDecimal(0));
BigDecimal totalAmount = new BigDecimal("0");
BigDecimal promotionAmount = new BigDecimal("0");
for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
}
calcAmount.setTotalAmount(totalAmount);
calcAmount.setPromotionAmount(promotionAmount);
calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));
return calcAmount;
}
}
|
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\OmsPortalOrderServiceImpl.java
| 2
|
请完成以下Java代码
|
public int untag()
{
return invoiceCandDAO.untag(this);
}
@Override
public Iterator<I_C_Invoice_Candidate> retrieveInvoiceCandidates()
{
final Properties ctx = getCtx();
final String trxName = getTrxName();
final InvoiceCandRecomputeTag recomputeTag = getRecomputeTag();
return invoiceCandDAO.fetchInvalidInvoiceCandidates(ctx, recomputeTag, trxName);
}
@Override
public IInvoiceCandRecomputeTagger setContext(final Properties ctx, final String trxName)
{
this._ctx = ctx;
this._trxName = trxName;
return this;
}
@Override
public final Properties getCtx()
{
Check.assumeNotNull(_ctx, "_ctx not null");
return _ctx;
}
String getTrxName()
{
return _trxName;
}
@Override
public IInvoiceCandRecomputeTagger setRecomputeTag(final InvoiceCandRecomputeTag recomputeTag)
{
this._recomputeTagToUseForTagging = recomputeTag;
return this;
}
private void generateRecomputeTagIfNotSet()
{
// Do nothing if the recompute tag was already generated
if (!InvoiceCandRecomputeTag.isNull(_recomputeTag))
{
return;
}
// Use the recompute tag which was suggested
if (!InvoiceCandRecomputeTag.isNull(_recomputeTagToUseForTagging))
{
_recomputeTag = _recomputeTagToUseForTagging;
return;
}
// Generate a new recompute tag
_recomputeTag = invoiceCandDAO.generateNewRecomputeTag();
}
/**
* @return recompute tag; never returns null
*/
final InvoiceCandRecomputeTag getRecomputeTag()
{
Check.assumeNotNull(_recomputeTag, "_recomputeTag not null");
return _recomputeTag;
}
@Override
public InvoiceCandRecomputeTagger setLockedBy(final ILock lockedBy)
{
this._lockedBy = lockedBy;
return this;
}
/* package */ILock getLockedBy()
|
{
return _lockedBy;
}
@Override
public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag)
{
_taggedWith = tag;
return this;
}
@Override
public InvoiceCandRecomputeTagger setTaggedWithNoTag()
{
return setTaggedWith(InvoiceCandRecomputeTag.NULL);
}
@Override
public IInvoiceCandRecomputeTagger setTaggedWithAnyTag()
{
return setTaggedWith(null);
}
/* package */
@Nullable
InvoiceCandRecomputeTag getTaggedWith()
{
return _taggedWith;
}
@Override
public InvoiceCandRecomputeTagger setLimit(final int limit)
{
this._limit = limit;
return this;
}
/* package */int getLimit()
{
return _limit;
}
@Override
public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds)
{
this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds;
}
@Override
@Nullable
public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds()
{
return onlyInvoiceCandidateIds;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BookstoreService {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
public BookstoreService(AuthorRepository authorRepository,
BookRepository bookRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
}
@Transactional
public void insertNewBook() {
Author author = authorRepository.getOne(4L);
// or, less efficient since a SELECT is triggered
// Author author = authorRepository.findByName("Joana Nimar");
Book book = new Book();
book.setIsbn("003-JN");
book.setTitle("History Of Present");
book.setAuthor(author);
bookRepository.save(book);
}
public void fetchBooksOfAuthorById() {
List<Book> books = bookRepository.fetchBooksOfAuthorById(4L);
System.out.println(books);
}
public void fetchPageBooksOfAuthorById() {
Page<Book> books = bookRepository.fetchPageBooksOfAuthorById(4L,
PageRequest.of(0, 2, Sort.by(Sort.Direction.ASC, "title")));
books.get().forEach(System.out::println);
}
@Transactional
public void fetchBooksOfAuthorByIdAndAddNewBook() {
List<Book> books = bookRepository.fetchBooksOfAuthorById(4L);
|
Book book = new Book();
book.setIsbn("004-JN");
book.setTitle("History Facts");
book.setAuthor(books.get(0).getAuthor());
books.add(bookRepository.save(book));
System.out.println(books);
}
@Transactional
public void fetchBooksOfAuthorByIdAndDeleteFirstBook() {
List<Book> books = bookRepository.fetchBooksOfAuthorById(4L);
bookRepository.delete(books.remove(0));
System.out.println(books);
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootJustManyToOne\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请完成以下Java代码
|
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
BoundaryEvent boundaryEvent = (BoundaryEvent) execution.getCurrentFlowElement();
Object eventInstance = execution.getTransientVariables().get(EventConstants.EVENT_INSTANCE);
if (eventInstance instanceof EventInstance) {
EventInstanceBpmnUtil.handleEventInstanceOutParameters(execution, boundaryEvent, (EventInstance) eventInstance);
}
if (boundaryEvent.isCancelActivity()) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
EventSubscriptionService eventSubscriptionService = processEngineConfiguration.getEventSubscriptionServiceConfiguration().getEventSubscriptionService();
List<EventSubscriptionEntity> eventSubscriptions = executionEntity.getEventSubscriptions();
String eventDefinitionKey = getEventDefinitionKey(executionEntity, processEngineConfiguration);
for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
if (Objects.equals(eventDefinitionKey, eventSubscription.getEventType())) {
eventSubscriptionService.deleteEventSubscription(eventSubscription);
CountingEntityUtil.handleDeleteEventSubscriptionEntityCount(eventSubscription);
}
}
}
super.trigger(executionEntity, triggerName, triggerData);
}
protected String getEventDefinitionKey(ExecutionEntity executionEntity, ProcessEngineConfigurationImpl processEngineConfiguration) {
|
Object key = null;
if (StringUtils.isNotEmpty(eventDefinitionKey)) {
Expression expression = processEngineConfiguration.getExpressionManager()
.createExpression(eventDefinitionKey);
key = expression.getValue(executionEntity);
}
if (key == null) {
throw new FlowableException("Could not resolve key for: " + eventDefinitionKey + " in " + executionEntity);
}
return key.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\behavior\BoundaryEventRegistryEventActivityBehavior.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static AutoConfigurationMetadata loadMetadata(ClassLoader classLoader) {
return loadMetadata(classLoader, PATH);
}
static AutoConfigurationMetadata loadMetadata(@Nullable ClassLoader classLoader, String path) {
try {
Enumeration<URL> urls = (classLoader != null) ? classLoader.getResources(path)
: ClassLoader.getSystemResources(path);
Properties properties = new Properties();
while (urls.hasMoreElements()) {
properties.putAll(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement())));
}
return loadMetadata(properties);
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load @ConditionalOnClass location [" + path + "]", ex);
}
}
static AutoConfigurationMetadata loadMetadata(Properties properties) {
return new PropertiesAutoConfigurationMetadata(properties);
}
/**
* {@link AutoConfigurationMetadata} implementation backed by a properties file.
*/
private static class PropertiesAutoConfigurationMetadata implements AutoConfigurationMetadata {
private final Properties properties;
PropertiesAutoConfigurationMetadata(Properties properties) {
this.properties = properties;
}
@Override
public boolean wasProcessed(String className) {
return this.properties.containsKey(className);
}
@Override
public @Nullable Integer getInteger(String className, String key) {
return getInteger(className, key, null);
|
}
@Override
public @Nullable Integer getInteger(String className, String key, @Nullable Integer defaultValue) {
String value = get(className, key);
return (value != null) ? Integer.valueOf(value) : defaultValue;
}
@Override
public @Nullable Set<String> getSet(String className, String key) {
return getSet(className, key, null);
}
@Override
public @Nullable Set<String> getSet(String className, String key, @Nullable Set<String> defaultValue) {
String value = get(className, key);
return (value != null) ? StringUtils.commaDelimitedListToSet(value) : defaultValue;
}
@Override
public @Nullable String get(String className, String key) {
return get(className, key, null);
}
@Override
public @Nullable String get(String className, String key, @Nullable String defaultValue) {
String value = this.properties.getProperty(className + "." + key);
return (value != null) ? value : defaultValue;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationMetadataLoader.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Result<?> sync(@PathVariable(name = "id", required = true) String id) {
return airagMcpService.sync(id);
}
/**
* 启用/禁用MCP信息
*
* @param action 启用:enable,禁用:disable
* @return
* @author chenrui
* @date 2025/10/20 20:13
*/
@Operation(summary = "MCP-启用/禁用MCP信息")
@PostMapping(value = "/status/{id}/{action}")
public Result<?> toggleStatus(@PathVariable(name = "id",required = true) String id,
@PathVariable(name = "action", required = true) String action) {
return airagMcpService.toggleStatus(id,action);
}
/**
* 保存插件工具
* for [QQYUN-12453]【AI】支持插件
* @param dto 包含插件ID和工具列表JSON字符串的DTO
* @return
* @author chenrui
* @date 2025/10/30
*/
@Operation(summary = "MCP-保存插件工具")
@PostMapping(value = "/saveTools")
public Result<String> saveTools(@RequestBody SaveToolsDTO dto) {
return airagMcpService.saveTools(dto.getId(), dto.getTools());
}
/**
* 通过id删除
*
* @param id
* @return
*/
@Operation(summary = "MCP-通过id删除")
@DeleteMapping(value = "/delete")
public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
airagMcpService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@Operation(summary = "MCP-通过id查询")
@GetMapping(value = "/queryById")
public Result<AiragMcp> queryById(@RequestParam(name = "id", required = true) String id) {
AiragMcp airagMcp = airagMcpService.getById(id);
if (airagMcp == null) {
return Result.error("未找到对应数据");
|
}
return Result.OK(airagMcp);
}
/**
* 导出excel
*
* @param request
* @param airagMcp
*/
// @RequiresPermissions("llm:airag_mcp:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, AiragMcp airagMcp) {
return super.exportXls(request, airagMcp, AiragMcp.class, "MCP");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
// @RequiresPermissions("llm:airag_mcp:importExcel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, AiragMcp.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\controller\AiragMcpController.java
| 2
|
请完成以下Java代码
|
public int getM_Securpharm_Productdata_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Securpharm_Productdata_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verification Code.
@param PackVerificationCode Verification Code */
@Override
public void setPackVerificationCode (java.lang.String PackVerificationCode)
{
set_Value (COLUMNNAME_PackVerificationCode, PackVerificationCode);
}
/** Get Verification Code.
@return Verification Code */
@Override
public java.lang.String getPackVerificationCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_PackVerificationCode);
}
/** Set Verification Message.
@param PackVerificationMessage Verification Message */
@Override
public void setPackVerificationMessage (java.lang.String PackVerificationMessage)
{
set_Value (COLUMNNAME_PackVerificationMessage, PackVerificationMessage);
}
/** Get Verification Message.
@return Verification Message */
@Override
public java.lang.String getPackVerificationMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_PackVerificationMessage);
}
/** Set Produktcode.
@param ProductCode Produktcode */
@Override
public void setProductCode (java.lang.String ProductCode)
{
set_ValueNoCheck (COLUMNNAME_ProductCode, ProductCode);
}
/** Get Produktcode.
@return Produktcode */
@Override
public java.lang.String getProductCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductCode);
}
/** Set Kodierungskennzeichen.
@param ProductCodeType
Kodierungskennzeichen
*/
@Override
public void setProductCodeType (java.lang.String ProductCodeType)
{
set_ValueNoCheck (COLUMNNAME_ProductCodeType, ProductCodeType);
|
}
/** Get Kodierungskennzeichen.
@return Kodierungskennzeichen
*/
@Override
public java.lang.String getProductCodeType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductCodeType);
}
/**
* SerialNumber AD_Reference_ID=110
* Reference name: AD_User
*/
public static final int SERIALNUMBER_AD_Reference_ID=110;
/** Set Seriennummer.
@param SerialNumber Seriennummer */
@Override
public void setSerialNumber (java.lang.String SerialNumber)
{
set_ValueNoCheck (COLUMNNAME_SerialNumber, SerialNumber);
}
/** Get Seriennummer.
@return Seriennummer */
@Override
public java.lang.String getSerialNumber ()
{
return (java.lang.String)get_Value(COLUMNNAME_SerialNumber);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Productdata_Result.java
| 1
|
请完成以下Java代码
|
public class HistoricVariableInstanceResourceImpl extends
AbstractResourceProvider<HistoricVariableInstanceQuery, HistoricVariableInstance, HistoricVariableInstanceDto> implements HistoricVariableInstanceResource {
public HistoricVariableInstanceResourceImpl(String variableId, ProcessEngine engine) {
super(variableId, engine);
}
protected HistoricVariableInstanceQuery baseQuery() {
return getEngine().getHistoryService().createHistoricVariableInstanceQuery().variableId(getId());
}
@Override
protected Query<HistoricVariableInstanceQuery, HistoricVariableInstance> baseQueryForBinaryVariable() {
return baseQuery().disableCustomObjectDeserialization();
}
@Override
protected Query<HistoricVariableInstanceQuery, HistoricVariableInstance> baseQueryForVariable(boolean deserializeObjectValue) {
HistoricVariableInstanceQuery query = baseQuery().disableBinaryFetching();
if (!deserializeObjectValue) {
query.disableCustomObjectDeserialization();
}
return query;
}
@Override
protected TypedValue transformQueryResultIntoTypedValue(HistoricVariableInstance queryResult) {
|
return queryResult.getTypedValue();
}
@Override
protected HistoricVariableInstanceDto transformToDto(HistoricVariableInstance queryResult) {
return HistoricVariableInstanceDto.fromHistoricVariableInstance(queryResult);
}
@Override
protected String getResourceNameForErrorMessage() {
return "Historic variable instance";
}
@Override
public Response deleteVariableInstance() {
try {
getEngine().getHistoryService().deleteHistoricVariableInstance(id);
} catch (NotFoundException nfe) { // rewrite status code from bad request (400) to not found (404)
throw new InvalidRequestException(Status.NOT_FOUND, nfe, nfe.getMessage());
}
// return no content (204) since resource is deleted
return Response.noContent().build();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\history\impl\HistoricVariableInstanceResourceImpl.java
| 1
|
请完成以下Java代码
|
public int getM_Material_Tracking_Report_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set M_Material_Tracking_Report_Line.
@param M_Material_Tracking_Report_Line_ID M_Material_Tracking_Report_Line */
@Override
public void setM_Material_Tracking_Report_Line_ID (int M_Material_Tracking_Report_Line_ID)
{
if (M_Material_Tracking_Report_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Report_Line_ID, Integer.valueOf(M_Material_Tracking_Report_Line_ID));
}
/** Get M_Material_Tracking_Report_Line.
@return M_Material_Tracking_Report_Line */
@Override
public int getM_Material_Tracking_Report_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Report_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@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_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
|
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausgelagerte Menge.
@param QtyIssued Ausgelagerte Menge */
@Override
public void setQtyIssued (java.math.BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
}
/** Get Ausgelagerte Menge.
@return Ausgelagerte Menge */
@Override
public java.math.BigDecimal getQtyIssued ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Empfangene Menge.
@param QtyReceived Empfangene Menge */
@Override
public void setQtyReceived (java.math.BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report_Line.java
| 1
|
请完成以下Java代码
|
private String getExcelReport(final MAlertRule rule, final String sql, final Collection<File> attachments) throws Exception
{
final SpreadsheetExporterService spreadsheetExporterService = SpringContextHolder.instance.getBean(SpreadsheetExporterService.class);
final File file = rule.createReportFile(ExcelFormats.getDefaultFileExtension());
final JdbcExcelExporter jdbcExcelExporter = JdbcExcelExporter.builder()
.ctx(getCtx())
.resultFile(file)
.build();
spreadsheetExporterService.processDataFromSQL(sql, jdbcExcelExporter);
if(jdbcExcelExporter.isNoDataAddedYet())
{
return null;
}
|
attachments.add(file);
final String msg = rule.getName() + " (@SeeAttachment@ " + file.getName() + ")" + Env.NL;
return Msg.parseTranslation(Env.getCtx(), msg);
}
/**
* Get Server Info
*
* @return info
*/
@Override
public String getServerInfo()
{
return "#" + getRunCount() + " - Last=" + m_summary.toString();
} // getServerInfo
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AlertProcessor.java
| 1
|
请完成以下Java代码
|
public boolean isSchedAllowsConsolidate(@NonNull final I_M_ShipmentSchedule sched)
{
final int orderID = sched.getC_Order_ID();
if (orderID <= 0)
{
return true; // if there is no order, there won't be a DESADV.
}
final I_C_Order orderRecord = orderDAO
.retrieveByOrderCriteria(OrderQuery.builder()
.orderId(orderID)
.orgId(OrgId.ofRepoId(sched.getAD_Org_ID()))
.build())
.orElseThrow(() -> new AdempiereException("Unable to retrieve C_Order for C_Order_ID=" + orderID));
final int desadvID = InterfaceWrapperHelper.create(orderRecord, de.metas.edi.model.I_C_Order.class).getEDI_Desadv_ID();
|
if (desadvID <= 0)
{
return true; // if the order doesn't have a desadv, we shouldn't bother
}
final boolean isMatchUsingOrderId = desadvBL.isMatchUsingOrderId(ClientId.ofRepoId(sched.getAD_Client_ID()));
if (isMatchUsingOrderId)
{
logger.debug("According to the SysConfig de.metas.edi.desadv.MatchUsingC_Order_ID consolidation into one shipment is not allowed");
return false;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\MatchOrderIdShipmentScheduleConsolidatePredicate.java
| 1
|
请完成以下Java代码
|
protected void writeStartTagClose(HtmlWriteContext context) {
StringWriter writer = context.getWriter();
if(isSelfClosing) {
writer.write(" /");
}
writer.write(">");
}
protected void writeLeadingWhitespace(HtmlWriteContext context) {
int stackSize = context.getElementStackSize();
StringWriter writer = context.getWriter();
for (int i = 0; i < stackSize; i++) {
writer.write(" ");
}
}
// builder /////////////////////////////////////
|
public HtmlElementWriter attribute(String name, String value) {
attributes.put(name, value);
return this;
}
public HtmlElementWriter textContent(String text) {
if(isSelfClosing) {
throw new IllegalStateException("Self-closing element cannot have text content.");
}
this.textContent = text;
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\HtmlElementWriter.java
| 1
|
请完成以下Java代码
|
public Object getBehavior() {
return behavior;
}
public void setBehavior(Object behavior) {
this.behavior = behavior;
}
public List<PlanItem> getEntryDependencies() {
return entryDependencies;
}
public void setEntryDependencies(List<PlanItem> entryDependencies) {
this.entryDependencies = entryDependencies;
}
public List<PlanItem> getExitDependencies() {
return exitDependencies;
}
public void setExitDependencies(List<PlanItem> exitDependencies) {
this.exitDependencies = exitDependencies;
}
public List<PlanItem> getEntryDependentPlanItems() {
return entryDependentPlanItems;
}
public void setEntryDependentPlanItems(List<PlanItem> entryDependentPlanItems) {
this.entryDependentPlanItems = entryDependentPlanItems;
}
public void addEntryDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = entryDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
entryDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getExitDependentPlanItems() {
return exitDependentPlanItems;
}
public void setExitDependentPlanItems(List<PlanItem> exitDependentPlanItems) {
|
this.exitDependentPlanItems = exitDependentPlanItems;
}
public void addExitDependentPlanItem(PlanItem planItem) {
Optional<PlanItem> planItemWithSameId = exitDependentPlanItems.stream().filter(p -> p.getId().equals(planItem.getId())).findFirst();
if (!planItemWithSameId.isPresent()) {
exitDependentPlanItems.add(planItem);
}
}
public List<PlanItem> getAllDependentPlanItems() {
List<PlanItem> allDependentPlanItems = new ArrayList<>(entryDependentPlanItems.size() + exitDependentPlanItems.size());
allDependentPlanItems.addAll(entryDependentPlanItems);
allDependentPlanItems.addAll(exitDependentPlanItems);
return allDependentPlanItems;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("PlanItem");
if (getName() != null) {
stringBuilder.append(" '").append(getName()).append("'");
}
stringBuilder.append(" (id: ");
stringBuilder.append(getId());
if (getPlanItemDefinition() != null) {
stringBuilder.append(", definitionId: ").append(getPlanItemDefinition().getId());
}
stringBuilder.append(")");
return stringBuilder.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\PlanItem.java
| 1
|
请完成以下Java代码
|
public AuthenticationMethod1Code getAuthntcnMtd() {
return authntcnMtd;
}
/**
* Sets the value of the authntcnMtd property.
*
* @param value
* allowed object is
* {@link AuthenticationMethod1Code }
*
*/
public void setAuthntcnMtd(AuthenticationMethod1Code value) {
this.authntcnMtd = value;
}
/**
* Gets the value of the authntcnNtty property.
*
* @return
* possible object is
* {@link AuthenticationEntity1Code }
*
*/
public AuthenticationEntity1Code getAuthntcnNtty() {
|
return authntcnNtty;
}
/**
* Sets the value of the authntcnNtty property.
*
* @param value
* allowed object is
* {@link AuthenticationEntity1Code }
*
*/
public void setAuthntcnNtty(AuthenticationEntity1Code value) {
this.authntcnNtty = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\CardholderAuthentication2.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public PatientDeliveryAddress city(String city) {
this.city = city;
return this;
}
/**
* Get city
* @return city
**/
@Schema(example = "Nürnberg", description = "")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientDeliveryAddress patientDeliveryAddress = (PatientDeliveryAddress) o;
return Objects.equals(this.gender, patientDeliveryAddress.gender) &&
Objects.equals(this.title, patientDeliveryAddress.title) &&
Objects.equals(this.name, patientDeliveryAddress.name) &&
Objects.equals(this.address, patientDeliveryAddress.address) &&
Objects.equals(this.postalCode, patientDeliveryAddress.postalCode) &&
Objects.equals(this.city, patientDeliveryAddress.city);
}
|
@Override
public int hashCode() {
return Objects.hash(gender, title, name, address, postalCode, city);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientDeliveryAddress {\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientDeliveryAddress.java
| 2
|
请完成以下Java代码
|
public void removeAllActions()
{
actions.clear();
}
@Override
public void addAction(final ISideAction action)
{
if (actions.contains(action))
{
return;
}
actions.addElement(action);
}
@Override
public void removeAction(final int index)
{
actions.remove(index);
}
|
@Override
public void setActions(final Iterable<? extends ISideAction> actions)
{
this.actions.clear();
if (actions != null)
{
final List<ISideAction> actionsList = ListUtils.copyAsList(actions);
Collections.sort(actionsList, ISideAction.COMPARATOR_ByDisplayName);
for (final ISideAction action : actionsList)
{
this.actions.addElement(action);
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\SideActionsGroupModel.java
| 1
|
请完成以下Java代码
|
public static SpinJsonNode JSON(Object input) {
return SpinFactory.INSTANCE.createSpin(input, DataFormats.json());
}
/**
* Provides the name of the dataformat used by this spin.
*
* @return the name of the dataformat used by this Spin.
*/
public abstract String getDataFormatName();
/**
* Return the wrapped object. The return type of this method
* depends on the concrete data format.
*
* @return the object wrapped by this wrapper.
*/
public abstract Object unwrap();
/**
* Returns the wrapped object as string representation.
*
* @return the string representation
*/
public abstract String toString();
/**
* Writes the wrapped object to a existing writer.
*
|
* @param writer the writer to write to
*/
public abstract void writeToWriter(Writer writer);
/**
* Maps the wrapped object to an instance of a java class.
*
* @param type the java class to map to
* @return the mapped object
*/
public abstract <C> C mapTo(Class<C> type);
/**
* Maps the wrapped object to a java object.
* The object is determined based on the configuration string
* which is data format specific.
*
* @param type the class name to map to
* @return the mapped object
*/
public abstract <C> C mapTo(String type);
}
|
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\Spin.java
| 1
|
请完成以下Java代码
|
public List<I_C_SubscriptionProgress> getSubscriptionProgress(@NonNull final I_C_Flatrate_Term currentTerm)
{
final ISubscriptionDAO subscriptionDAO = Services.get(ISubscriptionDAO.class);
final SubscriptionProgressQuery currentTermQuery = SubscriptionProgressQuery.term(currentTerm).build();
return subscriptionDAO.retrieveSubscriptionProgresses(currentTermQuery);
}
@Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#OrderId")
@Override
public List<I_C_Flatrate_Term> retrieveFlatrateTermsForOrderIdLatestFirst(@NonNull final OrderId orderId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId)
.andCollectChildren(I_C_Flatrate_Term.COLUMN_C_OrderLine_Term_ID, I_C_Flatrate_Term.class)
.orderByDescending(I_C_Flatrate_Term.COLUMN_EndDate)
.create()
.list();
}
@Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#BPartnerId")
@Override
@Nullable
public I_C_Flatrate_Term retrieveLatestFlatrateTermForBPartnerId(@NonNull final BPartnerId bpartnerId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_C_Flatrate_Term.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bpartnerId.getRepoId())
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMNNAME_MasterEndDate, Direction.Descending, Nulls.Last)
.addColumn(I_C_Flatrate_Term.COLUMNNAME_EndDate, Direction.Descending, Nulls.Last)
.endOrderBy()
.create()
.first();
}
@Cached(cacheName = I_C_Flatrate_Term.Table_Name + "#by#BPartnerId")
@Override
|
@Nullable
public I_C_Flatrate_Term retrieveFirstFlatrateTermForBPartnerId(@NonNull final BPartnerId bpartnerId)
{
return Services.get(IQueryBL.class).createQueryBuilder(I_C_Flatrate_Term.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.addEqualsFilter(I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID, bpartnerId)
.orderBy()
.addColumn(I_C_Flatrate_Term.COLUMNNAME_MasterStartDate, Direction.Ascending, Nulls.Last)
.addColumn(I_C_Flatrate_Term.COLUMNNAME_StartDate, Direction.Ascending, Nulls.Last)
.endOrderBy()
.create()
.first();
}
@Override
@NonNull
public <T extends I_C_Flatrate_Conditions> T getConditionsById(@NonNull final ConditionsId conditionsId, @NonNull final Class<T> modelClass)
{
return InterfaceWrapperHelper.load(conditionsId, modelClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\ContractsDAO.java
| 1
|
请完成以下Java代码
|
protected void executeParse(BpmnParse bpmnParse, SignalEventDefinition signalDefinition) {
Signal signal = null;
if (bpmnParse.getBpmnModel().containsSignalId(signalDefinition.getSignalRef())) {
signal = bpmnParse.getBpmnModel().getSignal(signalDefinition.getSignalRef());
}
if (bpmnParse.getCurrentFlowElement() instanceof IntermediateCatchEvent) {
IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) bpmnParse.getCurrentFlowElement();
intermediateCatchEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createIntermediateCatchSignalEventActivityBehavior(
intermediateCatchEvent,
signalDefinition,
signal
)
);
|
} else if (bpmnParse.getCurrentFlowElement() instanceof BoundaryEvent) {
BoundaryEvent boundaryEvent = (BoundaryEvent) bpmnParse.getCurrentFlowElement();
boundaryEvent.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createBoundarySignalEventActivityBehavior(
boundaryEvent,
signalDefinition,
signal,
boundaryEvent.isCancelActivity()
)
);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SignalEventDefinitionParseHandler.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.