instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public CaseInstanceStartEventSubscriptionBuilder caseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
return this;
}
@Override
public CaseInstanceStartEventSubscriptionBuilder doNotUpdateToLatestVersionAutomatically() {
this.doNotUpdateToLatestVersionAutomatically = true;
return this;
}
@Override
public CaseInstanceStartEventSubscriptionBuilder addCorrelationParameterValue(String parameterName, Object parameterValue) {
correlationParameterValues.put(parameterName, parameterValue);
return this;
}
@Override
public CaseInstanceStartEventSubscriptionBuilder addCorrelationParameterValues(Map<String, Object> parameters) {
correlationParameterValues.putAll(parameters);
return this;
}
@Override
public CaseInstanceStartEventSubscriptionBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
} | public Map<String, Object> getCorrelationParameterValues() {
return correlationParameterValues;
}
public boolean isDoNotUpdateToLatestVersionAutomatically() {
return doNotUpdateToLatestVersionAutomatically;
}
public String getTenantId() {
return tenantId;
}
@Override
public EventSubscription subscribe() {
checkValidInformation();
return cmmnRuntimeService.registerCaseInstanceStartEventSubscription(this);
}
protected void checkValidInformation() {
if (StringUtils.isEmpty(caseDefinitionKey)) {
throw new FlowableIllegalArgumentException("The case definition must be provided using the key for the subscription to be registered.");
}
if (correlationParameterValues.isEmpty()) {
throw new FlowableIllegalArgumentException(
"At least one correlation parameter value must be provided for a dynamic case start event subscription, "
+ "otherwise the case would get started on all events, regardless their correlation parameter values.");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CaseInstanceStartEventSubscriptionBuilderImpl.java | 1 |
请完成以下Java代码 | public LdapSearchResults search(String baseDn, String searchFilter) {
try {
return new LdapSearchResults(initialContext.search(baseDn, searchFilter, ldapConfiguration.getSearchControls()));
} catch (NamingException e) {
throw new IdentityProviderException("LDAP search request failed.", e);
}
}
public void setRequestControls(List<Control> listControls) {
try {
initialContext.setRequestControls(listControls.toArray(new Control[0]));
} catch (NamingException e) {
throw new IdentityProviderException("LDAP server failed to set request controls.", e);
}
}
public Control[] getResponseControls() {
try {
return initialContext.getResponseControls();
} catch (NamingException e) {
throw new IdentityProviderException("Error occurred while getting the response controls from the LDAP server.", e);
}
}
public static void addPaginationControl(List<Control> listControls, byte[] cookie, Integer pageSize) {
try {
listControls.add(new PagedResultsControl(pageSize, cookie, Control.NONCRITICAL));
} catch (IOException e) {
throw new IdentityProviderException("Pagination couldn't be enabled.", e);
}
}
public static void addSortKey(SortKey sortKey, List<Control> controls) {
try {
controls.add(new SortControl(new SortKey[] { sortKey }, Control.CRITICAL));
} catch (IOException e) {
throw new IdentityProviderException("Sorting couldn't be enabled.", e); | }
}
protected static String getValue(String attrName, Attributes attributes) {
Attribute attribute = attributes.get(attrName);
if (attribute != null) {
try {
return (String) attribute.get();
} catch (NamingException e) {
throw new IdentityProviderException("Error occurred while retrieving the value.", e);
}
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public static NamingEnumeration<String> getAllMembers(String attributeId, LdapSearchResults searchResults) {
SearchResult result = searchResults.nextElement();
Attributes attributes = result.getAttributes();
if (attributes != null) {
Attribute memberAttribute = attributes.get(attributeId);
if (memberAttribute != null) {
try {
return (NamingEnumeration<String>) memberAttribute.getAll();
} catch (NamingException e) {
throw new IdentityProviderException("Value couldn't be retrieved.", e);
}
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapClient.java | 1 |
请完成以下Java代码 | public void setExecutionId(String executionId) {
}
@Override
public Object getValue() {
return variableValue;
}
@Override
public void setValue(Object value) {
variableValue = value;
}
@Override
public String getTypeName() {
return TYPE_TRANSIENT;
}
@Override
public void setTypeName(String typeName) {
}
@Override
public String getProcessInstanceId() {
return null;
}
@Override
public String getProcessDefinitionId() {
return null;
}
@Override
public String getTaskId() {
return null;
}
@Override
public void setTaskId(String taskId) {
}
@Override
public String getExecutionId() {
return null;
}
// non-supported (v6)
@Override
public String getScopeId() {
return null;
}
@Override
public String getSubScopeId() {
return null;
}
@Override
public String getScopeType() {
return null;
}
@Override | public void setScopeId(String scopeId) {
}
@Override
public void setSubScopeId(String subScopeId) {
}
@Override
public void setScopeType(String scopeType) {
}
@Override
public String getScopeDefinitionId() {
return null;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
}
@Override
public String getMetaInfo() {
return null;
}
@Override
public void setMetaInfo(String metaInfo) {
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TransientVariableInstance.java | 1 |
请完成以下Java代码 | public synchronized Object getBean() {
if (this.bean == null) {
this.bean = this.objectFactory.getObject();
}
return this.bean;
}
/**
* Gets the bean managed by this instance, if it exists.
*
* @return The existing bean or null.
*/
public Object getBeanIfExists() {
return this.bean;
}
/**
* Sets the given callback used to destroy the managed bean.
*
* @param destructionCallback The destruction callback to use.
*/
public void setDestructionCallback(final Runnable destructionCallback) {
this.destructionCallback = destructionCallback; | }
/**
* Executes the destruction callback if set and clears the internal bean references.
*/
public synchronized void destroy() {
Runnable callback = this.destructionCallback;
if (callback != null) {
callback.run();
}
this.bean = null;
this.destructionCallback = null;
}
@Override
public String toString() {
return "ScopedBeanReference [objectFactory=" + this.objectFactory + ", bean=" + this.bean + "]";
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\scope\GrpcRequestScope.java | 1 |
请完成以下Java代码 | public CloseableCollector temporaryCollectOnThisThread()
{
final CloseableCollector closeableCollector = new CloseableCollector();
closeableCollector.open();
return closeableCollector;
}
public class CloseableCollector implements IAutoCloseable
{
@NonNull private final JSONDocumentChangedWebSocketEventCollector collector = JSONDocumentChangedWebSocketEventCollector.newInstance();
@NonNull private final AtomicBoolean closed = new AtomicBoolean(false);
@Override
public String toString()
{
return "CloseableCollector[" + collector + "]";
}
private void open()
{
if (THREAD_LOCAL_COLLECTOR.get() != null)
{
throw new AdempiereException("A thread level collector was already set"); | }
THREAD_LOCAL_COLLECTOR.set(collector);
}
@Override
public void close()
{
if (closed.getAndSet(true))
{
return; // already closed
}
THREAD_LOCAL_COLLECTOR.set(null);
sendAllAndClose(collector, websocketSender);
}
@VisibleForTesting
ImmutableList<JSONDocumentChangedWebSocketEvent> getEvents() {return collector.getEvents();}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\DocumentWebsocketPublisher.java | 1 |
请完成以下Java代码 | public static String toCamelCaseByRegex(String text) {
StringBuilder builder = new StringBuilder();
String[] words = text.split("[\\W_]+");
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i == 0) {
word = word.isEmpty() ? word : word.toLowerCase();
} else {
word = word.isEmpty() ? word : Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase();
}
builder.append(word);
}
return builder.toString();
}
//Third-Party Libraries
public static String toCamelCaseUsingICU4J(String text, String delimiter) {
if (text == null || text.isEmpty()) {
return text;
}
text = UCharacter.toTitleCase(text, BreakIterator.getTitleInstance()).replaceAll(delimiter, "");
StringBuilder builder = new StringBuilder(text);
builder.setCharAt(0, Character.toLowerCase(text.charAt(0)));
return builder.toString(); | }
public static String toCamelCaseUsingGuava(String text, String delimiter) {
String toUpperUnderscore = text.toUpperCase().replaceAll(delimiter, "_");
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, toUpperUnderscore);
}
public static String toCamelCaseUsingApacheCommons(String text, char delimiter) {
text = WordUtils.capitalizeFully(text, delimiter).replaceAll(String.valueOf(delimiter), "");
StringBuilder builder = new StringBuilder(text);
builder.setCharAt(0, Character.toLowerCase(text.charAt(0)));
return builder.toString();
}
} | repos\tutorials-master\core-java-modules\core-java-string-conversions\src\main\java\com\baeldung\stringtocamelcase\StringToCamelCase.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String index(HttpServletRequest request, Model model, int jobId) {
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(jobId);
List<XxlJobLogGlue> jobLogGlues = xxlJobLogGlueDao.findByJobId(jobId);
if (jobInfo == null) {
throw new RuntimeException(I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
}
if (GlueTypeEnum.BEAN == GlueTypeEnum.match(jobInfo.getGlueType())) {
throw new RuntimeException(I18nUtil.getString("jobinfo_glue_gluetype_unvalid"));
}
// valid permission
JobInfoController.validPermission(request, jobInfo.getJobGroup());
// Glue类型-字典
model.addAttribute("GlueTypeEnum", GlueTypeEnum.values());
model.addAttribute("jobInfo", jobInfo);
model.addAttribute("jobLogGlues", jobLogGlues);
return "jobcode/jobcode.index";
}
@RequestMapping("/save")
@ResponseBody
public ReturnT<String> save(Model model, int id, String glueSource, String glueRemark) {
// valid
if (glueRemark==null) {
return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobinfo_glue_remark")) );
}
if (glueRemark.length()<4 || glueRemark.length()>100) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_remark_limit"));
}
XxlJobInfo exists_jobInfo = xxlJobInfoDao.loadById(id);
if (exists_jobInfo == null) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
} | // update new code
exists_jobInfo.setGlueSource(glueSource);
exists_jobInfo.setGlueRemark(glueRemark);
exists_jobInfo.setGlueUpdatetime(new Date());
exists_jobInfo.setUpdateTime(new Date());
xxlJobInfoDao.update(exists_jobInfo);
// log old code
XxlJobLogGlue xxlJobLogGlue = new XxlJobLogGlue();
xxlJobLogGlue.setJobId(exists_jobInfo.getId());
xxlJobLogGlue.setGlueType(exists_jobInfo.getGlueType());
xxlJobLogGlue.setGlueSource(glueSource);
xxlJobLogGlue.setGlueRemark(glueRemark);
xxlJobLogGlue.setAddTime(new Date());
xxlJobLogGlue.setUpdateTime(new Date());
xxlJobLogGlueDao.save(xxlJobLogGlue);
// remove code backup more than 30
xxlJobLogGlueDao.removeOld(exists_jobInfo.getId(), 30);
return ReturnT.SUCCESS;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobCodeController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private PlainHUPackingAware createAndInitHUPackingAware(
@NonNull final I_C_Order order,
@NonNull final ProductsProposalRow fromRow)
{
final PlainHUPackingAware huPackingAware = new PlainHUPackingAware();
huPackingAware.setBpartnerId(BPartnerId.ofRepoId(order.getC_BPartner_ID()));
huPackingAware.setInDispute(false);
final UomId uomId = productBL.getStockUOMId(fromRow.getProductId());
huPackingAware.setProductId(fromRow.getProductId());
huPackingAware.setUomId(uomId);
huPackingAware.setM_AttributeSetInstance_ID(AttributeSetInstanceId.toRepoId(fromRow.getAsiId()));
huPackingAware.setPiItemProductId(fromRow.getPackingMaterialId());
return huPackingAware; | }
private void validateNewHUPackingAware(@NonNull final PlainHUPackingAware huPackingAware)
{
if (huPackingAware.getQty() == null || huPackingAware.getQty().signum() <= 0)
{
logger.warn("Invalid Qty={} for {}", huPackingAware.getQty(), huPackingAware);
throw new AdempiereException("Qty shall be greather than zero"); // TODO trl
}
if (huPackingAware.getQtyTU() == null || huPackingAware.getQtyTU().signum() <= 0)
{
logger.warn("Invalid QtyTU={} for {}", huPackingAware.getQtyTU(), huPackingAware);
throw new AdempiereException("QtyTU shall be greather than zero"); // TODO trl
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\service\OrderLinesFromProductProposalsProducer.java | 2 |
请完成以下Java代码 | public int getRealizedLoss_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RealizedLoss_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getUnrealizedGain_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setUnrealizedGain_A(org.compiere.model.I_C_ValidCombination UnrealizedGain_A)
{
set_ValueFromPO(COLUMNNAME_UnrealizedGain_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedGain_A);
}
/** Set Nicht realisierte Währungsgewinne.
@param UnrealizedGain_Acct
Konto für nicht realisierte Währungsgewinne
*/
@Override
public void setUnrealizedGain_Acct (int UnrealizedGain_Acct)
{
set_Value (COLUMNNAME_UnrealizedGain_Acct, Integer.valueOf(UnrealizedGain_Acct));
}
/** Get Nicht realisierte Währungsgewinne.
@return Konto für nicht realisierte Währungsgewinne
*/
@Override
public int getUnrealizedGain_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedGain_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override | public org.compiere.model.I_C_ValidCombination getUnrealizedLoss_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setUnrealizedLoss_A(org.compiere.model.I_C_ValidCombination UnrealizedLoss_A)
{
set_ValueFromPO(COLUMNNAME_UnrealizedLoss_Acct, org.compiere.model.I_C_ValidCombination.class, UnrealizedLoss_A);
}
/** Set Nicht realisierte Währungsverluste.
@param UnrealizedLoss_Acct
Konto für nicht realisierte Währungsverluste
*/
@Override
public void setUnrealizedLoss_Acct (int UnrealizedLoss_Acct)
{
set_Value (COLUMNNAME_UnrealizedLoss_Acct, Integer.valueOf(UnrealizedLoss_Acct));
}
/** Get Nicht realisierte Währungsverluste.
@return Konto für nicht realisierte Währungsverluste
*/
@Override
public int getUnrealizedLoss_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnrealizedLoss_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Currency_Acct.java | 1 |
请完成以下Java代码 | public class ProcessDefinitionStatisticsDto {
protected String id;
protected String key;
protected String name;
protected int version;
protected String tenantId;
protected int suspensionState;
protected Integer instances;
protected Integer incidents;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public int getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
public Integer getInstances() {
return instances;
}
public void setInstances(Integer instances) {
this.instances = instances;
}
public Integer getIncidents() {
return incidents;
}
public void setIncidents(Integer incidents) {
this.incidents = incidents;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\ProcessDefinitionStatisticsDto.java | 1 |
请完成以下Java代码 | private Login authenticateRequest()
{
// Login
final GetAuth getAuthValue = loginServiceOF.createGetAuth();
getAuthValue.setDelisId(config.getDelisID());
getAuthValue.setPassword(config.getDelisPassword());
getAuthValue.setMessageLanguage(DpdConstants.DEFAULT_MESSAGE_LANGUAGE);
final ILoggable epicLogger = getEpicLogger();
epicLogger.addLog("Creating login request");
final JAXBElement<GetAuth> getAuthElement = loginServiceOF.createGetAuth(getAuthValue);
@SuppressWarnings("unchecked") final JAXBElement<GetAuthResponse> authenticationElement = (JAXBElement<GetAuthResponse>)doActualRequest(config.getLoginApiUrl(), getAuthElement, null, null);
final Login login = authenticationElement.getValue().getReturn();
epicLogger.addLog("Finished login Request");
return login;
}
/**
* no idea what this does, but tobias sais it's useful to have this special log, so here it is! | */
@NonNull
private ILoggable getEpicLogger()
{
return Loggables.withLogger(logger, Level.TRACE);
}
@Override
public @NonNull JsonDeliveryAdvisorResponse adviseShipment(final @NonNull JsonDeliveryAdvisorRequest request)
{
return JsonDeliveryAdvisorResponse.builder()
.requestId(request.getId())
.shipperProduct(JsonShipperProduct.builder()
.code(DpdShipperProduct.DPD_CLASSIC.getCode())
.build())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java\de\metas\shipper\gateway\dpd\DpdShipperGatewayClient.java | 1 |
请完成以下Java代码 | public boolean isContainedProperty() {
return relation == null && queryProperty.getFunction() == null;
}
@Override
public String toString() {
return "QueryOrderingProperty["
+ "relation=" + relation
+ ", queryProperty=" + queryProperty
+ ", direction=" + direction
+ ", relationConditions=" + getRelationConditionsString()
+ "]";
} | public String getRelationConditionsString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
if(relationConditions != null) {
for (int i = 0; i < relationConditions.size(); i++) {
if (i > 0) {
builder.append(",");
}
builder.append(relationConditions.get(i));
}
}
builder.append("]");
return builder.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryOrderingProperty.java | 1 |
请完成以下Java代码 | class AttributeSetAggregator
{
private final HashMap<AttributeCode, AttributeAggregator> attributeAggregators = new HashMap<>();
void collect(@NonNull final IAttributeSet from)
{
from.getAttributes()
.stream()
.filter(AttributeSetAggregator::isAggregable)
.forEach(attribute -> getAttributeAggregator(attribute).collect(from));
}
@NonNull
private AttributeAggregator getAttributeAggregator(@NonNull final I_M_Attribute attribute)
{
return attributeAggregators.computeIfAbsent(
AttributeCode.ofString(attribute.getValue()),
attributeCode -> new AttributeAggregator(attributeCode, AttributeValueType.ofCode(attribute.getAttributeValueType()))
);
}
void updateAggregatedValuesTo(@NonNull final IAttributeSet to)
{
attributeAggregators.values()
.forEach(attributeAggregator -> attributeAggregator.updateAggregatedValueTo(to));
}
private static boolean isAggregable(@NonNull final I_M_Attribute attribute)
{
return !Weightables.isWeightableAttribute(AttributeCode.ofString(attribute.getValue()));
}
//
//
//
@RequiredArgsConstructor
private static class AttributeAggregator
{
private final AttributeCode attributeCode;
private final AttributeValueType attributeValueType;
private final HashSet<Object> values = new HashSet<>();
void collect(@NonNull final IAttributeSet from)
{
final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>()
{
@Nullable
@Override
public Object string()
{
return from.getValueAsString(attributeCode);
}
@Override | public Object number()
{
return from.getValueAsBigDecimal(attributeCode);
}
@Nullable
@Override
public Object date()
{
return from.getValueAsDate(attributeCode);
}
@Nullable
@Override
public Object list()
{
return from.getValueAsString(attributeCode);
}
});
values.add(value);
}
void updateAggregatedValueTo(@NonNull final IAttributeSet to)
{
if (values.size() == 1 && to.hasAttribute(attributeCode))
{
to.setValue(attributeCode, values.iterator().next());
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java | 1 |
请完成以下Java代码 | public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx)
{
setContext(ctx, ITrx.TRXNAME_None);
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setContext(final Properties ctx, final String trxName)
{
this._processorCtx = null;
this._ctx = ctx;
this._trxName = trxName;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setContext(final ITrxItemProcessorContext processorCtx)
{
this._processorCtx = processorCtx;
this._ctx = null;
this._trxName = null;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setProcessor(final ITrxItemProcessor<IT, RT> processor)
{
this._processor = processor;
return this;
}
private final ITrxItemProcessor<IT, RT> getProcessor()
{
Check.assumeNotNull(_processor, "processor is set");
return _processor;
}
@Override
public TrxItemExecutorBuilder<IT, RT> setExceptionHandler(@NonNull final ITrxItemExceptionHandler exceptionHandler)
{
this._exceptionHandler = exceptionHandler;
return this;
} | private final ITrxItemExceptionHandler getExceptionHandler()
{
return _exceptionHandler;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setOnItemErrorPolicy(@NonNull final OnItemErrorPolicy onItemErrorPolicy)
{
this._onItemErrorPolicy = onItemErrorPolicy;
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setItemsPerBatch(final int itemsPerBatch)
{
if (itemsPerBatch == Integer.MAX_VALUE)
{
this.itemsPerBatch = null;
}
else
{
this.itemsPerBatch = itemsPerBatch;
}
return this;
}
@Override
public ITrxItemExecutorBuilder<IT, RT> setUseTrxSavepoints(final boolean useTrxSavepoints)
{
this._useTrxSavepoints = useTrxSavepoints;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\processor\api\impl\TrxItemExecutorBuilder.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGrowth() {
return growth;
}
public void setGrowth(Integer growth) {
this.growth = growth;
}
public Integer getIntergration() {
return intergration;
}
public void setIntergration(Integer intergration) {
this.intergration = intergration;
}
public Integer getType() {
return type; | }
public void setType(Integer type) {
this.type = type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", growth=").append(growth);
sb.append(", intergration=").append(intergration);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NoOpConnectionProvider implements MultiTenantConnectionProvider<Object>, HibernatePropertiesCustomizer {
@Autowired DataSource dataSource;
@Override
public Connection getAnyConnection() throws SQLException {
return dataSource.getConnection();
}
@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
connection.close();
}
@Override
public boolean supportsAggressiveRelease() {
return false;
}
@Override
public boolean isUnwrappableAs(Class<?> aClass) {
return false;
}
@Override
public <T> T unwrap(Class<T> aClass) {
throw new UnsupportedOperationException("Can't unwrap this.");
}
@Override
public void customize(Map<String, Object> hibernateProperties) { | hibernateProperties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, this);
}
@Override
public Connection getConnection(Object tenantIdentifier) throws SQLException {
return dataSource.getConnection();
}
/*
* (non-Javadoc)
* @see org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider#releaseConnection(java.lang.Object, java.sql.Connection)
*/
@Override
public void releaseConnection(Object tenantIdentifier, Connection connection) throws SQLException {
connection.close();
}
} | repos\spring-data-examples-main\jpa\multitenant\db\src\main\java\example\springdata\jpa\hibernatemultitenant\db\NoOpConnectionProvider.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.getSelectedIncludedRecords().size() != 1)
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final OrderLineId orderLineId = OrderLineId.ofRepoId(Check.singleElement(getSelectedIncludedRecordIds(I_C_OrderLine.class)));
final I_C_Order salesOrder = orderDAO.getById(OrderId.ofRepoId(getRecord_ID()));
final OrderLineDescriptor orderLineDescriptor = OrderLineDescriptor.builder()
.orderId(salesOrder.getC_Order_ID())
.orderLineId(orderLineId.getRepoId())
.orderBPartnerId(salesOrder.getC_BPartner_ID())
.docTypeId(salesOrder.getC_DocType_ID())
.build();
try
{
productionSimulationService.processSimulatedDemand(orderLineId, salesOrder, orderLineDescriptor); | final ViewId viewId = viewsFactory.createView(CreateViewRequest.builder(ProductionSimulationViewFactory.WINDOWID)
.setParameter(VIEW_FACTORY_PARAM_DOCUMENT_LINE_DESCRIPTOR, orderLineDescriptor)
.build())
.getViewId();
getResult().setWebuiViewToOpen(ProcessExecutionResult.WebuiViewToOpen.builder()
.viewId(viewId.getViewId())
.target(ProcessExecutionResult.ViewOpenTarget.ModalOverlay)
.build());
}
catch (final Exception exception)
{
log.error("Error encountered while launching ProductionSimulationModal:", exception);
postMaterialEventService.enqueueEventNow(DeactivateAllSimulatedCandidatesEvent.builder()
.eventDescriptor(EventDescriptor.ofClientAndOrg(Env.getClientAndOrgId()))
.build());
throw AdempiereException.wrapIfNeeded(exception);
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\simulation\process\C_Order_ProductionSimulationView_Launcher.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JerseyProperties {
/**
* Jersey integration type.
*/
private Type type = Type.SERVLET;
/**
* Init parameters to pass to Jersey through the servlet or filter.
*/
private Map<String, String> init = new HashMap<>();
private final Filter filter = new Filter();
private final Servlet servlet = new Servlet();
/**
* Path that serves as the base URI for the application. If specified, overrides the
* value of "@ApplicationPath".
*/
private @Nullable String applicationPath;
public Filter getFilter() {
return this.filter;
}
public Servlet getServlet() {
return this.servlet;
}
public Type getType() {
return this.type;
}
public void setType(Type type) {
this.type = type;
}
public Map<String, String> getInit() {
return this.init;
}
public void setInit(Map<String, String> init) {
this.init = init;
}
public @Nullable String getApplicationPath() {
return this.applicationPath;
}
public void setApplicationPath(@Nullable String applicationPath) {
this.applicationPath = applicationPath;
}
public enum Type {
SERVLET, FILTER
}
public static class Filter { | /**
* Jersey filter chain order.
*/
private int order;
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
public static class Servlet {
/**
* Load on startup priority of the Jersey servlet.
*/
private int loadOnStartup = -1;
public int getLoadOnStartup() {
return this.loadOnStartup;
}
public void setLoadOnStartup(int loadOnStartup) {
this.loadOnStartup = loadOnStartup;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\JerseyProperties.java | 2 |
请完成以下Java代码 | public class AppDefinitionEntityImpl extends AbstractAppEngineEntity implements AppDefinitionEntity {
protected String category;
protected String name;
protected String key;
protected String description;
protected int version;
protected String resourceName;
protected String deploymentId;
protected String tenantId = AppEngineConfiguration.NO_TENANT_ID;
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("category", this.category);
return persistentState;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public String getKey() {
return key;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getVersion() {
return version;
}
@Override
public String getResourceName() {
return resourceName;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public String getTenantId() {
return tenantId; | }
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public void setM_AttributeValue_ID (int M_AttributeValue_ID)
{
if (M_AttributeValue_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID));
}
/** Get Merkmals-Wert.
@return Product Attribute Value
*/
@Override
public int getM_AttributeValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/ | @Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_ValueNoCheck (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue.java | 1 |
请完成以下Java代码 | public C_AggregationItem_Builder setC_Aggregation(final I_C_Aggregation aggregation)
{
this.aggregation = aggregation;
return this;
}
private I_C_Aggregation getC_Aggregation()
{
Check.assumeNotNull(aggregation, "aggregation not null");
return aggregation;
}
public C_AggregationItem_Builder setType(final String type)
{
this.type = type;
return this;
}
private String getType()
{
Check.assumeNotEmpty(type, "type not empty");
return type;
}
public C_AggregationItem_Builder setAD_Column(@Nullable final String columnName)
{
if (isBlank(columnName))
{
this.adColumnId = null;
}
else
{
this.adColumnId = Services.get(IADTableDAO.class).retrieveColumnId(adTableId, columnName);
}
return this;
}
private AdColumnId getAD_Column_ID()
{
return adColumnId; | }
public C_AggregationItem_Builder setIncluded_Aggregation(final I_C_Aggregation includedAggregation)
{
this.includedAggregation = includedAggregation;
return this;
}
private I_C_Aggregation getIncluded_Aggregation()
{
return includedAggregation;
}
public C_AggregationItem_Builder setIncludeLogic(final String includeLogic)
{
this.includeLogic = includeLogic;
return this;
}
private String getIncludeLogic()
{
return includeLogic;
}
public C_AggregationItem_Builder setC_Aggregation_Attribute(I_C_Aggregation_Attribute attribute)
{
this.attribute = attribute;
return this;
}
private I_C_Aggregation_Attribute getC_Aggregation_Attribute()
{
return this.attribute;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\model\C_AggregationItem_Builder.java | 1 |
请完成以下Java代码 | final class FavoritesGroup
{
private final FavoritesGroupContainer container;
private final int topNodeId;
private final IdentityHashMap<MTreeNode, FavoriteItem> node2item = new IdentityHashMap<>();
private final IdentityHashMap<JComponent, FavoriteItem> component2item = new IdentityHashMap<>();
private final JXTaskPane panel = new JXTaskPane();
private final JToolBar toolbar;
private final MouseAdapter itemMouseListener = new MouseAdapter()
{
@Override
public void mouseClicked(final MouseEvent e)
{
if (SwingUtilities.isRightMouseButton(e))
{
final FavoriteItem item = component2item.get(e.getSource());
container.showPopup(item, e);
}
};
};
private ActionListener itemActionListener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
final FavoriteItem item = component2item.get(e.getSource());
if(item == null)
{
return;
}
container.fireItemClicked(item);
}
};
public FavoritesGroup(final FavoritesGroupContainer container, final MTreeNode ndTop)
{
super();
Check.assumeNotNull(container, "container not null");
this.container = container;
Check.assumeNotNull(ndTop, "ndTop not null");
topNodeId = ndTop.getNode_ID();
// barPart.setAnimated(true); // use Theme setting
panel.setLayout(new BorderLayout());
panel.setTitle(ndTop.getName().trim());
toolbar = new JToolBar(SwingConstants.VERTICAL);
toolbar.setOpaque(false);
toolbar.setFloatable(false);
toolbar.setRollover(true);
toolbar.setBorder(BorderFactory.createEmptyBorder()); | panel.add(toolbar, BorderLayout.NORTH);
}
public JXTaskPane getComponent()
{
return panel;
}
public int getTopNodeId()
{
return topNodeId;
}
public void removeAllItems()
{
toolbar.removeAll();
}
public void addFavorite(final MTreeNode node)
{
if (node2item.get(node) != null)
{
// already added
return;
}
final FavoriteItem item = new FavoriteItem(this, node);
item.addMouseListener(itemMouseListener);
item.addActionListener(itemActionListener);
final JComponent itemComp = item.getComponent();
node2item.put(node, item);
component2item.put(itemComp, item);
node.setOnBar(true);
toolbar.add(itemComp);
}
public boolean isEmpty()
{
return node2item.isEmpty();
}
public void removeItem(final FavoriteItem item)
{
Check.assumeNotNull(item, "item not null");
final MTreeNode node = item.getNode();
final JComponent itemComp = item.getComponent();
node2item.remove(node);
component2item.remove(itemComp);
node.setOnBar(false);
toolbar.remove(itemComp);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\FavoritesGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RpPayWay getByPayWayTypeCode(String payProductCode, String payWayCode, String payTypeCode){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("payProductCode", payProductCode);
paramMap.put("payTypeCode", payTypeCode);
paramMap.put("payWayCode", payWayCode);
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpPayWayDao.getBy(paramMap);
}
/**
* 绑定支付费率
* @param payWayCode
* @param payTypeCode
* @param payRate
*/
@Override
public void createPayWay(String payProductCode, String payWayCode, String payTypeCode, Double payRate) throws PayBizException {
RpPayWay payWay = getByPayWayTypeCode(payProductCode,payWayCode,payTypeCode);
if(payWay!=null){
throw new PayBizException(PayBizException.PAY_TYPE_IS_EXIST,"支付渠道已存在");
}
RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(payProductCode, null);
if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){
throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法绑定!");
}
RpPayWay rpPayWay = new RpPayWay();
rpPayWay.setPayProductCode(payProductCode);
rpPayWay.setPayRate(payRate);
rpPayWay.setPayWayCode(payWayCode);
rpPayWay.setPayWayName(PayWayEnum.getEnum(payWayCode).getDesc());
rpPayWay.setPayTypeCode(payTypeCode);
rpPayWay.setPayTypeName(PayTypeEnum.getEnum(payTypeCode).getDesc());
rpPayWay.setStatus(PublicStatusEnum.ACTIVE.name());
rpPayWay.setCreateTime(new Date());
rpPayWay.setId(StringUtil.get32UUID()); | saveData(rpPayWay);
}
/**
* 根据支付产品获取支付方式
*/
@Override
public List<RpPayWay> listByProductCode(String payProductCode){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("payProductCode", payProductCode);
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpPayWayDao.listBy(paramMap);
}
/**
* 获取所有支付方式
*/
@Override
public List<RpPayWay> listAll(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpPayWayDao.listBy(paramMap);
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\service\impl\RpPayWayServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().permitAll())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults()
.matcher(POST, this.adminContextPath + "/instances"),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminContextPath + "/instances/*"),
PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**")));
return http.build();
}
}
@Profile("secure")
@Configuration(proxyBeanMethods = false)
public static class SecuritySecureConfig {
private final String adminContextPath;
public SecuritySecureConfig(AdminServerProperties adminServerProperties) {
this.adminContextPath = adminServerProperties.getContextPath();
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminContextPath + "/");
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests | .requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/assets/**"))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/login"))
.permitAll()
.anyRequest()
.authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login")
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout"))
.httpBasic(Customizer.withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults()
.matcher(POST, this.adminContextPath + "/instances"),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminContextPath + "/instances/*"),
PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**")));
return http.build();
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-consul\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminConsulApplication.java | 2 |
请完成以下Java代码 | private static int colorToRGB(int alpha, int red, int green, int blue) {
int pixel = 0;
pixel += alpha;
pixel = pixel << 8;
pixel += red;
pixel = pixel << 8;
pixel += green;
pixel = pixel << 8;
pixel += blue;
return pixel;
}
/**
* 反色处理
* @param base 处理文件的目录
* @param src 用于处理的源文件
* @return 反色处理后的新文件
* @throws IOException
*/
public static String colorRevert(String base, String src) throws IOException {
int color, r, g, b, pixel;
// 读原始文件
BufferedImage srcImage = ImageIO.read(new File(base + src));
// 修改后的文件
BufferedImage destImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), srcImage.getType());
for (int i=0; i<srcImage.getWidth(); i++) {
for (int j=0; j<srcImage.getHeight(); j++) {
color = srcImage.getRGB(i, j);
r = (color >> 16) & 0xff;
g = (color >> 8) & 0xff;
b = color & 0xff;
pixel = colorToRGB(255, 0xff - r, 0xff - g, 0xff - b);
destImage.setRGB(i, j, pixel);
}
}
// 反射文件的名字
String revertFileName = src.substring(0, src.lastIndexOf(".")) + "-revert.png";
// 转换后的图片写文件
ImageIO.write(destImage, "png", new File(base + revertFileName)); | return revertFileName;
}
/**
* 取黑白图片的特征
* @param base
* @param fileName
* @return
* @throws Exception
*/
public static INDArray getGrayImageFeatures(String base, String fileName) throws Exception {
log.info("start getImageFeatures [{}]", base + fileName);
// 和训练模型时一样的设置
ImageRecordReader imageRecordReader = new ImageRecordReader(RESIZE_HEIGHT, RESIZE_WIDTH, 1);
FileSplit fileSplit = new FileSplit(new File(base + fileName),
NativeImageLoader.ALLOWED_FORMATS);
imageRecordReader.initialize(fileSplit);
DataSetIterator dataSetIterator = new RecordReaderDataSetIterator(imageRecordReader, 1);
dataSetIterator.setPreProcessor(new ImagePreProcessingScaler(0, 1));
// 取特征
return dataSetIterator.next().getFeatures();
}
/**
* 批量清理文件
* @param base 处理文件的目录
* @param fileNames 待清理文件集合
*/
public static void clear(String base, String...fileNames) {
for (String fileName : fileNames) {
if (null==fileName) {
continue;
}
File file = new File(base + fileName);
if (file.exists()) {
file.delete();
}
}
}
} | repos\springboot-demo-master\Deeplearning4j\src\main\java\com\et\dl4j\util\ImageFileUtil.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_PaySchedule getC_PaySchedule()
{
return get_ValueAsPO(COLUMNNAME_C_PaySchedule_ID, org.compiere.model.I_C_PaySchedule.class);
}
@Override
public void setC_PaySchedule(final org.compiere.model.I_C_PaySchedule C_PaySchedule)
{
set_ValueFromPO(COLUMNNAME_C_PaySchedule_ID, org.compiere.model.I_C_PaySchedule.class, C_PaySchedule);
}
@Override
public void setC_PaySchedule_ID (final int C_PaySchedule_ID)
{
if (C_PaySchedule_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PaySchedule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PaySchedule_ID, C_PaySchedule_ID);
}
@Override
public int getC_PaySchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PaySchedule_ID);
}
@Override
public void setDiscountAmt (final @Nullable BigDecimal DiscountAmt)
{
set_Value (COLUMNNAME_DiscountAmt, DiscountAmt);
}
@Override
public BigDecimal getDiscountAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DiscountAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDiscountDate (final @Nullable java.sql.Timestamp DiscountDate)
{
set_Value (COLUMNNAME_DiscountDate, DiscountDate);
}
@Override
public java.sql.Timestamp getDiscountDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DiscountDate);
}
@Override
public void setDueAmt (final BigDecimal DueAmt)
{
set_Value (COLUMNNAME_DueAmt, DueAmt);
}
@Override
public BigDecimal getDueAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DueAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setDueDate (final java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
} | @Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InvoicePaySchedule.java | 1 |
请完成以下Java代码 | public UserQuery userFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserQuery userFirstNameLike(String firstNameLike) {
ensureNotNull("Provided firstNameLike", firstNameLike);
this.firstNameLike = firstNameLike;
return this;
}
public UserQuery userLastName(String lastName) {
this.lastName = lastName;
return this;
}
public UserQuery userLastNameLike(String lastNameLike) {
ensureNotNull("Provided lastNameLike", lastNameLike);
this.lastNameLike = lastNameLike;
return this;
}
public UserQuery userEmail(String email) {
this.email = email;
return this;
}
public UserQuery userEmailLike(String emailLike) {
ensureNotNull("Provided emailLike", emailLike);
this.emailLike = emailLike;
return this;
}
public UserQuery memberOfGroup(String groupId) {
ensureNotNull("Provided groupId", groupId);
this.groupId = groupId;
return this;
}
public UserQuery potentialStarter(String procDefId) {
ensureNotNull("Provided processDefinitionId", procDefId);
this.procDefId = procDefId;
return this;
}
public UserQuery memberOfTenant(String tenantId) {
ensureNotNull("Provided tenantId", tenantId);
this.tenantId = tenantId;
return this;
}
//sorting //////////////////////////////////////////////////////////
public UserQuery orderByUserId() {
return orderBy(UserQueryProperty.USER_ID);
}
public UserQuery orderByUserEmail() {
return orderBy(UserQueryProperty.EMAIL);
}
public UserQuery orderByUserFirstName() {
return orderBy(UserQueryProperty.FIRST_NAME);
}
public UserQuery orderByUserLastName() {
return orderBy(UserQueryProperty.LAST_NAME);
} | //getters //////////////////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId;
}
public String getTenantId() {
return tenantId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSerialShippingContainerCode(String value) {
this.serialShippingContainerCode = value;
}
/**
* The mode of despatch in free-text. E.g., "standard international shipping", "express international shipping", etc.
*
* @return
* possible object is
* {@link String }
*
*/
public String getModeOfDispatch() {
return modeOfDispatch;
}
/**
* Sets the value of the modeOfDispatch property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setModeOfDispatch(String value) {
this.modeOfDispatch = value;
}
/**
* The number of packages in the given delivery.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumberOfPackages() {
return numberOfPackages;
}
/**
* Sets the value of the numberOfPackages property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumberOfPackages(BigInteger value) {
this.numberOfPackages = value;
}
/**
* The name of the driver performing the delivery.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNameOfDriver() {
return nameOfDriver;
}
/**
* Sets the value of the nameOfDriver property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNameOfDriver(String value) {
this.nameOfDriver = value;
} | /**
* The license plate number of the vehicle performing the delivery.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTransportVehicleLicenseNumber() {
return transportVehicleLicenseNumber;
}
/**
* Sets the value of the transportVehicleLicenseNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTransportVehicleLicenseNumber(String value) {
this.transportVehicleLicenseNumber = value;
}
/**
* Gets the value of the deliveryDetailsExtension property.
*
* @return
* possible object is
* {@link DeliveryDetailsExtensionType }
*
*/
public DeliveryDetailsExtensionType getDeliveryDetailsExtension() {
return deliveryDetailsExtension;
}
/**
* Sets the value of the deliveryDetailsExtension property.
*
* @param value
* allowed object is
* {@link DeliveryDetailsExtensionType }
*
*/
public void setDeliveryDetailsExtension(DeliveryDetailsExtensionType value) {
this.deliveryDetailsExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DeliveryDetailsType.java | 2 |
请完成以下Java代码 | public BatchDto deleteAsync(DeleteHistoricDecisionInstancesDto dto) {
HistoricDecisionInstanceQuery decisionInstanceQuery = null;
if (dto.getHistoricDecisionInstanceQuery() != null) {
decisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine);
}
try {
List<String> historicDecisionInstanceIds = dto.getHistoricDecisionInstanceIds();
String deleteReason = dto.getDeleteReason();
Batch batch = processEngine.getHistoryService().deleteHistoricDecisionInstancesAsync(historicDecisionInstanceIds, decisionInstanceQuery, deleteReason);
return BatchDto.fromBatch(batch);
}
catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
@Override
public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricDecisionInstancesDto dto) {
HistoryService historyService = processEngine.getHistoryService();
HistoricDecisionInstanceQuery historicDecisionInstanceQuery = null;
if (dto.getHistoricDecisionInstanceQuery() != null) {
historicDecisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine);
}
SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder =
historyService.setRemovalTimeToHistoricDecisionInstances();
if (dto.isCalculatedRemovalTime()) {
builder.calculatedRemovalTime();
} | Date removalTime = dto.getAbsoluteRemovalTime();
if (dto.getAbsoluteRemovalTime() != null) {
builder.absoluteRemovalTime(removalTime);
}
if (dto.isClearedRemovalTime()) {
builder.clearedRemovalTime();
}
builder.byIds(dto.getHistoricDecisionInstanceIds());
builder.byQuery(historicDecisionInstanceQuery);
if (dto.isHierarchical()) {
builder.hierarchical();
}
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricDecisionInstanceRestServiceImpl.java | 1 |
请完成以下Java代码 | public class DmnExpressionImpl implements CachedCompiledScriptSupport, CachedExpressionSupport {
protected String id;
protected String name;
protected DmnTypeDefinition typeDefinition;
protected String expressionLanguage;
protected String expression;
protected CompiledScript cachedCompiledScript;
protected ElExpression cachedExpression;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DmnTypeDefinition getTypeDefinition() {
return typeDefinition;
}
public void setTypeDefinition(DmnTypeDefinition typeDefinition) {
this.typeDefinition = typeDefinition;
}
public String getExpressionLanguage() {
return expressionLanguage;
} | public void setExpressionLanguage(String expressionLanguage) {
this.expressionLanguage = expressionLanguage;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
@Override
public String toString() {
return "DmnExpressionImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", typeDefinition=" + typeDefinition +
", expressionLanguage='" + expressionLanguage + '\'' +
", expression='" + expression + '\'' +
'}';
}
public void cacheCompiledScript(CompiledScript compiledScript) {
this.cachedCompiledScript = compiledScript;
}
public CompiledScript getCachedCompiledScript() {
return this.cachedCompiledScript;
}
public ElExpression getCachedExpression() {
return this.cachedExpression;
}
public void setCachedExpression(ElExpression expression) {
this.cachedExpression = expression;
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnExpressionImpl.java | 1 |
请完成以下Java代码 | private Mono<Void> filterWithCache(ServerWebExchange exchange, GatewayFilterChain chain) {
final String metadataKey = responseCacheManager.resolveMetadataKey(exchange);
Optional<CachedResponse> cached = getCachedResponse(exchange, metadataKey);
if (cached.isPresent()) {
return responseCacheManager.processFromCache(exchange, metadataKey, cached.get());
}
else {
return chain
.filter(exchange.mutate().response(new CachingResponseDecorator(metadataKey, exchange)).build());
}
}
private Optional<CachedResponse> getCachedResponse(ServerWebExchange exchange, String metadataKey) {
Optional<CachedResponse> cached;
if (shouldRevalidate(exchange)) {
cached = Optional.empty();
}
else {
cached = responseCacheManager.getFromCache(exchange.getRequest(), metadataKey);
}
return cached;
}
private boolean shouldRevalidate(ServerWebExchange exchange) {
return LocalResponseCacheUtils.isNoCacheRequest(exchange.getRequest());
}
private class CachingResponseDecorator extends ServerHttpResponseDecorator {
private final String metadataKey;
private final ServerWebExchange exchange;
CachingResponseDecorator(String metadataKey, ServerWebExchange exchange) {
super(exchange.getResponse());
this.metadataKey = metadataKey;
this.exchange = exchange;
} | @Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
final ServerHttpResponse response = exchange.getResponse();
Flux<DataBuffer> decoratedBody;
if (responseCacheManager.isResponseCacheable(response)
&& !responseCacheManager.isNoCacheRequestWithoutUpdate(exchange.getRequest())) {
decoratedBody = responseCacheManager.processFromUpstream(metadataKey, exchange, Flux.from(body));
}
else {
decoratedBody = Flux.from(body);
}
return super.writeWith(decoratedBody);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\ResponseCacheGatewayFilter.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_OrderLine getC_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class);
}
@Override
public void setC_OrderLine(final org.compiere.model.I_C_OrderLine C_OrderLine)
{
set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine);
}
@Override
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_Product_ID (final int M_Product_ID) | {
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPrice (final BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
@Override
public BigDecimal getPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderLine_Detail.java | 1 |
请完成以下Java代码 | public int updateStatusByDeliveryMethodAndRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, NotificationStatus status) {
return notificationRepository.updateStatusByDeliveryMethodAndRecipientIdAndStatusNot(deliveryMethod, recipientId.getId(), status);
}
@Override
public void deleteByRequestId(TenantId tenantId, NotificationRequestId requestId) {
notificationRepository.deleteByRequestId(requestId.getId());
}
@Override
public void deleteByRecipientId(TenantId tenantId, UserId recipientId) {
notificationRepository.deleteByRecipientId(recipientId.getId());
}
@Override
public void createPartition(NotificationEntity entity) {
partitioningRepository.createPartitionIfNotExists(ModelConstants.NOTIFICATION_TABLE_NAME,
entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
} | @Override
protected Class<NotificationEntity> getEntityClass() {
return NotificationEntity.class;
}
@Override
protected JpaRepository<NotificationEntity, UUID> getRepository() {
return notificationRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationDao.java | 1 |
请完成以下Java代码 | public class MaterialTrackingICHeaderAggregationKeyBuilder_OLD extends AbstractAggregationKeyBuilder<I_C_Invoice_Candidate>
{
private static final List<String> columnNames = Arrays.asList(
de.metas.materialtracking.model.I_C_Invoice_Candidate.COLUMNNAME_M_Material_Tracking_ID
);
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public String getTableName()
{
return I_C_Invoice_Candidate.Table_Name;
}
@Override
public List<String> getDependsOnColumnNames()
{
return columnNames;
} | @Override
public AggregationKey buildAggregationKey(I_C_Invoice_Candidate model)
{
final List<Object> keyValues = extractKeyValues(model);
final ArrayKey key = Util.mkKey(keyValues.toArray());
final AggregationId aggregationId = null;
return new AggregationKey(key, aggregationId);
}
private final List<Object> extractKeyValues(final I_C_Invoice_Candidate ic)
{
final List<Object> values = new ArrayList<>();
final de.metas.materialtracking.model.I_C_Invoice_Candidate icExt = InterfaceWrapperHelper.create(ic, de.metas.materialtracking.model.I_C_Invoice_Candidate.class);
//
// Bind the Material Tracking ID for the reference of the Invoice Candidate
values.add(icExt.getM_Material_Tracking_ID());
return values;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\agg\key\impl\MaterialTrackingICHeaderAggregationKeyBuilder_OLD.java | 1 |
请完成以下Java代码 | public int getVersion() {
return version;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public String getResourceName() {
return resourceName;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public boolean hasGraphicalNotation() {
return isGraphicalNotationDefined;
}
public boolean isGraphicalNotationDefined() {
return hasGraphicalNotation();
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public String getDiagramResourceName() {
return diagramResourceName;
}
@Override | public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String getDecisionType() {
return decisionType;
}
@Override
public void setDecisionType(String decisionType) {
this.decisionType = decisionType;
}
@Override
public String toString() {
return "DecisionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DecisionEntityImpl.java | 1 |
请完成以下Java代码 | private void deleteLinesByExportId(@NonNull final DATEVExportId datevExportId)
{
queryBL.createQueryBuilder(I_DATEV_ExportLine.class)
.addEqualsFilter(I_DATEV_ExportLine.COLUMN_DATEV_Export_ID, datevExportId)
.create()
.deleteDirectly();
}
private static I_DATEV_Export getById(final DATEVExportId datevExportId)
{
return load(datevExportId, I_DATEV_Export.class);
}
private IQuery<I_RV_DATEV_Export_Fact_Acct_Invoice> createSourceQuery(final DATEVExportCreateLinesRequest request)
{
final I_DATEV_Export datevExport = getById(request.getDatevExportId());
final IQueryBuilder<I_RV_DATEV_Export_Fact_Acct_Invoice> queryBuilder = queryBL.createQueryBuilder(I_RV_DATEV_Export_Fact_Acct_Invoice.class)
.orderBy(I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMNNAME_DateAcct)
.orderBy(I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMNNAME_C_Invoice_ID)
.orderBy(I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMNNAME_RV_DATEV_Export_Fact_Acct_Invoice_ID)
.addEqualsFilter(I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMNNAME_AD_Org_ID, datevExport.getAD_Org_ID());
if (datevExport.getDateAcctFrom() != null)
{ | queryBuilder.addCompareFilter(I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMN_DateAcct, Operator.GREATER_OR_EQUAL, datevExport.getDateAcctFrom());
}
if (datevExport.getDateAcctTo() != null)
{
queryBuilder.addCompareFilter(I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMN_DateAcct, Operator.LESS_OR_EQUAL, datevExport.getDateAcctTo());
}
if (datevExport.isExcludeAlreadyExported())
{
final IQuery<I_DATEV_ExportLine> exportLinesQuery = queryBL.createQueryBuilder(I_DATEV_ExportLine.class)
.create();
queryBuilder.addNotInSubQueryFilter(
I_RV_DATEV_Export_Fact_Acct_Invoice.COLUMN_C_Invoice_ID,
I_DATEV_ExportLine.COLUMN_C_Invoice_ID,
exportLinesQuery);
}
return queryBuilder.create()
.setSqlFromParameter("p_IsOneLinePerInvoiceTax", request.isOneLinePerInvoiceTax())
.setSqlFromParameter("p_IsSwitchCreditMemo", datevExport.isSwitchCreditMemo())
.setSqlFromParameter("p_IsNegateInboundAmounts", datevExport.isNegateInboundAmounts())
.setSqlFromParameter("p_IsPlaceBPAccountsOnCredit", datevExport.isPlaceBPAccountsOnCredit())
.setSqlFromParameter("p_IsSOTrx", datevExport.getIsSOTrx())
;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java\de\metas\datev\DATEVExportLinesRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Account {
@Id
private long id;
private String type;
@ManyToOne
@JoinColumn(referencedColumnName = "email")
private User user;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
} | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-2\src\main\java\com\baeldung\hibernate\serializable\Account.java | 2 |
请完成以下Java代码 | public CountIfQueryAggregateColumnBuilder<SourceModelType, TargetModelType> setDynAttribute(final ModelDynAttributeAccessor<TargetModelType, Integer> dynAttribute)
{
this.dynAttribute = dynAttribute;
return this;
}
@Override
public ModelDynAttributeAccessor<TargetModelType, Integer> getDynAttribute()
{
return dynAttribute;
}
@Override
public IAggregator<Integer, SourceModelType> createAggregator(final TargetModelType targetModel)
{
Check.assumeNotNull(targetModel, "targetModel not null");
return new IAggregator<Integer, SourceModelType>()
{
private final ICompositeQueryFilter<SourceModelType> filters = CountIfQueryAggregateColumnBuilder.this.filters.copy();
private ModelDynAttributeAccessor<TargetModelType, Integer> dynAttribute = CountIfQueryAggregateColumnBuilder.this.dynAttribute;
private int counter = 0;
@Override
public void add(final SourceModelType value) | {
if (filters.accept(value))
{
counter++;
}
// Update target model's dynamic attribute
dynAttribute.setValue(targetModel, counter);
}
@Override
public Integer getValue()
{
return counter;
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CountIfQueryAggregateColumnBuilder.java | 1 |
请完成以下Java代码 | public String getEventType() {
return eventType;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public EventSubscriptionEntity prepareEventSubscriptionEntity(ExecutionEntity execution) {
EventSubscriptionEntity eventSubscriptionEntity = null;
if ("message".equals(eventType)) {
eventSubscriptionEntity = new MessageEventSubscriptionEntity(execution);
} else if ("signal".equals(eventType)) {
eventSubscriptionEntity = new SignalEventSubscriptionEntity(execution);
} else {
throw new ActivitiIllegalArgumentException("Found event definition of unknown type: " + eventType); | }
eventSubscriptionEntity.setEventName(eventName);
if (activityId != null) {
ActivityImpl activity = execution.getProcessDefinition().findActivity(activityId);
eventSubscriptionEntity.setActivity(activity);
}
if (configuration != null) {
eventSubscriptionEntity.setConfiguration(configuration);
}
return eventSubscriptionEntity;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\EventSubscriptionDeclaration.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_CycleStep[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_Cycle getC_Cycle() throws RuntimeException
{
return (I_C_Cycle)MTable.get(getCtx(), I_C_Cycle.Table_Name)
.getPO(getC_Cycle_ID(), get_TrxName()); }
/** Set Project Cycle.
@param C_Cycle_ID
Identifier for this Project Reporting Cycle
*/
public void setC_Cycle_ID (int C_Cycle_ID)
{
if (C_Cycle_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, Integer.valueOf(C_Cycle_ID));
}
/** Get Project Cycle.
@return Identifier for this Project Reporting Cycle
*/
public int getC_Cycle_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Cycle Step.
@param C_CycleStep_ID
The step for this Cycle
*/
public void setC_CycleStep_ID (int C_CycleStep_ID)
{
if (C_CycleStep_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID));
}
/** Get Cycle Step.
@return The step for this Cycle
*/
public int getC_CycleStep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity | */
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Relative Weight.
@param RelativeWeight
Relative weight of this step (0 = ignored)
*/
public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CycleStep.java | 1 |
请完成以下Java代码 | void train() {
network.init();
int epochsNum = properties.getEpochsNum();
IntStream.range(1, epochsNum + 1).forEach(epoch -> {
log.info("Epoch {} / {}", epoch, epochsNum);
network.fit(dataSetService.trainIterator());
});
}
Evaluation evaluate() {
return network.evaluate(dataSetService.testIterator());
}
private ConvolutionLayer conv5x5() {
return new ConvolutionLayer.Builder(5, 5)
.nIn(3)
.nOut(16)
.stride(1, 1)
.padding(1, 1)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private SubsamplingLayer pooling2x2Stride2() {
return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2)
.stride(2, 2)
.build();
}
private ConvolutionLayer conv3x3Stride1Padding2() {
return new ConvolutionLayer.Builder(3, 3)
.nOut(32)
.stride(1, 1)
.padding(2, 2)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private SubsamplingLayer pooling2x2Stride1() {
return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX)
.kernelSize(2, 2)
.stride(1, 1) | .build();
}
private ConvolutionLayer conv3x3Stride1Padding1() {
return new ConvolutionLayer.Builder(3, 3)
.nOut(64)
.stride(1, 1)
.padding(1, 1)
.weightInit(WeightInit.XAVIER_UNIFORM)
.activation(Activation.RELU)
.build();
}
private OutputLayer dense() {
return new OutputLayer.Builder(LossFunctions.LossFunction.MEAN_SQUARED_LOGARITHMIC_ERROR)
.activation(Activation.SOFTMAX)
.weightInit(WeightInit.XAVIER_UNIFORM)
.nOut(dataSetService.labels().size() - 1)
.build();
}
} | repos\tutorials-master\deeplearning4j\src\main\java\com\baeldung\deeplearning4j\cnn\CnnModel.java | 1 |
请完成以下Java代码 | public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
return obj == this;
}
@Override
public Object invoke(ELContext context, Object[] params) {
try {
return method.invoke(null, params);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.identifier.method.access", name));
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e));
} catch (InvocationTargetException e) {
throw new ELException(
LocalMessages.get("error.identifier.method.invocation", name, e.getCause())
);
}
}
@Override
public MethodInfo getMethodInfo(ELContext context) {
return new MethodInfo(method.getName(), method.getReturnType(), method.getParameterTypes());
}
};
} else if (value instanceof MethodExpression) {
return (MethodExpression) value;
}
throw new MethodNotFoundException(
LocalMessages.get("error.identifier.method.notamethod", name, value.getClass())
);
}
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
return getMethodExpression(bindings, context, returnType, paramTypes).getMethodInfo(context);
}
public Object invoke(
Bindings bindings, | ELContext context,
Class<?> returnType,
Class<?>[] paramTypes,
Object[] params
) {
return getMethodExpression(bindings, context, returnType, paramTypes).invoke(context, params);
}
@Override
public String toString() {
return name;
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstIdentifier.java | 1 |
请完成以下Java代码 | public class ProductModel {
private String name;
private String description;
private String status;
private String currency;
private Double price;
private List<String> imageUrls;
private List<String> videoUrls;
private Integer stock;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price; | }
public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<String> getVideoUrls() {
return videoUrls;
}
public void setVideoUrls(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
@Override
public String toString() {
return "ProductModel{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", status='" + status + '\'' +
", currency='" + currency + '\'' +
", price=" + price +
", imageUrls=" + imageUrls +
", videoUrls=" + videoUrls +
", stock=" + stock +
'}';
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\model\ProductModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | void sendPeriodicMessages() throws IOException {
for (WebSocketSession session : sessions) {
if (session.isOpen()) {
String broadcast = "server periodic message " + LocalTime.now();
logger.info("Server sends: {}", broadcast);
session.sendMessage(new TextMessage(broadcast));
}
}
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String request = message.getPayload();
logger.info("Server received: {}", request); | String response = String.format("response from server to '%s'", HtmlUtils.htmlEscape(request));
logger.info("Server sends: {}", response);
session.sendMessage(new TextMessage(response));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) {
logger.info("Server transport error: {}", exception.getMessage());
}
@Override
public List<String> getSubProtocols() {
return Collections.singletonList("subprotocol.demo.websocket");
}
} | repos\tutorials-master\spring-web-modules\spring-websockets\src\main\java\com\baeldung\rawwebsocket\ServerWebSocketHandler.java | 2 |
请完成以下Java代码 | public int getDropShip_User_ID()
{
return dropShipUserId;
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
this.dropShipUserId = DropShip_User_ID;
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this); | }
@Override
public DropShipOverrideLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new DropShipOverrideLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_OLCand.class));
}
@Override
public I_C_OLCand getWrappedRecord()
{
return delegate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\location\adapter\DropShipOverrideLocationAdapter.java | 1 |
请完成以下Java代码 | public int getK_INDEX_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_INDEX_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Source Updated.
@param SourceUpdated
Date the source document was updated
*/
public void setSourceUpdated (Timestamp SourceUpdated)
{
set_Value (COLUMNNAME_SourceUpdated, SourceUpdated);
}
/** Get Source Updated.
@return Date the source document was updated
*/
public Timestamp getSourceUpdated ()
{
return (Timestamp)get_Value(COLUMNNAME_SourceUpdated);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Index.java | 1 |
请完成以下Java代码 | public String getFillValue() {
return "#585858";
}
@Override
public void drawIcon(int imageX, int imageY, int iconPadding, ProcessDiagramSVGGraphics2D svgGenerator) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 8) + "," + (imageY - 6) + ")");
Element polygonTag1 = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_POLYGON_TAG);
polygonTag1.setAttributeNS(null, "points", "14 8 14 22 7 15 ");
polygonTag1.setAttributeNS(null, "fill", this.getFillValue());
polygonTag1.setAttributeNS(null, "stroke", this.getStrokeValue());
polygonTag1.setAttributeNS(null, "stroke-width", this.getStrokeWidth());
polygonTag1.setAttributeNS(null, "stroke-linecap", "butt");
polygonTag1.setAttributeNS(null, "stroke-linejoin", "miter"); | polygonTag1.setAttributeNS(null, "stroke-miterlimit", "10");
gTag.appendChild(polygonTag1);
Element polygonTag2 = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_POLYGON_TAG);
polygonTag2.setAttributeNS(null, "points", "21 8 21 22 14 15 ");
polygonTag2.setAttributeNS(null, "fill", this.getFillValue());
polygonTag2.setAttributeNS(null, "stroke", this.getStrokeValue());
polygonTag2.setAttributeNS(null, "stroke-width", this.getStrokeWidth());
polygonTag2.setAttributeNS(null, "stroke-linecap", "butt");
polygonTag2.setAttributeNS(null, "stroke-linejoin", "miter");
polygonTag2.setAttributeNS(null, "stroke-miterlimit", "10");
gTag.appendChild(polygonTag2);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
} | repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\CompensateThrowIconType.java | 1 |
请完成以下Java代码 | public String getSourceRef() {
return sourceRef;
}
public void setSourceRef(String sourceRef) {
this.sourceRef = sourceRef;
}
public BaseElement getSourceElement() {
return sourceElement;
}
public void setSourceElement(BaseElement sourceElement) {
this.sourceElement = sourceElement;
}
public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
}
public BaseElement getTargetElement() {
return targetElement;
}
public void setTargetElement(BaseElement targetElement) {
this.targetElement = targetElement;
}
public String getTransitionEvent() {
return transitionEvent; | }
public void setTransitionEvent(String transitionEvent) {
this.transitionEvent = transitionEvent;
}
@Override
public Association clone() {
Association clone = new Association();
clone.setValues(this);
return clone;
}
public void setValues(Association otherElement) {
super.setValues(otherElement);
setSourceRef(otherElement.getSourceRef());
setTargetRef(otherElement.getTargetRef());
setTransitionEvent(otherElement.getTransitionEvent());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Association.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public SwaggerBasePathRewritingFilter swaggerBasePathRewritingFilter(){
return new SwaggerBasePathRewritingFilter();
}
}
@Configuration
public static class AccessControlFilterConfiguration {
@Bean
public AccessControlFilter accessControlFilter(RouteLocator routeLocator, JHipsterProperties jHipsterProperties){
return new AccessControlFilter(routeLocator, jHipsterProperties);
}
}
/**
* Configures the Zuul filter that limits the number of API calls per user.
* <p>
* This uses Bucket4J to limit the API calls, see {@link com.baeldung.jhipster.gateway.gateway.ratelimiting.RateLimitingFilter}. | */
@Configuration
@ConditionalOnProperty("jhipster.gateway.rate-limiting.enabled")
public static class RateLimitingConfiguration {
private final JHipsterProperties jHipsterProperties;
public RateLimitingConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Bean
public RateLimitingFilter rateLimitingFilter() {
return new RateLimitingFilter(jHipsterProperties);
}
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\config\GatewayConfiguration.java | 2 |
请完成以下Java代码 | public WidgetsBundle findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(widgetsBundleRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public WidgetsBundle findByTenantIdAndName(UUID tenantId, String name) {
return DaoUtil.getData(widgetsBundleRepository.findFirstByTenantIdAndTitle(tenantId, name));
}
@Override
public PageData<WidgetsBundle> findByTenantId(UUID tenantId, PageLink pageLink) {
return findTenantWidgetsBundlesByTenantId(tenantId, pageLink);
}
@Override
public WidgetsBundleId getExternalIdByInternal(WidgetsBundleId internalId) {
return Optional.ofNullable(widgetsBundleRepository.getExternalIdById(internalId.getId()))
.map(WidgetsBundleId::new).orElse(null);
}
@Override
public List<WidgetsBundle> findByTenantAndImageLink(TenantId tenantId, String imageUrl, int limit) {
return DaoUtil.convertDataList(widgetsBundleRepository.findByTenantAndImageUrl(tenantId.getId(), imageUrl, limit));
}
@Override | public List<WidgetsBundle> findByImageLink(String imageUrl, int limit) {
return DaoUtil.convertDataList(widgetsBundleRepository.findByImageUrl(imageUrl, limit));
}
@Override
public PageData<WidgetsBundle> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<? extends EntityFields> findNextBatch(UUID id, int batchSize) {
return widgetsBundleRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGETS_BUNDLE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\widget\JpaWidgetsBundleDao.java | 1 |
请完成以下Java代码 | public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public UserSexEnum getUserSex() {
return userSex;
}
public void setUserSex(UserSexEnum userSex) {
this.userSex = userSex;
}
public String getNickName() {
return nickName; | }
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", userSex=" + userSex +
", nickName='" + nickName + '\'' +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-mybatis-xml\src\main\java\com\neo\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<String> getDepartPathNameByOrgCode(@RequestParam(name = "orgCode", required = false) String orgCode,
@RequestParam(name = "depId", required = false) String depId) {
String departName = sysDepartService.getDepartPathNameByOrgCode(orgCode, depId);
return Result.OK(departName);
}
/**
* 根据部门id获取部门下的岗位id
*
* @param depIds 当前选择的公司、子公司、部门id
* @return
*/
@GetMapping("/getDepPostIdByDepId")
public Result<Map<String, String>> getDepPostIdByDepId(@RequestParam(name = "depIds") String depIds) {
String departIds = sysDepartService.getDepPostIdByDepId(depIds);
return Result.OK(departIds);
}
/**
* 更新改变后的部门数据
*
* @param changeDepartVo
* @return
*/ | @PutMapping("/updateChangeDepart")
@RequiresPermissions("system:depart:updateChange")
@RequiresRoles({"admin"})
public Result<String> updateChangeDepart(@RequestBody SysChangeDepartVo changeDepartVo) {
sysDepartService.updateChangeDepart(changeDepartVo);
return Result.ok("调整部门位置成功!");
}
/**
* 获取部门负责人
*
* @param departId
* @return
*/
@GetMapping("/getDepartmentHead")
public Result<IPage<SysUser>> getDepartmentHead(@RequestParam(name = "departId") String departId,
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
Page<SysUser> page = new Page<>(pageNo, pageSize);
IPage<SysUser> pageList = sysDepartService.getDepartmentHead(departId,page);
return Result.OK(pageList);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDepartController.java | 2 |
请完成以下Java代码 | public void setDivideRate (java.math.BigDecimal DivideRate)
{
set_Value (COLUMNNAME_DivideRate, DivideRate);
}
/** Get Divisor.
@return To convert Source number to Target number, the Source is divided
*/
@Override
public java.math.BigDecimal getDivideRate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Faktor.
@param MultiplyRate
Rate to multiple the source by to calculate the target.
*/
@Override
public void setMultiplyRate (java.math.BigDecimal MultiplyRate)
{
set_Value (COLUMNNAME_MultiplyRate, MultiplyRate);
}
/** Get Faktor.
@return Rate to multiple the source by to calculate the target.
*/
@Override
public java.math.BigDecimal getMultiplyRate ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate);
if (bd == null)
return Env.ZERO;
return bd;
} | /** Set Gültig ab.
@param ValidFrom
Valid from including this date (first day)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Valid from including this date (first day)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Valid to including this date (last day)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Valid to including this date (last day)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Conversion_Rate.java | 1 |
请完成以下Java代码 | protected void writeItemDefinition(List<ItemDefinition> itemDefinitions, DmnDefinition model, XMLStreamWriter xtw) throws Exception {
writeItemDefinition(itemDefinitions, false, model, xtw);
}
protected void writeItemDefinition(List<ItemDefinition> itemDefinitions, boolean isItemComponent, DmnDefinition model, XMLStreamWriter xtw) throws Exception {
if (itemDefinitions == null) {
return;
}
for (ItemDefinition itemDefinition : itemDefinitions) {
if (isItemComponent) {
xtw.writeStartElement(ELEMENT_ITEM_COMPONENT);
} else {
xtw.writeStartElement(ELEMENT_ITEM_DEFINITION);
}
if (StringUtils.isNotEmpty(itemDefinition.getId())) {
xtw.writeAttribute(ATTRIBUTE_ID, itemDefinition.getId());
}
if (StringUtils.isNotEmpty(itemDefinition.getName())) {
xtw.writeAttribute(ATTRIBUTE_NAME, itemDefinition.getName());
}
if (StringUtils.isNotEmpty(itemDefinition.getLabel())) {
xtw.writeAttribute(ATTRIBUTE_LABEL, itemDefinition.getLabel());
}
if (itemDefinition.isCollection()) {
xtw.writeAttribute(ATTRIBUTE_IS_COLLECTION, "true");
} | DmnXMLUtil.writeElementDescription(itemDefinition, xtw);
DmnXMLUtil.writeExtensionElements(itemDefinition, model.getNamespaces(), xtw);
if (itemDefinition.getTypeRef() != null) {
xtw.writeStartElement(ELEMENT_TYPE_REF);
xtw.writeCharacters(itemDefinition.getTypeRef());
xtw.writeEndElement();
}
if (itemDefinition.getAllowedValues() != null) {
xtw.writeStartElement(ELEMENT_REQUIRED_AUTHORITY);
xtw.writeStartElement(ELEMENT_TEXT);
xtw.writeCharacters(itemDefinition.getAllowedValues().getText());
xtw.writeEndElement();
xtw.writeEndElement();
}
if (itemDefinition.getItemComponents().size() > 0) {
writeItemDefinition(itemDefinition.getItemComponents(), true, model, xtw);
}
xtw.writeEndElement();
}
}
} | repos\flowable-engine-main\modules\flowable-dmn-xml-converter\src\main\java\org\flowable\dmn\xml\converter\DmnXMLConverter.java | 1 |
请完成以下Java代码 | public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public List<EventSubscriptionQueryValue> getEventSubscriptions() {
return eventSubscriptions;
}
public boolean isIncludeChildExecutionsWithBusinessKeyQuery() {
return includeChildExecutionsWithBusinessKeyQuery;
}
public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) {
this.eventSubscriptions = eventSubscriptions;
}
public boolean isActive() {
return isActive;
}
public String getInvolvedUser() {
return involvedUser;
}
public void setInvolvedUser(String involvedUser) {
this.involvedUser = involvedUser;
}
public Set<String> getProcessDefinitionIds() {
return processDefinitionIds;
}
public Set<String> getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getParentId() {
return parentId;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getName() { | return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public void setNameLikeIgnoreCase(String nameLikeIgnoreCase) {
this.nameLikeIgnoreCase = nameLikeIgnoreCase;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ExecutionQueryImpl.java | 1 |
请完成以下Java代码 | public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Scheduler getAD_Scheduler() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class);
}
@Override
public void setAD_Scheduler(org.compiere.model.I_AD_Scheduler AD_Scheduler)
{
set_ValueFromPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class, AD_Scheduler);
}
/** Set Ablaufsteuerung.
@param AD_Scheduler_ID
Schedule Processes
*/
@Override
public void setAD_Scheduler_ID (int AD_Scheduler_ID)
{
if (AD_Scheduler_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, Integer.valueOf(AD_Scheduler_ID));
}
/** Get Ablaufsteuerung.
@return Schedule Processes
*/
@Override
public int getAD_Scheduler_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Scheduler_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Empfänger.
@param AD_SchedulerRecipient_ID
Recipient of the Scheduler Notification
*/
@Override
public void setAD_SchedulerRecipient_ID (int AD_SchedulerRecipient_ID)
{
if (AD_SchedulerRecipient_ID < 1) | set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, Integer.valueOf(AD_SchedulerRecipient_ID));
}
/** Get Empfänger.
@return Recipient of the Scheduler Notification
*/
@Override
public int getAD_SchedulerRecipient_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_SchedulerRecipient_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerRecipient.java | 1 |
请完成以下Java代码 | public final class Point {
private final int x;
private final int y;
private final int z;
private static Point ORIGIN = new Point(0, 0, 0);
private Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Point valueOfPoint(int x, int y, int z) {
// returns a cached instance if it is origin, or a new instance
if (isOrigin(x, y, z))
return ORIGIN;
return new Point(x, y, z);
}
@Override | public String toString() {
return "Point{" + "x=" + x + ", y=" + y + ", z=" + z + '}';
}
@Override
public boolean equals(Object other) {
if (other == null || getClass() != other.getClass())
return false;
Point point = (Point) other;
return x == point.x && y == point.y && z == point.z;
}
@Override
public int hashCode() {
return Objects.hash(x, y, z);
}
private static boolean isOrigin(int x, int y, int z) {
return x == 0 && y == 0 && z == 0;
}
} | repos\tutorials-master\core-java-modules\core-java-16\src\main\java\com\baeldung\value_based_class\Point.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MobileApplicationActionId implements RepoIdAware
{
@JsonCreator
public static MobileApplicationActionId ofRepoId(final int repoId)
{
return new MobileApplicationActionId(repoId);
}
@Nullable
public static MobileApplicationActionId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new MobileApplicationActionId(repoId) : null;
}
public static int toRepoId(@Nullable final MobileApplicationActionId MobileApplicationActionId)
{ | return MobileApplicationActionId != null ? MobileApplicationActionId.getRepoId() : -1;
}
int repoId;
private MobileApplicationActionId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "Mobile_Application_Action_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\application\MobileApplicationActionId.java | 2 |
请完成以下Java代码 | public List<FieldDeclaration> createFieldDeclarations(List<FieldExtension> fieldList) {
List<FieldDeclaration> fieldDeclarations = new ArrayList<FieldDeclaration>();
for (FieldExtension fieldExtension : fieldList) {
FieldDeclaration fieldDeclaration = null;
if (StringUtils.isNotEmpty(fieldExtension.getExpression())) {
fieldDeclaration = new FieldDeclaration(
fieldExtension.getFieldName(),
Expression.class.getName(),
expressionManager.createExpression(fieldExtension.getExpression())
);
} else {
fieldDeclaration = new FieldDeclaration(
fieldExtension.getFieldName(),
Expression.class.getName(),
new FixedValue(fieldExtension.getStringValue())
);
}
fieldDeclarations.add(fieldDeclaration);
}
return fieldDeclarations;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public ThrowMessageDelegateFactory getThrowMessageDelegateFactory() {
return throwMessageDelegateFactory;
} | public void setThrowMessageDelegateFactory(ThrowMessageDelegateFactory throwMessageDelegateFactory) {
this.throwMessageDelegateFactory = throwMessageDelegateFactory;
}
public MessagePayloadMappingProviderFactory getMessagePayloadMappingProviderFactory() {
return messagePayloadMappingProviderFactory;
}
public void setMessagePayloadMappingProviderFactory(
MessagePayloadMappingProviderFactory messagePayloadMappingProviderFactory
) {
this.messagePayloadMappingProviderFactory = messagePayloadMappingProviderFactory;
}
public MessageExecutionContextFactory getMessageExecutionContextFactory() {
return messageExecutionContextFactory;
}
public void setMessageExecutionContextFactory(MessageExecutionContextFactory messageExecutionContextFactory) {
this.messageExecutionContextFactory = messageExecutionContextFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\AbstractBehaviorFactory.java | 1 |
请完成以下Java代码 | public void setAsText(String s) throws IllegalArgumentException {
if (!StringUtils.hasText(s)) {
setValue(null);
return;
}
String[] tokens = StringUtils.commaDelimitedListToStringArray(s);
UserAttribute userAttrib = new UserAttribute();
List<String> authoritiesAsStrings = new ArrayList<>();
for (int i = 0; i < tokens.length; i++) {
String currentToken = tokens[i].trim();
if (i == 0) {
userAttrib.setPassword(currentToken);
}
else {
if (currentToken.toLowerCase(Locale.ENGLISH).equals("enabled")) { | userAttrib.setEnabled(true);
}
else if (currentToken.toLowerCase(Locale.ENGLISH).equals("disabled")) {
userAttrib.setEnabled(false);
}
else {
authoritiesAsStrings.add(currentToken);
}
}
}
userAttrib.setAuthoritiesAsString(authoritiesAsStrings);
setValue(userAttrib.isValid() ? userAttrib : null);
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\userdetails\memory\UserAttributeEditor.java | 1 |
请完成以下Java代码 | public void setOrderedData(final I_C_Invoice_Candidate ic)
{
// nothing to do; the value won't change
}
/**
* <ul>
* <li>QtyDelivered := QtyOrdered
* <li>DeliveryDate := DateOrdered
* <li>M_InOut_ID: untouched
* </ul>
*
* @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate)
*/
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially
ic.setQtyDeliveredInUOM(ic.getQtyEntered());
ic.setDeliveryDate(ic.getDateOrdered());
}
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic) | {
// nothing to do; the value won't change
}
/**
* @return {@link OnInvalidateForModelAction#RECREATE_ASYNC}.
*/
@Override
public final OnInvalidateForModelAction getOnInvalidateForModelAction()
{
return OnInvalidateForModelAction.RECREATE_ASYNC;
}
/* package */boolean isInvoiceable(final Object model)
{
final I_PP_Order ppOrder = InterfaceWrapperHelper.create(model, I_PP_Order.class);
return dao.isInvoiceable(ppOrder);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\PP_Order_MaterialTracking_Handler.java | 1 |
请完成以下Java代码 | public void onCompleted() {
CallUnaryRpc();
}
});
}
private void CallClientStreamingRpc() {
byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(10240, 20480)];
ThreadLocalRandom.current().nextBytes(bytes);
ClientStreamingRequest request = ClientStreamingRequest.newBuilder()
.setMessage(new String(bytes)).build();
StreamObserver<ClientStreamingRequest> requestStreamObserver = stub.clientStreamingRpc(
new StreamObserver<>() {
@Override
public void onNext(ClientStreamingResponse value) {}
@Override
public void onError(Throwable t) {
CallClientStreamingRpc();
}
@Override
public void onCompleted() {
CallClientStreamingRpc();
}
});
requestStreamObserver.onNext(request);
requestStreamObserver.onCompleted();
}
private void CallServerStreamingRpc() {
byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(10240, 20480)];
ThreadLocalRandom.current().nextBytes(bytes);
ServerStreamingRequest request = ServerStreamingRequest.newBuilder()
.setMessage(new String(bytes)).build();
stub.serverStreamingRpc(request, new StreamObserver<>() {
@Override
public void onNext(ServerStreamingResponse value) {}
@Override
public void onError(Throwable t) {
CallServerStreamingRpc();
} | @Override
public void onCompleted() {
CallServerStreamingRpc();
}
});
}
private void CallBidStreamingRpc() {
byte[] bytes = new byte[ThreadLocalRandom.current().nextInt(10240, 20480)];
ThreadLocalRandom.current().nextBytes(bytes);
BidiStreamingRequest request = BidiStreamingRequest.newBuilder()
.setMessage(new String(bytes)).build();
StreamObserver<BidiStreamingRequest> requestStreamObserver = stub.bidiStreamingRpc(
new StreamObserver<>() {
@Override
public void onNext(BidiStreamingResponse value) {}
@Override
public void onError(Throwable t) {
CallBidStreamingRpc();
}
@Override
public void onCompleted() {
CallBidStreamingRpc();
}
});
requestStreamObserver.onNext(request);
requestStreamObserver.onCompleted();
}
@Override
public void run(String... args) {
CallUnaryRpc();
CallServerStreamingRpc();
CallClientStreamingRpc();
CallBidStreamingRpc();
}
} | repos\grpc-spring-master\examples\grpc-observability\frontend\src\main\java\net\devh\boot\grpc\examples\observability\frontend\FrontendApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultJwtService implements JwtService {
private final SecretKey signingKey;
private final SignatureAlgorithm signatureAlgorithm;
private int sessionTime;
@Autowired
public DefaultJwtService(
@Value("${jwt.secret}") String secret, @Value("${jwt.sessionTime}") int sessionTime) {
this.sessionTime = sessionTime;
signatureAlgorithm = SignatureAlgorithm.HS512;
this.signingKey = new SecretKeySpec(secret.getBytes(), signatureAlgorithm.getJcaName());
}
@Override
public String toToken(User user) {
return Jwts.builder()
.setSubject(user.getId())
.setExpiration(expireTimeFromNow())
.signWith(signingKey)
.compact(); | }
@Override
public Optional<String> getSubFromToken(String token) {
try {
Jws<Claims> claimsJws =
Jwts.parserBuilder().setSigningKey(signingKey).build().parseClaimsJws(token);
return Optional.ofNullable(claimsJws.getBody().getSubject());
} catch (Exception e) {
return Optional.empty();
}
}
private Date expireTimeFromNow() {
return new Date(System.currentTimeMillis() + sessionTime * 1000L);
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\infrastructure\service\DefaultJwtService.java | 2 |
请完成以下Java代码 | public BigDecimal getCol_8 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Col_8);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Payroll List Line.
@param HR_ListLine_ID Payroll List Line */
public void setHR_ListLine_ID (int HR_ListLine_ID)
{
if (HR_ListLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListLine_ID, Integer.valueOf(HR_ListLine_ID));
}
/** Get Payroll List Line.
@return Payroll List Line */
public int getHR_ListLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.eevolution.model.I_HR_ListVersion getHR_ListVersion() throws RuntimeException
{
return (org.eevolution.model.I_HR_ListVersion)MTable.get(getCtx(), org.eevolution.model.I_HR_ListVersion.Table_Name)
.getPO(getHR_ListVersion_ID(), get_TrxName()); }
/** Set Payroll List Version.
@param HR_ListVersion_ID Payroll List Version */
public void setHR_ListVersion_ID (int HR_ListVersion_ID)
{
if (HR_ListVersion_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, Integer.valueOf(HR_ListVersion_ID));
}
/** Get Payroll List Version.
@return Payroll List Version */
public int getHR_ListVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Max Value.
@param MaxValue Max Value */
public void setMaxValue (BigDecimal MaxValue)
{
set_Value (COLUMNNAME_MaxValue, MaxValue); | }
/** Get Max Value.
@return Max Value */
public BigDecimal getMaxValue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxValue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Min Value.
@param MinValue Min Value */
public void setMinValue (BigDecimal MinValue)
{
set_Value (COLUMNNAME_MinValue, MinValue);
}
/** Get Min Value.
@return Min Value */
public BigDecimal getMinValue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinValue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** 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\eevolution\model\X_HR_ListLine.java | 1 |
请完成以下Java代码 | public String getDecisionKey() {
return decisionKey;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
}
public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
public Map<String, Object> getVariables() {
return variables;
} | @Override
public ExecuteDecisionContext buildExecuteDecisionContext() {
ExecuteDecisionContext executeDecisionContext = new ExecuteDecisionContext();
executeDecisionContext.setDecisionKey(decisionKey);
executeDecisionContext.setParentDeploymentId(parentDeploymentId);
executeDecisionContext.setInstanceId(instanceId);
executeDecisionContext.setExecutionId(executionId);
executeDecisionContext.setActivityId(activityId);
executeDecisionContext.setScopeType(scopeType);
executeDecisionContext.setVariables(variables);
executeDecisionContext.setTenantId(tenantId);
executeDecisionContext.setFallbackToDefaultTenant(fallbackToDefaultTenant);
executeDecisionContext.setDisableHistory(disableHistory);
return executeDecisionContext;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\ExecuteDecisionBuilderImpl.java | 1 |
请完成以下Java代码 | public class CreditCard {
private String rawCardNumber;
private Integer bankIdNo;
private Integer accountNo;
private Integer checkCode;
public String getRawCardNumber() {
return rawCardNumber;
}
public void setRawCardNumber(String rawCardNumber) {
this.rawCardNumber = rawCardNumber;
}
public Integer getBankIdNo() {
return bankIdNo;
}
public void setBankIdNo(Integer bankIdNo) {
this.bankIdNo = bankIdNo;
} | public Integer getAccountNo() {
return accountNo;
}
public void setAccountNo(Integer accountNo) {
this.accountNo = accountNo;
}
public Integer getCheckCode() {
return checkCode;
}
public void setCheckCode(Integer checkCode) {
this.checkCode = checkCode;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data-3\src\main\java\com\baeldung\propertyeditor\creditcard\CreditCard.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
public User() {
}
public User(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public User(final Long id, final String firstName, final String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) { | return false;
}
final User user = (User) o;
if (!Objects.equals(id, user.id)) {
return false;
}
if (!Objects.equals(firstName, user.firstName)) {
return false;
}
return Objects.equals(lastName, user.lastName);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-query-4\src\main\java\com\baeldung\spring\data\jpa\querymap\User.java | 2 |
请完成以下Java代码 | private void handle() throws Exception {
try {
try (OutputStream outputStream = this.socket.getOutputStream()) {
Connection connection = createConnection(this.socket, this.inputStream, outputStream);
runConnection(connection);
}
finally {
this.inputStream.close();
}
}
finally {
this.socket.close();
}
}
private void runConnection(Connection connection) throws Exception {
try {
addConnection(connection);
connection.run();
}
finally {
removeConnection(connection);
}
}
}
/**
* {@link ThreadFactory} to create the worker threads.
*/ | private static final class WorkerThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("Live Reload #" + this.threadNumber.getAndIncrement());
return thread;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\livereload\LiveReloadServer.java | 1 |
请完成以下Java代码 | public InputStream getCaseModel(String caseDefinitionId) {
try {
return commandExecutor.execute(new GetDeploymentCaseModelCmd(caseDefinitionId));
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (CaseDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (DeploymentResourceNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
}
public DecisionDefinition getDecisionDefinition(String decisionDefinitionId) {
try {
return commandExecutor.execute(new GetDeploymentDecisionDefinitionCmd(decisionDefinitionId));
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (DecisionDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
}
public DecisionRequirementsDefinition getDecisionRequirementsDefinition(String decisionRequirementsDefinitionId) {
try {
return commandExecutor.execute(new GetDeploymentDecisionRequirementsDefinitionCmd(decisionRequirementsDefinitionId));
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (DecisionDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
}
public InputStream getDecisionModel(String decisionDefinitionId) {
try {
return commandExecutor.execute(new GetDeploymentDecisionModelCmd(decisionDefinitionId));
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e); | } catch (DecisionDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (DeploymentResourceNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
}
public InputStream getDecisionRequirementsModel(String decisionRequirementsDefinitionId) {
try {
return commandExecutor.execute(new GetDeploymentDecisionRequirementsModelCmd(decisionRequirementsDefinitionId));
} catch (NullValueException e) {
throw new NotValidException(e.getMessage(), e);
} catch (DecisionDefinitionNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
} catch (DeploymentResourceNotFoundException e) {
throw new NotFoundException(e.getMessage(), e);
}
}
public InputStream getDecisionDiagram(String decisionDefinitionId) {
return commandExecutor.execute(new GetDeploymentDecisionDiagramCmd(decisionDefinitionId));
}
public InputStream getDecisionRequirementsDiagram(String decisionRequirementsDefinitionId) {
return commandExecutor.execute(new GetDeploymentDecisionRequirementsDiagramCmd(decisionRequirementsDefinitionId));
}
@Override
public Collection<CalledProcessDefinition> getStaticCalledProcessDefinitions(String processDefinitionId) {
return commandExecutor.execute(new GetStaticCalledProcessDefinitionCmd(processDefinitionId));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RepositoryServiceImpl.java | 1 |
请完成以下Java代码 | public int deleteNotProcessedCandidates(final IDunningContext context, final I_C_DunningLevel dunningLevel)
{
final String deleteSQL = "DELETE FROM " + I_C_Dunning_Candidate.Table_Name +
" WHERE "
+ I_C_Dunning_Candidate.COLUMNNAME_IsActive + "='Y' AND "
+ I_C_Dunning_Candidate.COLUMNNAME_AD_Client_ID + "=? AND "
+ I_C_Dunning_Candidate.COLUMNNAME_Processed + "='N' AND "
+ I_C_Dunning_Candidate.COLUMNNAME_C_DunningLevel_ID + "=?";
final int[] result = { 0 };
Services.get(ITrxManager.class).run(context.getTrxName(), context.getTrxRunnerConfig(), new TrxRunnable()
{
@Override
public void run(final String localTrxName)
{
result[0] = DB.executeUpdateAndThrowExceptionOnFail(deleteSQL, new Object[] { Env.getAD_Client_ID(context.getCtx()), dunningLevel.getC_DunningLevel_ID() }, localTrxName);
}
}); | return result[0];
}
@Override
public List<I_C_Dunning_Candidate> retrieveProcessedDunningCandidatesForRecord(final Properties ctx, final int tableId, final int recordId, final String trxName)
{
final StringBuilder whereClause = new StringBuilder();
whereClause.append(I_C_Dunning_Candidate.COLUMNNAME_AD_Table_ID).append("=?")
.append(" AND ")
.append(I_C_Dunning_Candidate.COLUMNNAME_Record_ID).append("=?")
.append(" AND ")
.append(I_C_Dunning_Candidate.COLUMNNAME_IsDunningDocProcessed).append("='Y'");
return new Query(ctx, I_C_Dunning_Candidate.Table_Name, whereClause.toString(), trxName)
.setParameters(tableId, recordId)
.list(I_C_Dunning_Candidate.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningDAO.java | 1 |
请完成以下Java代码 | private void bulkUpdatePendingTransactionsNoFail()
{
try
{
final BulkUpdateByQueryResult result = sumUpService.bulkUpdatePendingTransactions(false);
if (!result.isZero())
{
logger.debug("Pending transactions updated: {}", result);
}
// Set the pending transactions flag as long as we get some updates
pendingTransactionsDetected.set(!result.isZero());
}
catch (final Exception ex)
{
logger.warn("Failed to process. Ignored.", ex);
} | }
private Duration getPollInterval()
{
final int valueInt = sysConfigBL.getPositiveIntValue(SYSCONFIG_PollIntervalInSeconds, 0);
return valueInt > 0 ? Duration.ofSeconds(valueInt) : DEFAULT_PollInterval;
}
@Override
public void onStatusChanged(@NonNull final SumUpTransactionStatusChangedEvent event)
{
if (event.getStatusNew().isPending())
{
pendingTransactionsDetected.set(true);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\server\SumUpPendingTransactionContinuousUpdater.java | 1 |
请完成以下Java代码 | public String showNewTodoPage(ModelMap model) {
String username = getLoggedInUsername(model);
Todo todo = new Todo(0, username, "", LocalDate.now().plusYears(1), false);
model.put("todo", todo);
return "todo";
}
@RequestMapping(value="add-todo", method = RequestMethod.POST)
public String addNewTodo(ModelMap model, @Valid Todo todo, BindingResult result) {
if(result.hasErrors()) {
return "todo";
}
String username = getLoggedInUsername(model);
todoService.addTodo(username, todo.getDescription(),
LocalDate.now().plusYears(1), false);
return "redirect:list-todos";
}
@RequestMapping("delete-todo")
public String deleteTodo(@RequestParam int id) {
//Delete todo
todoService.deleteById(id);
return "redirect:list-todos";
}
@RequestMapping(value="update-todo", method = RequestMethod.GET)
public String showUpdateTodoPage(@RequestParam int id, ModelMap model) {
Todo todo = todoService.findById(id);
model.addAttribute("todo", todo);
return "todo";
} | @RequestMapping(value="update-todo", method = RequestMethod.POST)
public String updateTodo(ModelMap model, @Valid Todo todo, BindingResult result) {
if(result.hasErrors()) {
return "todo";
}
String username = getLoggedInUsername(model);
todo.setUsername(username);
todoService.updateTodo(todo);
return "redirect:list-todos";
}
private String getLoggedInUsername(ModelMap model) {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
}
} | repos\master-spring-and-spring-boot-main\11-web-application\src\main\java\com\in28minutes\springboot\myfirstwebapp\todo\TodoController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class M_Product
{
private void runAfterCommit(@NonNull final Runnable runnable)
{
Services.get(ITrxManager.class)
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> runnable.run());
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void onNew(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
if (!isMSV3ServerProduct(serverConfig, product))
{
return;
}
final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
runAfterCommit(() -> getStockAvailabilityService().publishProductAddedEvent(productId));
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = { I_M_Product.COLUMNNAME_IsActive, I_M_Product.COLUMNNAME_M_Product_Category_ID })
public void onChange(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
final I_M_Product productOld = InterfaceWrapperHelper.createOld(product, I_M_Product.class);
final boolean wasMSV3Product = isMSV3ServerProduct(serverConfig, productOld);
final boolean isMSV3Product = isMSV3ServerProduct(serverConfig, product);
if (wasMSV3Product == isMSV3Product)
{
return;
}
final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
if (isMSV3Product)
{
runAfterCommit(() -> getStockAvailabilityService().publishProductChangedEvent(productId));
}
else
{
runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId));
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void onDelete(final I_M_Product product)
{
final MSV3ServerConfig serverConfig = getServerConfigService().getServerConfig();
if (!isMSV3ServerProduct(serverConfig, product))
{
return;
} | final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID());
runAfterCommit(() -> getStockAvailabilityService().publishProductDeletedEvent(productId));
}
private boolean isMSV3ServerProduct(final MSV3ServerConfig serverConfig, final I_M_Product product)
{
if (!serverConfig.hasProducts())
{
return false;
}
if (!product.isActive())
{
return false;
}
final ProductCategoryId productCategoryId = ProductCategoryId.ofRepoId(product.getM_Product_Category_ID());
if (!serverConfig.getProductCategoryIds().contains(productCategoryId))
{
return false;
}
return true;
}
private MSV3ServerConfigService getServerConfigService()
{
return Adempiere.getBean(MSV3ServerConfigService.class);
}
private MSV3StockAvailabilityService getStockAvailabilityService()
{
return Adempiere.getBean(MSV3StockAvailabilityService.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\interceptor\M_Product.java | 2 |
请完成以下Java代码 | public Money getGrandTotal(@NonNull final I_C_Order order)
{
final BigDecimal grandTotal = order.getGrandTotal();
return Money.of(grandTotal, CurrencyId.ofRepoId(order.getC_Currency_ID()));
}
@Override
public void save(final I_C_Order order)
{
orderDAO.save(order);
}
@Override
public void syncDatesFromTransportOrder(@NonNull final OrderId orderId, @NonNull final I_M_ShipperTransportation transportOrder)
{
final I_C_Order order = getById(orderId);
order.setBLDate(transportOrder.getBLDate()); | order.setETA(transportOrder.getETA());
save(order);
}
@Override
public void syncDateInvoicedFromInvoice(@NonNull final OrderId orderId, @NonNull final I_C_Invoice invoice)
{
final I_C_Order order = getById(orderId);
order.setInvoiceDate(invoice.getDateInvoiced());
save(order);
}
public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter)
{
return orderDAO.getByQueryFilter(queryFilter);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderBL.java | 1 |
请完成以下Java代码 | public void addResourceHandlers(final @NonNull ResourceHandlerRegistry registry)
{
if (Check.isEmpty(downloadsPath, true))
{
downloadsPath = defaultDownloadsPath();
}
// Make sure the path ends with separator
// see https://jira.spring.io/browse/SPR-14063
if (downloadsPath != null && !downloadsPath.endsWith(File.separator))
{
downloadsPath += File.separator;
}
if (!Check.isEmpty(downloadsPath, true))
{
logger.info("Serving static content from " + downloadsPath);
registry.addResourceHandler("/download/**").addResourceLocations("file:" + downloadsPath);
// the "binaries" download path is about to be removed soon!
registry.addResourceHandler("/binaries/**").addResourceLocations("file:" + downloadsPath); | }
}
@Nullable
private String defaultDownloadsPath()
{
try
{
final File cwd = new File(".").getCanonicalFile();
final File downloadsFile = new File(cwd, "download");
return downloadsFile.getCanonicalPath();
}
catch (final IOException ex)
{
logger.warn("Failed finding the default downloads path", ex);
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\home_page\DownloadsFolderConfiguration.java | 1 |
请完成以下Java代码 | public Object extractFieldValueForDataEntry(@NonNull final IDocumentFieldView fieldView)
{
final Object value = fieldView.getValue();
final DocumentFieldDescriptor descriptor = fieldView.getDescriptor();
final DataEntryFieldBindingDescriptor dataBinding = descriptor.getDataBindingNotNull(DataEntryFieldBindingDescriptor.class);
final FieldType fieldType = dataBinding.getFieldType();
if (value == null)
{
return null;
}
final Object result;
switch (fieldType)
{
case DATE:
result = fieldType.getClazz().cast(value);
break;
case LIST:
final LookupDescriptor lookupDescriptor = descriptor.getLookupDescriptor().get();
final DataEntryListValueDataSourceFetcher fetcher = (DataEntryListValueDataSourceFetcher)lookupDescriptor.getLookupDataSourceFetcher();
result = fetcher.getListValueIdForLookup((IntegerLookupValue)value);
break;
case NUMBER:
result = fieldType.getClazz().cast(value);
break;
case TEXT:
result = fieldType.getClazz().cast(value);
break;
case LONG_TEXT:
result = fieldType.getClazz().cast(value);
break;
case YESNO: | result = fieldType.getClazz().cast(value);
break;
case PARENT_LINK_ID:
result = fieldType.getClazz().cast(value);
break;
case SUB_TAB_ID:
result = fieldType.getClazz().cast(value);
break;
default:
// this includes CREATED_UPDATED_INFO, PARENT_LINK_ID and SUB_TAB_ID; we don't expect the document repo to try and extract these
throw new AdempiereException("Unexpected fieldType=" + fieldType);
}
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryWebuiTools.java | 1 |
请完成以下Java代码 | public IScriptFactory getScriptFactory()
{
return scriptFactory;
}
@Override
public void setScriptFactory(final IScriptFactory scriptFactory)
{
this.scriptFactory = scriptFactory;
}
@Override
public IScriptFactory getScriptFactoryToUse()
{
//
// If there is an script factory defined on this level, return it
{
final IScriptFactory scriptFactory = getScriptFactory();
if (scriptFactory != null)
{
return scriptFactory;
} | }
//
// Ask parent script scanner
if (parentScanner != null)
{
final IScriptFactory scriptFactory = parentScanner.getScriptFactoryToUse();
if (scriptFactory != null)
{
return scriptFactory;
}
}
//
// Ask Script Scanner Factory for IScriptFactory
{
final IScriptScannerFactory scriptScannerFactory = getScriptScannerFactoryToUse();
final IScriptFactory scriptFactory = scriptScannerFactory.getScriptFactoryToUse();
return scriptFactory;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\AbstractScriptScanner.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected ProcessPreconditionsResolution checkIsServiceOrRepairProject(@NonNull final ProjectId projectId)
{
return projectService.isServiceOrRepair(projectId)
? ProcessPreconditionsResolution.accept()
: ProcessPreconditionsResolution.rejectWithInternalReason("not Service/Repair project");
}
protected ProjectId getProjectId()
{
return ProjectId.ofRepoId(getRecord_ID());
}
protected ServiceRepairProjectInfo getProject()
{
final ProjectId projectId = getProjectId();
return projectService.getById(projectId);
}
protected ServiceRepairProjectTaskId getSingleSelectedTaskId()
{
return CollectionUtils.singleElement(getSelectedTaskIds());
}
protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds()
{
final ProjectId projectId = getProjectId();
return getSelectedIncludedRecordIds(I_C_Project_Repair_Task.class)
.stream()
.map(taskRepoId -> ServiceRepairProjectTaskId.ofRepoId(projectId, taskRepoId))
.collect(ImmutableSet.toImmutableSet());
}
protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedSparePartsTaskIds(final @NonNull IProcessPreconditionsContext context)
{
final ImmutableSet<ServiceRepairProjectTaskId> taskIds = getSelectedTaskIds(context);
return projectService.retainIdsOfTypeSpareParts(taskIds);
} | protected ImmutableSet<ServiceRepairProjectTaskId> getSelectedTaskIds(final @NonNull IProcessPreconditionsContext context)
{
final ProjectId projectId = ProjectId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
if (projectId == null)
{
return ImmutableSet.of();
}
return context.getSelectedIncludedRecords()
.stream()
.filter(recordRef -> I_C_Project_Repair_Task.Table_Name.equals(recordRef.getTableName()))
.map(recordRef -> ServiceRepairProjectTaskId.ofRepoId(projectId, recordRef.getRecord_ID()))
.collect(ImmutableSet.toImmutableSet());
}
protected List<ServiceRepairProjectTask> getSelectedTasks(final @NonNull IProcessPreconditionsContext context)
{
return projectService.getTasksByIds(getSelectedTaskIds(context));
}
protected List<ServiceRepairProjectTask> getSelectedTasks()
{
return projectService.getTasksByIds(getSelectedTaskIds());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\project\process\ServiceOrRepairProjectBasedProcess.java | 2 |
请完成以下Java代码 | public de.metas.contracts.commission.model.I_C_MediatedCommissionSettings getC_MediatedCommissionSettings()
{
return get_ValueAsPO(COLUMNNAME_C_MediatedCommissionSettings_ID, de.metas.contracts.commission.model.I_C_MediatedCommissionSettings.class);
}
@Override
public void setC_MediatedCommissionSettings(final de.metas.contracts.commission.model.I_C_MediatedCommissionSettings C_MediatedCommissionSettings)
{
set_ValueFromPO(COLUMNNAME_C_MediatedCommissionSettings_ID, de.metas.contracts.commission.model.I_C_MediatedCommissionSettings.class, C_MediatedCommissionSettings);
}
@Override
public void setC_MediatedCommissionSettings_ID (final int C_MediatedCommissionSettings_ID)
{
if (C_MediatedCommissionSettings_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettings_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettings_ID, C_MediatedCommissionSettings_ID);
}
@Override
public int getC_MediatedCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_MediatedCommissionSettings_ID);
}
@Override
public void setC_MediatedCommissionSettingsLine_ID (final int C_MediatedCommissionSettingsLine_ID)
{
if (C_MediatedCommissionSettingsLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettingsLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettingsLine_ID, C_MediatedCommissionSettingsLine_ID);
}
@Override
public int getC_MediatedCommissionSettingsLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_MediatedCommissionSettingsLine_ID);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
} | @Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_MediatedCommissionSettingsLine.java | 1 |
请完成以下Java代码 | public void onSnmpTransportListChanged() {
log.trace("SNMP transport list changed. Updating sessions");
List<DeviceId> deleted = new LinkedList<>();
for (DeviceId deviceId : allSnmpDevicesIds) {
if (balancingService.isManagedByCurrentTransport(deviceId.getId())) {
if (!sessions.containsKey(deviceId)) {
Device device = protoEntityService.getDeviceById(deviceId);
if (device != null) {
log.info("SNMP device {} is now managed by current transport node", deviceId);
establishDeviceSession(device);
} else {
deleted.add(deviceId);
}
}
} else {
Optional.ofNullable(sessions.get(deviceId))
.ifPresent(sessionContext -> {
log.info("SNMP session for device {} is not managed by current transport node anymore", deviceId);
destroyDeviceSession(sessionContext);
});
}
} | log.trace("Removing deleted SNMP devices: {}", deleted);
allSnmpDevicesIds.removeAll(deleted);
}
public Collection<DeviceSessionContext> getSessions() {
return sessions.values();
}
@PreDestroy
public void destroy() {
snmpExecutor.shutdown();
}
} | repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\SnmpTransportContext.java | 1 |
请完成以下Java代码 | private HUToReport getHuToReport()
{
return HUReportAwareViewRowAsHUToReport.of(getSingleSelectedRow());
}
private ReportResult printLabel()
{
final AdProcessId adProcessId = getLabelConfig()
.get()
.getPrintFormatProcessId();
final PInstanceRequest pinstanceRequest = createPInstanceRequest(adProcessId);
final PInstanceId pinstanceId = adPInstanceDAO.createADPinstanceAndADPInstancePara(pinstanceRequest);
final ProcessInfo jasperProcessInfo = ProcessInfo.builder()
.setCtx(getCtx())
.setProcessCalledFrom(ProcessCalledFrom.WebUI)
.setAD_Process_ID(adProcessId)
.setAD_PInstance(adPInstanceDAO.getById(pinstanceId))
.setReportLanguage(getProcessInfo().getReportLanguage())
.setJRDesiredOutputType(OutputType.PDF)
.build();
final ReportsClient reportsClient = ReportsClient.get(); | return reportsClient.report(jasperProcessInfo);
}
private PInstanceRequest createPInstanceRequest(@NonNull final AdProcessId adProcessId)
{
return PInstanceRequest.builder()
.processId(adProcessId)
.processParams(ImmutableList.of(
ProcessInfoParameter.of("AD_PInstance_ID", getPinstanceId())))
.build();
}
private String buildFilename()
{
final String instance = String.valueOf(getPinstanceId().getRepoId());
final String title = getProcessInfo().getTitle();
return Joiner.on("_").skipNulls().join(instance, title) + ".pdf";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_PrintFinishedGoodsLabel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookContrller {
Map<Long, Book> books = Collections.synchronizedMap(new HashMap<Long, Book>());
@ApiOperation(value="获取图书列表", notes="获取图书列表")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<Book> getBook() {
List<Book> book = new ArrayList<>(books.values());
return book;
}
@ApiOperation(value="创建图书", notes="创建图书")
@ApiImplicitParam(name = "book", value = "图书详细实体", required = true, dataType = "Book")
@RequestMapping(value="", method=RequestMethod.POST)
public String postBook(@RequestBody Book book) {
books.put(book.getId(), book);
return "success";
}
@ApiOperation(value="获图书细信息", notes="根据url的id来获取详细信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public Book getBook(@PathVariable Long id) {
return books.get(id);
}
@ApiOperation(value="更新信息", notes="根据url的id来指定更新图书信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "图书ID", required = true, dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "book", value = "图书实体book", required = true, dataType = "Book")
})
@RequestMapping(value="/{id}", method= RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody Book book) { | Book book1 = books.get(id);
book1.setName(book.getName());
book1.setPrice(book.getPrice());
books.put(id, book1);
return "success";
}
@ApiOperation(value="删除图书", notes="根据url的id来指定删除图书")
@ApiImplicitParam(name = "id", value = "图书ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
books.remove(id);
return "success";
}
@ApiIgnore//使用该注解忽略这个API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
} | repos\SpringBootLearning-master\springboot-swagger\src\main\java\com\forezp\controller\BookContrller.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<String> findHistoricTaskIdsForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
return dataManager.findHistoricTaskIdsForScopeIdsAndScopeType(scopeIds, scopeType);
}
@Override
public long findHistoricTaskInstanceCountByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstanceCountByQueryCriteria(historicTaskInstanceQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricTaskInstance> findHistoricTaskInstancesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstancesByQueryCriteria(historicTaskInstanceQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricTaskInstance> findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
return dataManager.findHistoricTaskInstancesAndRelatedEntitiesByQueryCriteria(historicTaskInstanceQuery);
}
@Override
public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstancesByNativeQuery(parameterMap);
}
@Override
public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findHistoricTaskInstanceCountByNativeQuery(parameterMap);
}
@Override
public void deleteHistoricTaskInstances(HistoricTaskInstanceQueryImpl historicTaskInstanceQuery) {
dataManager.deleteHistoricTaskInstances(historicTaskInstanceQuery);
}
@Override
public void bulkDeleteHistoricTaskInstancesForIds(Collection<String> taskIds) { | dataManager.bulkDeleteHistoricTaskInstancesForIds(taskIds);
}
@Override
public void deleteHistoricTaskInstancesForNonExistingProcessInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingProcessInstances();
}
@Override
public void deleteHistoricTaskInstancesForNonExistingCaseInstances() {
dataManager.deleteHistoricTaskInstancesForNonExistingCaseInstances();
}
public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() {
return dataManager;
}
public void setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) {
this.dataManager = historicTaskInstanceDataManager;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskInstanceEntityManagerImpl.java | 2 |
请完成以下Java代码 | public DocumentId getId()
{
return rowId;
}
@Override
public boolean isProcessed()
{
return isReconciled();
}
@Override
public DocumentPath getDocumentPath()
{
return null;
}
@Override
public Set<String> getFieldNames()
{
return values.getFieldNames();
} | @Override
public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues()
{
return values.get(this);
}
static DocumentId convertBankStatementLineIdToDocumentId(@NonNull final BankStatementLineId bankStatementLineId)
{
return DocumentId.of(bankStatementLineId);
}
static BankStatementLineId convertDocumentIdToBankStatementLineId(@NonNull final DocumentId rowId)
{
return rowId.toId(BankStatementLineId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\BankStatementLineRow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private BOMUpsertCamelRequest getBOMUpsertCamelRequest(@NonNull final JsonBOM jsonBOM)
{
if (jsonBOM.getBomLines().isEmpty())
{
throw new RuntimeCamelException("Missing lines!");
}
final List<JsonCreateBOMLine> bomLines = jsonBOM.getBomLines()
.stream()
.map(line -> getJsonCreateBOMLine(line, jsonBOM.getScrap()))
.collect(ImmutableList.toImmutableList());
final JsonBOMCreateRequest jsonBOMCreateRequest = JsonBOMCreateRequest.builder()
.uomCode(GRSSignumConstants.DEFAULT_UOM_CODE)
.productIdentifier(ExternalIdentifierFormat.asExternalIdentifier(jsonBOM.getProductId()))
.name(JsonBOMUtil.getName(jsonBOM))
.isActive(jsonBOM.isActive())
.validFrom(SystemTime.asInstant())
.bomLines(bomLines)
.build();
return getBOMUpsertCamelRequest(jsonBOMCreateRequest);
}
@NonNull
private static JsonCreateBOMLine getJsonCreateBOMLine(@NonNull final JsonBOMLine jsonBOMLine, @Nullable final BigDecimal scrap)
{
final JsonCreateBOMLine.JsonCreateBOMLineBuilder jsonCreateBOMLineBuilder = JsonCreateBOMLine.builder()
.productIdentifier(ExternalIdentifierFormat.asExternalIdentifier(jsonBOMLine.getProductId()))
.line(jsonBOMLine.getLine())
.isQtyPercentage(Boolean.TRUE) | .qtyBom(JsonQuantity.builder()
.qty(jsonBOMLine.getQtyBOM())
.uomCode(jsonBOMLine.getUom())
.build())
.scrap(scrap);
if (Check.isNotBlank(jsonBOMLine.getCountryCode()))
{
jsonCreateBOMLineBuilder.attributeSetInstance(JsonAttributeSetInstance.builder()
.attributeInstance(JsonAttributeInstance.builder()
.attributeCode(GRSSignumConstants.HERKUNFT_ATTRIBUTE_CODE)
.valueStr(jsonBOMLine.getCountryCode())
.build())
.build());
}
return jsonCreateBOMLineBuilder.build();
}
@NonNull
private static BOMUpsertCamelRequest getBOMUpsertCamelRequest(@NonNull final JsonBOMCreateRequest jsonRequest)
{
final TokenCredentials credentials = (TokenCredentials)SecurityContextHolder.getContext().getAuthentication().getCredentials();
return BOMUpsertCamelRequest.builder()
.jsonBOMCreateRequest(jsonRequest)
.orgCode(credentials.getOrgCode())
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\bom\processor\PushBOMProductsProcessor.java | 2 |
请完成以下Java代码 | protected void deleteAuthorizations(Resource resource, String resourceId) {
getAuthorizationManager().deleteAuthorizationsByResourceId(resource, resourceId);
}
protected void deleteAuthorizationsForUser(Resource resource, String resourceId, String userId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndUserId(resource, resourceId, userId);
}
protected void deleteAuthorizationsForGroup(Resource resource, String resourceId, String groupId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndGroupId(resource, resourceId, groupId);
}
public void saveDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
if(authorization.getId() == null) {
authorizationManager.insert(authorization);
} else {
authorizationManager.update(authorization);
}
}
return null; | }
});
}
}
public void deleteDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
authorizationManager.delete(authorization);
}
return null;
}
});
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String deletePassword(String name) {
try {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
credentialOperations.deleteByName(credentialName);
return "Credential:" + credentialName + " deleted successfully!";
} catch (Exception e) {
return "Error! Unable to delete credential";
}
}
public String getPassword(String name) {
try {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
return credentialOperations.getByName(credentialName, PasswordCredential.class)
.getValue()
.getPassword();
} catch (Exception e) {
return null;
}
}
public CredentialPermission addCredentialPermission(String name) {
SimpleCredentialName credentialName = new SimpleCredentialName(name);
try {
Permission permission = Permission.builder()
.app(UUID.randomUUID()
.toString())
.operations(Operation.READ, Operation.WRITE)
.user("u101") | .build();
CredentialPermission credentialPermission = permissionOperations.addPermissions(credentialName, permission);
return credentialPermission;
} catch (Exception e) {
return null;
}
}
public CredentialPermission getCredentialPermission(String name) {
try {
return permissionOperations.getPermissions(name);
} catch (Exception e) {
return null;
}
}
} | repos\tutorials-master\spring-credhub\src\main\java\com\baeldung\service\CredentialService.java | 2 |
请完成以下Java代码 | public String toJson()
{
if (idInt == NEW_ID)
{
return NEW_ID_STRING;
}
return String.valueOf(idInt);
}
@Override
public int hashCode()
{
return Objects.hash(idInt);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof IntDocumentId))
{
return false;
}
final IntDocumentId other = (IntDocumentId)obj;
return idInt == other.idInt;
}
@Override
public boolean isInt()
{
return true;
}
@Override
public int toInt()
{
return idInt;
}
@Override
public boolean isNew()
{
return idInt == NEW_ID;
}
@Override
public boolean isComposedKey()
{
return false;
}
@Override
public List<Object> toComposedKeyParts()
{
return ImmutableList.of(idInt);
}
}
private static final class StringDocumentId extends DocumentId
{
private final String idStr;
private StringDocumentId(final String idStr)
{
Check.assumeNotEmpty(idStr, "idStr is not empty");
this.idStr = idStr;
}
@Override
public String toJson()
{
return idStr;
}
@Override | public int hashCode()
{
return Objects.hash(idStr);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof StringDocumentId))
{
return false;
}
final StringDocumentId other = (StringDocumentId)obj;
return Objects.equals(idStr, other.idStr);
}
@Override
public boolean isInt()
{
return false;
}
@Override
public int toInt()
{
if (isComposedKey())
{
throw new AdempiereException("Composed keys cannot be converted to int: " + this);
}
else
{
throw new AdempiereException("String document IDs cannot be converted to int: " + this);
}
}
@Override
public boolean isNew()
{
return false;
}
@Override
public boolean isComposedKey()
{
return idStr.contains(COMPOSED_KEY_SEPARATOR);
}
@Override
public List<Object> toComposedKeyParts()
{
final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder();
COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add);
return composedKeyParts.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static void updateRecord(final I_SUMUP_Config record, SumUpConfig from)
{
record.setIsActive(from.isActive());
record.setApiKey(from.getApiKey());
record.setSUMUP_merchant_code(from.getMerchantCode().getAsString());
}
private static SumUpCardReader fromRecord(final I_SUMUP_CardReader record)
{
return SumUpCardReader.builder()
.name(record.getName())
.externalId(SumUpCardReaderExternalId.ofString(record.getExternalId()))
.isActive(record.isActive())
.build();
}
private static void updateRecord(final I_SUMUP_CardReader record, final SumUpCardReader from)
{
record.setName(from.getName());
record.setExternalId(from.getExternalId().getAsString());
record.setIsActive(from.isActive());
}
//
//
//
private static class SumUpConfigMap
{
public static SumUpConfigMap EMPTY = new SumUpConfigMap(ImmutableList.of());
private final ImmutableMap<SumUpConfigId, SumUpConfig> byId;
private final SumUpConfig defaultConfig;
private SumUpConfigMap(final List<SumUpConfig> list)
{
this.byId = Maps.uniqueIndex(list, SumUpConfig::getId);
final List<SumUpConfig> activeConfigs = list.stream()
.filter(SumUpConfig::isActive)
.collect(ImmutableList.toImmutableList());
this.defaultConfig = activeConfigs.size() == 1 ? activeConfigs.get(0) : null;
} | public SumUpConfig getById(final @NonNull SumUpConfigId id)
{
final SumUpConfig config = byId.get(id);
if (config == null)
{
throw new AdempiereException("No SumUp config found for " + id);
}
return config;
}
public SumUpConfig getDefault()
{
if (defaultConfig == null)
{
throw new AdempiereException("No default SumUp config found");
}
return defaultConfig;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\repository\SumUpConfigRepository.java | 2 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(BpmnEdge.class, BPMNDI_ELEMENT_BPMN_EDGE)
.namespaceUri(BPMNDI_NS)
.extendsType(LabeledEdge.class)
.instanceProvider(new ModelTypeInstanceProvider<BpmnEdge>() {
public BpmnEdge newInstance(ModelTypeInstanceContext instanceContext) {
return new BpmnEdgeImpl(instanceContext);
}
});
bpmnElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_BPMN_ELEMENT)
.qNameAttributeReference(BaseElement.class)
.build();
sourceElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_SOURCE_ELEMENT)
.qNameAttributeReference(DiagramElement.class)
.build();
targetElementAttribute = typeBuilder.stringAttribute(BPMNDI_ATTRIBUTE_TARGET_ELEMENT)
.qNameAttributeReference(DiagramElement.class)
.build();
messageVisibleKindAttribute = typeBuilder.enumAttribute(BPMNDI_ATTRIBUTE_MESSAGE_VISIBLE_KIND, MessageVisibleKind.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
bpmnLabelChild = sequenceBuilder.element(BpmnLabel.class)
.build();
typeBuilder.build();
}
public BpmnEdgeImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public BaseElement getBpmnElement() {
return bpmnElementAttribute.getReferenceTargetElement(this);
}
public void setBpmnElement(BaseElement bpmnElement) {
bpmnElementAttribute.setReferenceTargetElement(this, bpmnElement);
}
public DiagramElement getSourceElement() {
return sourceElementAttribute.getReferenceTargetElement(this); | }
public void setSourceElement(DiagramElement sourceElement) {
sourceElementAttribute.setReferenceTargetElement(this, sourceElement);
}
public DiagramElement getTargetElement() {
return targetElementAttribute.getReferenceTargetElement(this);
}
public void setTargetElement(DiagramElement targetElement) {
targetElementAttribute.setReferenceTargetElement(this, targetElement);
}
public MessageVisibleKind getMessageVisibleKind() {
return messageVisibleKindAttribute.getValue(this);
}
public void setMessageVisibleKind(MessageVisibleKind messageVisibleKind) {
messageVisibleKindAttribute.setValue(this, messageVisibleKind);
}
public BpmnLabel getBpmnLabel() {
return bpmnLabelChild.getChild(this);
}
public void setBpmnLabel(BpmnLabel bpmnLabel) {
bpmnLabelChild.setChild(this, bpmnLabel);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\bpmndi\BpmnEdgeImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public Boolean getWithoutProcessInstanceId() {
return withoutProcessInstanceId;
}
public void setWithoutProcessInstanceId(Boolean withoutProcessInstanceId) {
this.withoutProcessInstanceId = withoutProcessInstanceId;
}
public String getCandidateOrAssigned() {
return candidateOrAssigned;
}
public void setCandidateOrAssigned(String candidateOrAssigned) {
this.candidateOrAssigned = candidateOrAssigned;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public List<String> getCategoryIn() {
return categoryIn;
}
public void setCategoryIn(List<String> categoryIn) {
this.categoryIn = categoryIn;
}
public List<String> getCategoryNotIn() {
return categoryNotIn;
} | public void setCategoryNotIn(List<String> categoryNotIn) {
this.categoryNotIn = categoryNotIn;
}
public Boolean getWithoutCategory() {
return withoutCategory;
}
public void setWithoutCategory(Boolean withoutCategory) {
this.withoutCategory = withoutCategory;
}
public String getRootScopeId() {
return rootScopeId;
}
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
public void setParentScopeId(String parentScopeId) {
this.parentScopeId = parentScopeId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskQueryRequest.java | 2 |
请完成以下Java代码 | public class GzipUtils {
/**
* Gzip a string.
*
* @param text
* @return
* @throws Exception
*/
public static byte[] compress(String text) throws Exception {
return GzipUtils.compress(text.getBytes(StandardCharsets.UTF_8));
}
/**
* Gzip a byte array.
*
* @param body
* @return
* @throws IOException
*/
public static byte[] compress(byte[] body) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {
gzipOutputStream.write(body);
} | return baos.toByteArray();
}
/**
* Decompress a Gzipped byte array to a String.
*
* @param body
* @return
* @throws IOException
*/
public static String decompress(byte[] body) throws IOException {
try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(body))) {
return IOUtils.toString(gzipInputStream, StandardCharsets.UTF_8);
}
}
} | repos\tutorials-master\spring-web-modules\spring-resttemplate-3\src\main\java\com\baeldung\compress\GzipUtils.java | 1 |
请完成以下Java代码 | public List<String> getParameterNames() {
return parameterNames;
}
@Override
public void appendStructure(StringBuilder builder, Bindings bindings) {
if (parameterNames.size() == 1) {
builder.append(parameterNames.get(0));
} else {
builder.append("(");
for (int i = 0; i < parameterNames.size(); i++) {
if (i > 0) {
builder.append(", ");
}
builder.append(parameterNames.get(i));
}
builder.append(")");
}
}
@Override
public Object eval(Bindings bindings, ELContext context) { | // Lambda parameters don't evaluate to a value
return parameterNames;
}
@Override
public int getCardinality() {
return 0;
}
@Override
public AstNode getChild(int i) {
return null;
}
@Override
public String toString() {
return parameterNames.size() == 1 ? parameterNames.get(0) : parameterNames.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstLambdaParameters.java | 1 |
请完成以下Java代码 | protected void prepare()
{
for (ProcessInfoParameter para : getParametersAsArray())
{
String name = para.getParameterName();
if (para.getParameter() == null)
{
// do nothing
}
else if (name.equals("TableName"))
{
p_TableName = (String)para.getParameter();
}
else if (name.equals("WhereClause"))
{
p_WhereClause = (String)para.getParameter();
}
else if (name.equals("IsTest"))
{
p_IsTest = para.getParameterAsBoolean();
}
else
{
log.debug("Unknown Parameter: " + name);
}
}
}
@Override
protected String doIt() throws Exception
{
Check.assume(p_WhereClause != null, "WhereClause is not null");
final long startTime = System.currentTimeMillis();
final ISweepTableBL sweepTableBL = Services.get(ISweepTableBL.class);
// clean log data
db_delete_logs();
DB.saveConstraints();
final String trxName = get_TrxName();
try
{
DB.getConstraints().setTrxTimeoutSecs(-1, false);
// workaround, the API should do | Services.get(IOpenTrxBL.class).onTimeOutChange(Trx.get(trxName, false));
// final int targetClientId = 100;
final int targetClientId = -1;
final boolean result = sweepTableBL.sweepTable(getCtx(), p_TableName, p_WhereClause, targetClientId, this, trxName);
addLog("Finished after " + TimeUtil.formatElapsed(System.currentTimeMillis() - startTime) + " (Everything deleted: " + result + ")");
//
// Do a second run, just for safety and to check the results
{
addLog("--------------- SECOND RUN ------------------------------------------");
final long startTime2 = System.currentTimeMillis();
final boolean result2 = sweepTableBL.sweepTable(getCtx(), p_TableName, p_WhereClause, targetClientId, this, trxName);
addLog("Finished(2) after " + TimeUtil.formatElapsed(System.currentTimeMillis() - startTime2) + " (Everything deleted: " + result2 + ")");
if (result2 == false)
{
// NOTE: because in de.metas.adempiere.service.impl.SweepTableBL.retrieveRecordIds(RuntimeContext,
// String, String, int)
// we are setting references to NULL, is absolutely mandatory to make sure that everything was
// deleted, because else we will leave the database in a inconsistent and irreversible state
throw new AdempiereException("There is remaining data! ROLLBACK!");
}
}
if (p_IsTest)
{
throw new AdempiereException("ROLLBACK!");
}
return "Everything could be deleted: " + result;
}
finally
{
DB.restoreConstraints();
// workaround, the API should do this automatically
Services.get(IOpenTrxBL.class).onTimeOutChange(Trx.get(trxName, false));
}
}
private int db_delete_logs()
{
final String sql = "select db_delete_logs(?, ?)";
final int adSessionId = Env.getAD_Session_ID(getCtx());
final int no = DB.getSQLValueEx(get_TrxName(), sql, adSessionId, getPinstanceId());
addLog("Deleted log data: " + no + " records");
return no;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\SweepTable.java | 1 |
请完成以下Java代码 | public int getParent_M_HU_Trx_Line_ID()
{
return Parent_M_HU_Trx_Line_ID;
}
@Override
public void setParent_M_HU_Trx_Line_ID(final int parent_M_HU_Trx_Line_ID)
{
Parent_M_HU_Trx_Line_ID = parent_M_HU_Trx_Line_ID;
}
@Override
public void setM_HU_Item_ID(final int Ref_HU_Item_ID)
{
this.Ref_HU_Item_ID = Ref_HU_Item_ID;
}
@Override
public int getM_HU_Item_ID()
{
return Ref_HU_Item_ID;
}
@Override
public int getAD_Table_ID()
{
return AD_Table_ID;
}
@Override
public void setAD_Table_ID(final int aD_Table_ID)
{
AD_Table_ID = aD_Table_ID;
} | @Override
public int getRecord_ID()
{
return Record_ID;
}
@Override
public void setRecord_ID(final int record_ID)
{
Record_ID = record_ID;
}
@Override
public void setM_HU_ID(int m_hu_ID)
{
M_HU_ID = m_hu_ID;
}
@Override
public int getM_HU_ID()
{
return M_HU_ID;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxQuery.java | 1 |
请完成以下Java代码 | public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPriceStd (final BigDecimal PriceStd)
{
set_Value (COLUMNNAME_PriceStd, PriceStd);
}
@Override
public BigDecimal getPriceStd()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PriceStd);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPricingSystem_Value (final @Nullable java.lang.String PricingSystem_Value)
{
set_Value (COLUMNNAME_PricingSystem_Value, PricingSystem_Value);
}
@Override
public java.lang.String getPricingSystem_Value()
{
return get_ValueAsString(COLUMNNAME_PricingSystem_Value);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProductValue (final java.lang.String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
@Override
public java.lang.String getProductValue() | {
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setUOM (final java.lang.String UOM)
{
set_Value (COLUMNNAME_UOM, UOM);
}
@Override
public java.lang.String getUOM()
{
return get_ValueAsString(COLUMNNAME_UOM);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Campaign_Price.java | 1 |
请完成以下Java代码 | public Map<String, Object> deserializeUsingGson(String jsonString) {
try {
Type type = new TypeToken<Map<String, Object>>() {}.getType();
return gson.fromJson(jsonString, type);
} catch (Exception e) {
throw new RuntimeException("Gson deserialization failed: " + e.getMessage(), e);
}
}
public Map<String, Object> deserializeUsingOrgJson(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Map<String, Object> result = new HashMap<>();
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
value = ((JSONArray) value).toList();
} else if (value instanceof JSONObject) {
value = ((JSONObject) value).toMap();
}
result.put(key, value);
}
return result;
} catch (Exception e) {
throw new RuntimeException("org.json deserialization failed: " + e.getMessage(), e);
}
}
public Map<String, Object> deserializeUsingJsonP(String jsonString) {
try (JsonReader reader = Json.createReader(new StringReader(jsonString))) {
JsonObject jsonObject = reader.readObject();
return convertJsonToMap(jsonObject);
} catch (Exception e) {
throw new RuntimeException("JSON-P deserialization failed: " + e.getMessage(), e);
}
}
private Map<String, Object> convertJsonToMap(JsonObject jsonObject) {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, JsonValue> entry : jsonObject.entrySet()) {
String key = entry.getKey();
JsonValue value = entry.getValue();
result.put(key, convertJsonValue(value));
} | return result;
}
private Object convertJsonValue(JsonValue jsonValue) {
switch (jsonValue.getValueType()) {
case STRING:
return ((JsonString) jsonValue).getString();
case NUMBER:
JsonNumber num = (JsonNumber) jsonValue;
return num.isIntegral() ? num.longValue() : num.doubleValue();
case TRUE:
return true;
case FALSE:
return false;
case NULL:
return null;
case ARRAY:
return convertJsonArray(( jakarta.json.JsonArray) jsonValue);
case OBJECT:
return convertJsonToMap((JsonObject) jsonValue);
default:
return jsonValue.toString();
}
}
private List<Object> convertJsonArray( jakarta.json.JsonArray jsonArray) {
List<Object> list = new ArrayList<>();
for (JsonValue value : jsonArray) {
list.add(convertJsonValue(value));
}
return list;
}
} | repos\tutorials-master\json-modules\json-3\src\main\java\com\baeldung\jsondeserialization\JsonDeserializerService.java | 1 |
请完成以下Java代码 | public class Node<T> {
T data;
Node<T> next;
public static <T> Node<T> createNewNode(T data, Node<T> next) {
Node<T> node = new Node<T>();
node.data = data;
node.next = next;
return node;
}
public static <T> void traverseList(Node<T> root) {
if (root == null) {
return;
}
Node<T> node = root;
while (node != null) {
System.out.println(node.data);
node = node.next;
} | }
public static <T> Node<T> getTail(Node<T> root) {
if (root == null) {
return null;
}
Node<T> node = root;
while (node.next != null) {
node = node.next;
}
return node;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\linkedlist\Node.java | 1 |
请完成以下Java代码 | public class ProcessDeployedEventProducer extends AbstractActivitiSmartLifeCycle {
private RepositoryService repositoryService;
private APIProcessDefinitionConverter converter;
private List<ProcessRuntimeEventListener<ProcessDeployedEvent>> listeners;
private ApplicationEventPublisher eventPublisher;
public ProcessDeployedEventProducer(
RepositoryService repositoryService,
APIProcessDefinitionConverter converter,
List<ProcessRuntimeEventListener<ProcessDeployedEvent>> listeners,
ApplicationEventPublisher eventPublisher
) {
this.repositoryService = repositoryService;
this.converter = converter;
this.listeners = listeners;
this.eventPublisher = eventPublisher;
}
@Override
public void doStart() {
List<ProcessDefinition> processDefinitions = converter.from(
repositoryService.createProcessDefinitionQuery().latestVersion().list()
);
List<ProcessDeployedEvent> processDeployedEvents = new ArrayList<>();
for (ProcessDefinition processDefinition : processDefinitions) {
try (InputStream inputStream = repositoryService.getProcessModel(processDefinition.getId())) {
String xmlModel = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
ProcessDeployedEventImpl processDeployedEvent = new ProcessDeployedEventImpl(
processDefinition,
xmlModel
);
processDeployedEvents.add(processDeployedEvent); | for (ProcessRuntimeEventListener<ProcessDeployedEvent> listener : listeners) {
listener.onEvent(processDeployedEvent);
}
} catch (IOException e) {
throw new ActivitiException(
"Error occurred while getting process model '" + processDefinition.getId() + "' : ",
e
);
}
}
if (!processDeployedEvents.isEmpty()) {
eventPublisher.publishEvent(new ProcessDeployedEvents(processDeployedEvents));
}
}
@Override
public void doStop() {
// nothing
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\ProcessDeployedEventProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
} | @Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
} | repos\springBoot-master\springboot-SpringSecurity1\src\main\java\com\us\example\service\MyFilterSecurityInterceptor.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.