instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Message_ID (final int AD_Message_ID)
{
if (AD_Message_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, AD_Message_ID);
}
@Override
public int getAD_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Message_ID);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setErrorCode (final @Nullable java.lang.String ErrorCode)
{
set_Value (COLUMNNAME_ErrorCode, ErrorCode);
}
@Override
public java.lang.String getErrorCode()
{
return get_ValueAsString(COLUMNNAME_ErrorCode);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setMsgTip (final @Nullable java.lang.String MsgTip)
{
set_Value (COLUMNNAME_MsgTip, MsgTip);
}
@Override
public java.lang.String getMsgTip()
{
return get_ValueAsString(COLUMNNAME_MsgTip);
}
/** | * MsgType AD_Reference_ID=103
* Reference name: AD_Message Type
*/
public static final int MSGTYPE_AD_Reference_ID=103;
/** Fehler = E */
public static final String MSGTYPE_Fehler = "E";
/** Information = I */
public static final String MSGTYPE_Information = "I";
/** Menü = M */
public static final String MSGTYPE_Menue = "M";
@Override
public void setMsgType (final java.lang.String MsgType)
{
set_Value (COLUMNNAME_MsgType, MsgType);
}
@Override
public java.lang.String getMsgType()
{
return get_ValueAsString(COLUMNNAME_MsgType);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message.java | 1 |
请完成以下Java代码 | public boolean isError() { return isAborted() || isTerminated(); }
/**
* @return true if state is Aborted (Environment/Setup issue)
*/
public boolean isAborted()
{
return Aborted.equals(this);
}
/**
* @return true if state is Terminated (Execution issue)
*/
public boolean isTerminated()
{
return Terminated.equals(this);
}
/**
* Get New State Options based on current State
*/
private WFState[] getNewStateOptions()
{
if (isNotStarted())
return new WFState[] { Running, Aborted, Terminated };
else if (isRunning())
return new WFState[] { Suspended, Completed, Aborted, Terminated };
else if (isSuspended())
return new WFState[] { Running, Aborted, Terminated };
else
return new WFState[] {};
}
/**
* Is the new State valid based on current state
*
* @param newState new state
* @return true valid new state
*/
public boolean isValidNewState(final WFState newState)
{
final WFState[] options = getNewStateOptions();
for (final WFState option : options)
{
if (option.equals(newState))
return true;
}
return false;
}
/**
* @return true if the action is valid based on current state
*/
public boolean isValidAction(final WFAction action)
{
final WFAction[] options = getActionOptions(); | for (final WFAction option : options)
{
if (option.equals(action))
{
return true;
}
}
return false;
}
/**
* @return valid actions based on current State
*/
private WFAction[] getActionOptions()
{
if (isNotStarted())
return new WFAction[] { WFAction.Start, WFAction.Abort, WFAction.Terminate };
if (isRunning())
return new WFAction[] { WFAction.Suspend, WFAction.Complete, WFAction.Abort, WFAction.Terminate };
if (isSuspended())
return new WFAction[] { WFAction.Resume, WFAction.Abort, WFAction.Terminate };
else
return new WFAction[] {};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\WFState.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ReceiptTypeEnum getReceiptTypeEnum() {
return receiptTypeEnum;
}
public void setReceiptTypeEnum(ReceiptTypeEnum receiptTypeEnum) {
this.receiptTypeEnum = receiptTypeEnum;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTaxpayerNo() {
return taxpayerNo;
} | public void setTaxpayerNo(String taxpayerNo) {
this.taxpayerNo = taxpayerNo;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "ReceiptEntity{" +
"id='" + id + '\'' +
", receiptTypeEnum=" + receiptTypeEnum +
", title='" + title + '\'' +
", taxpayerNo='" + taxpayerNo + '\'' +
", content='" + content + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\ReceiptEntity.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!isHUEditorView())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view");
}
if (!getSelectedRowIds().isSingleDocumentId())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No (single) row selected");
}
final HUToReport hu = HUReportAwareViewRowAsHUToReport.of(getSingleSelectedRow());
if (hu == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No (single) HU selected");
}
return ProcessPreconditionsResolution.accept();
}
@Override | @RunOutOfTrx
protected String doIt()
{
final HUToReport hu = HUReportAwareViewRowAsHUToReport.of(getSingleSelectedRow());
huLabelService.print(HULabelPrintRequest.builder()
.sourceDocType(HULabelSourceDocType.MaterialReceipt)
.hu(hu)
.printCopiesOverride(PrintCopies.ofInt(p_copies))
.failOnMissingLabelConfig(true)
.build());
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_PrintReceiptLabel.java | 1 |
请完成以下Java代码 | private String getUnqualifiedName(String name) {
if (!name.contains(".")) {
return name;
}
return name.substring(name.lastIndexOf(".") + 1);
}
private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) {
if (name == null || !name.contains(".")) {
return false;
}
String packageName = name.substring(0, name.lastIndexOf('.'));
return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName);
}
static class GroovyFormattingOptions implements FormattingOptions { | @Override
public String statementSeparator() {
return "";
}
@Override
public CodeBlock arrayOf(CodeBlock... values) {
return CodeBlock.of("[ $L ]", CodeBlock.join(Arrays.asList(values), ", "));
}
@Override
public CodeBlock classReference(ClassName className) {
return CodeBlock.of("$T", className);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovySourceCodeWriter.java | 1 |
请完成以下Java代码 | protected boolean existsMembership(String userId, String groupId) {
Map<String, String> key = new HashMap<>();
key.put("userId", userId);
key.put("groupId", groupId);
return ((Long) getDbEntityManager().selectOne("selectMembershipCount", key)) > 0;
}
protected boolean existsTenantMembership(String tenantId, String userId, String groupId) {
Map<String, String> key = new HashMap<>();
key.put("tenantId", tenantId);
if (userId != null) {
key.put("userId", userId);
}
if (groupId != null) {
key.put("groupId", groupId);
}
return ((Long) getDbEntityManager().selectOne("selectTenantMembershipCount", key)) > 0;
}
//authorizations //////////////////////////////////////////////////// | @Override
protected void configureQuery(@SuppressWarnings("rawtypes") AbstractQuery query, Resource resource) {
Context.getCommandContext()
.getAuthorizationManager()
.configureQuery(query, resource);
}
@Override
protected void checkAuthorization(Permission permission, Resource resource, String resourceId) {
Context.getCommandContext()
.getAuthorizationManager()
.checkAuthorization(permission, resource, resourceId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\identity\db\DbReadOnlyIdentityServiceProvider.java | 1 |
请完成以下Java代码 | private static boolean isGatewayRequest(HttpServletRequest request) {
return request.getAttribute(MvcUtils.GATEWAY_ROUTE_ID_ATTR) != null
|| request.getAttribute(MvcUtils.GATEWAY_REQUEST_URL_ATTR) != null;
}
/**
* StandardMultipartHttpServletRequest wrapper that will not parse multipart if it is
* a gateway request. A gateway request has certain request attributes set.
*/
static class GatewayMultipartHttpServletRequest extends StandardMultipartHttpServletRequest {
GatewayMultipartHttpServletRequest(HttpServletRequest request) {
super(request, true);
}
@Override
protected void initializeMultipart() { | if (!isGatewayRequest(getRequest())) {
super.initializeMultipart();
}
}
@Override
public Map<String, String[]> getParameterMap() {
if (isGatewayRequest(getRequest())) {
return Collections.emptyMap();
}
return super.getParameterMap();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayMvcMultipartResolver.java | 1 |
请完成以下Java代码 | public int getAD_Element_Link_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Element_Link_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Field getAD_Field() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Field_ID, org.compiere.model.I_AD_Field.class);
}
@Override
public void setAD_Field(org.compiere.model.I_AD_Field AD_Field)
{
set_ValueFromPO(COLUMNNAME_AD_Field_ID, org.compiere.model.I_AD_Field.class, AD_Field);
}
/** Set Feld.
@param AD_Field_ID
Ein Feld einer Datenbanktabelle
*/
@Override
public void setAD_Field_ID (int AD_Field_ID)
{
if (AD_Field_ID < 1)
set_Value (COLUMNNAME_AD_Field_ID, null);
else
set_Value (COLUMNNAME_AD_Field_ID, Integer.valueOf(AD_Field_ID));
}
/** Get Feld.
@return Ein Feld einer Datenbanktabelle
*/
@Override
public int getAD_Field_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Field_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Tab getAD_Tab() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class);
}
@Override
public void setAD_Tab(org.compiere.model.I_AD_Tab AD_Tab)
{
set_ValueFromPO(COLUMNNAME_AD_Tab_ID, org.compiere.model.I_AD_Tab.class, AD_Tab);
}
/** Set Register.
@param AD_Tab_ID
Register auf einem Fenster
*/
@Override
public void setAD_Tab_ID (int AD_Tab_ID)
{
if (AD_Tab_ID < 1)
set_Value (COLUMNNAME_AD_Tab_ID, null);
else
set_Value (COLUMNNAME_AD_Tab_ID, Integer.valueOf(AD_Tab_ID));
}
/** Get Register.
@return Register auf einem Fenster
*/
@Override
public int getAD_Tab_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Eingabe- oder Anzeige-Fenster
*/
@Override
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Fenster.
@return Eingabe- oder Anzeige-Fenster
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_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_Element_Link.java | 1 |
请完成以下Java代码 | public void setGTIN_PackingMaterial (final @Nullable java.lang.String GTIN_PackingMaterial)
{
set_Value (COLUMNNAME_GTIN_PackingMaterial, GTIN_PackingMaterial);
}
@Override
public java.lang.String getGTIN_PackingMaterial()
{
return get_ValueAsString(COLUMNNAME_GTIN_PackingMaterial);
}
@Override
public void setIPA_SSCC18 (final java.lang.String IPA_SSCC18)
{
set_Value (COLUMNNAME_IPA_SSCC18, IPA_SSCC18);
}
@Override
public java.lang.String getIPA_SSCC18()
{
return get_ValueAsString(COLUMNNAME_IPA_SSCC18);
}
@Override
public void setIsManual_IPA_SSCC18 (final boolean IsManual_IPA_SSCC18)
{
set_Value (COLUMNNAME_IsManual_IPA_SSCC18, IsManual_IPA_SSCC18);
}
@Override
public boolean isManual_IPA_SSCC18()
{
return get_ValueAsBoolean(COLUMNNAME_IsManual_IPA_SSCC18);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_Value (COLUMNNAME_M_HU_ID, null);
else
set_Value (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_PackagingCode_ID (final int M_HU_PackagingCode_ID)
{
if (M_HU_PackagingCode_ID < 1)
set_Value (COLUMNNAME_M_HU_PackagingCode_ID, null);
else
set_Value (COLUMNNAME_M_HU_PackagingCode_ID, M_HU_PackagingCode_ID);
}
@Override
public int getM_HU_PackagingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID);
} | @Override
public void setM_HU_PackagingCode_Text (final @Nullable java.lang.String M_HU_PackagingCode_Text)
{
throw new IllegalArgumentException ("M_HU_PackagingCode_Text is virtual column"); }
@Override
public java.lang.String getM_HU_PackagingCode_Text()
{
return get_ValueAsString(COLUMNNAME_M_HU_PackagingCode_Text);
}
@Override
public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
throw new IllegalArgumentException ("M_InOut_ID is virtual column"); }
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@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.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SimpleWebAuthServiceImpl implements AuthService<HttpServletRequest> {
public static final String WEB_SESSION_KEY = "session_sentinel_admin";
@Override
public AuthUser getAuthUser(HttpServletRequest request) {
HttpSession session = request.getSession();
Object sentinelUserObj = session.getAttribute(SimpleWebAuthServiceImpl.WEB_SESSION_KEY);
if (sentinelUserObj != null && sentinelUserObj instanceof AuthUser) {
return (AuthUser) sentinelUserObj;
}
return null;
}
public static final class SimpleWebAuthUserImpl implements AuthUser {
private String username;
public SimpleWebAuthUserImpl(String username) {
this.username = username;
}
@Override
public boolean authTarget(String target, PrivilegeType privilegeType) {
return true;
} | @Override
public boolean isSuperUser() {
return true;
}
@Override
public String getNickName() {
return username;
}
@Override
public String getLoginName() {
return username;
}
@Override
public String getId() {
return username;
}
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\auth\SimpleWebAuthServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public Credential getCredential() {
return this.credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public List<String> getBaseDn() {
return this.baseDn;
}
public void setBaseDn(List<String> baseDn) {
this.baseDn = baseDn;
}
public String getLdif() {
return this.ldif;
}
public void setLdif(String ldif) {
this.ldif = ldif;
}
public Validation getValidation() {
return this.validation;
}
public static class Credential {
/**
* Embedded LDAP username.
*/
private @Nullable String username;
/**
* Embedded LDAP password.
*/
private @Nullable String password;
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
boolean isAvailable() {
return StringUtils.hasText(this.username) && StringUtils.hasText(this.password);
}
} | public static class Validation {
/**
* Whether to enable LDAP schema validation.
*/
private boolean enabled = true;
/**
* Path to the custom schema.
*/
private @Nullable Resource schema;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable Resource getSchema() {
return this.schema;
}
public void setSchema(@Nullable Resource schema) {
this.schema = schema;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-ldap\src\main\java\org\springframework\boot\ldap\autoconfigure\embedded\EmbeddedLdapProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void run(ApplicationArguments args) throws Exception {
String[] jobArguments = args.getNonOptionArgs().toArray(new String[0]);
run(jobArguments);
}
public void run(String... args) throws JobExecutionException {
logger.info("Running default command line with: " + Arrays.asList(args));
Properties properties = StringUtils.splitArrayElementsIntoProperties(args, "=");
launchJobFromProperties((properties != null) ? properties : new Properties());
}
protected void launchJobFromProperties(Properties properties) throws JobExecutionException {
JobParameters jobParameters = this.converter.getJobParameters(properties);
executeLocalJobs(jobParameters);
executeRegisteredJobs(jobParameters);
}
private boolean isLocalJob(String jobName) {
return this.jobs.stream().anyMatch((job) -> job.getName().equals(jobName));
}
private boolean isRegisteredJob(String jobName) {
return this.jobRegistry != null && this.jobRegistry.getJobNames().contains(jobName);
}
private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException {
for (Job job : this.jobs) {
if (StringUtils.hasText(this.jobName)) {
if (!this.jobName.equals(job.getName())) {
logger.debug(LogMessage.format("Skipped job: %s", job.getName()));
continue;
}
}
execute(job, jobParameters);
}
} | private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException {
if (this.jobRegistry != null && StringUtils.hasText(this.jobName)) {
if (!isLocalJob(this.jobName)) {
Job job = this.jobRegistry.getJob(this.jobName);
Assert.notNull(job, () -> "No job found with name '" + this.jobName + "'");
execute(job, jobParameters);
}
}
}
protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException, InvalidJobParametersException {
JobExecution execution = this.jobOperator.start(job, jobParameters);
if (this.publisher != null) {
this.publisher.publishEvent(new JobExecutionEvent(execution));
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-batch\src\main\java\org\springframework\boot\batch\autoconfigure\JobLauncherApplicationRunner.java | 2 |
请完成以下Java代码 | public SearchResult next() throws NamingException {
return enumeration.next();
}
@Override
public boolean hasMore() throws NamingException {
return enumeration.hasMore();
}
@Override
public boolean hasMoreElements() {
return enumeration.hasMoreElements();
}
@Override
public SearchResult nextElement() { | return enumeration.nextElement();
}
@Override
public void close() {
try {
if (enumeration != null) {
enumeration.close();
}
} catch (Exception e) {
// ignore silently
}
}
} | repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapSearchResults.java | 1 |
请完成以下Java代码 | public static JSONMenuNodeType ofNullable(@Nullable final MenuNodeType type)
{
if (type == null)
{
return null;
}
final JSONMenuNodeType jsonType = type2json.get(type);
if (jsonType == null)
{
throw new AdempiereException("Cannot convert " + type + " to " + JSONMenuNodeType.class);
}
return jsonType;
}
private static final BiMap<MenuNodeType, JSONMenuNodeType> type2json = ImmutableBiMap.<MenuNodeType, JSONMenuNodeType>builder()
.put(MenuNodeType.Group, group)
.put(MenuNodeType.Window, window) | .put(MenuNodeType.NewRecord, newRecord)
.put(MenuNodeType.Process, process)
.put(MenuNodeType.Report, report)
.put(MenuNodeType.Board, board)
.build();
public final MenuNodeType toMenuNodeType()
{
final MenuNodeType type = type2json.inverse().get(this);
if (type == null)
{
throw new AdempiereException("Cannot convert " + type + " to " + MenuNodeType.class);
}
return type;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\datatypes\json\JSONMenuNodeType.java | 1 |
请完成以下Java代码 | public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
System.out.println("方法的返回值 : " + ret);
}
//后置异常通知
@AfterThrowing("webLog()")
public void throwss(JoinPoint jp){
System.out.println("方法异常时执行.....");
}
//后置最终通知,final增强,不管是抛出异常或者正常退出都会执行
@After("webLog()")
public void after(JoinPoint jp){
System.out.println("方法最后执行....."); | }
//环绕通知,环绕增强,相当于MethodInterceptor
@Around("webLog()")
public Object arround(ProceedingJoinPoint pjp) {
System.out.println("方法环绕start.....");
try {
Object o = pjp.proceed();
System.out.println("方法环绕proceed,结果是 :" + o);
return o;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
} | repos\SpringBootBucket-master\springboot-aop\src\main\java\com\xncoding\aop\aspect\LogAspect.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getProdState() {
return prodState;
}
public void setProdState(Integer prodState) {
this.prodState = prodState;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getCompanyEntityID() {
return companyEntityID;
}
public void setCompanyEntityID(String companyEntityID) {
this.companyEntityID = companyEntityID;
}
@Override
public String toString() {
return "ProdInsertReq{" + | "id='" + id + '\'' +
", prodName='" + prodName + '\'' +
", marketPrice='" + marketPrice + '\'' +
", shopPrice='" + shopPrice + '\'' +
", stock=" + stock +
", sales=" + sales +
", weight='" + weight + '\'' +
", topCateEntityID='" + topCateEntityID + '\'' +
", subCategEntityID='" + subCategEntityID + '\'' +
", brandEntityID='" + brandEntityID + '\'' +
", prodState=" + prodState +
", content='" + content + '\'' +
", companyEntityID='" + companyEntityID + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\product\ProdInsertReq.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
org.springframework.messaging.converter.MappingJackson2MessageConverter converter = new org.springframework.messaging.converter.MappingJackson2MessageConverter(
this.objectMapper);
DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
converter.setContentTypeResolver(resolver);
messageConverters.add(converter);
return false;
}
}
static class NoJacksonOrJackson2Preferred extends AnyNestedCondition {
NoJacksonOrJackson2Preferred() {
super(ConfigurationPhase.PARSE_CONFIGURATION); | }
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
static class NoJackson {
}
@ConditionalOnProperty(name = "spring.websocket.messaging.preferred-json-mapper", havingValue = "jackson2")
static class Jackson2Preferred {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-websocket\src\main\java\org\springframework\boot\websocket\autoconfigure\servlet\WebSocketMessagingAutoConfiguration.java | 2 |
请完成以下Java代码 | public static EndpointId of(Environment environment, String value) {
Assert.notNull(environment, "'environment' must not be null");
return new EndpointId(migrateLegacyId(environment, value));
}
private static String migrateLegacyId(Environment environment, String value) {
if (environment.getProperty(MIGRATE_LEGACY_NAMES_PROPERTY, Boolean.class, false)) {
return value.replaceAll("[-.]+", "");
}
return value;
}
/**
* Factory method to create a new {@link EndpointId} from a property value. More
* lenient than {@link #of(String)} to allow for common "relaxed" property variants.
* @param value the property value to convert
* @return an {@link EndpointId} instance | */
public static EndpointId fromPropertyValue(String value) {
return new EndpointId(value.replace("-", ""));
}
static void resetLoggedWarnings() {
loggedWarnings.clear();
}
private static void logWarning(String value) {
if (logger.isWarnEnabled() && loggedWarnings.add(value)) {
logger.warn("Endpoint ID '" + value + "' contains invalid characters, please migrate to a valid format.");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\EndpointId.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Escalation.class, BPMN_ELEMENT_ESCALATION)
.namespaceUri(BPMN20_NS)
.extendsType(RootElement.class)
.instanceProvider(new ModelTypeInstanceProvider<Escalation>() {
public Escalation newInstance(ModelTypeInstanceContext instanceContext) {
return new EscalationImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
escalationCodeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ESCALATION_CODE)
.build();
structureRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_STRUCTURE_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
typeBuilder.build();
}
public EscalationImpl(ModelTypeInstanceContext context) {
super(context);
} | public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public String getEscalationCode() {
return escalationCodeAttribute.getValue(this);
}
public void setEscalationCode(String escalationCode) {
escalationCodeAttribute.setValue(this, escalationCode);
}
public ItemDefinition getStructure() {
return structureRefAttribute.getReferenceTargetElement(this);
}
public void setStructure(ItemDefinition structure) {
structureRefAttribute.setReferenceTargetElement(this, structure);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\EscalationImpl.java | 1 |
请完成以下Java代码 | public Optional<AttributeKvEntry> getServerPrivateAttribute(String attribute) {
return Optional.ofNullable(serverPrivateAttributesMap.get(attribute));
}
public Optional<AttributeKvEntry> getServerPublicAttribute(String attribute) {
return Optional.ofNullable(serverPublicAttributesMap.get(attribute));
}
public void remove(AttributeKey key) {
Map<String, AttributeKvEntry> map = getMapByScope(key.getScope());
if (map != null) {
map.remove(key.getAttributeKey());
}
}
public void update(String scope, List<AttributeKvEntry> values) {
Map<String, AttributeKvEntry> map = getMapByScope(scope);
values.forEach(v -> map.put(v.getKey(), v));
}
private Map<String, AttributeKvEntry> getMapByScope(String scope) { | Map<String, AttributeKvEntry> map = null;
if (scope.equalsIgnoreCase(DataConstants.CLIENT_SCOPE)) {
map = clientSideAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SHARED_SCOPE)) {
map = serverPublicAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SERVER_SCOPE)) {
map = serverPrivateAttributesMap;
}
return map;
}
@Override
public String toString() {
return "DeviceAttributes{" +
"clientSideAttributesMap=" + clientSideAttributesMap +
", serverPrivateAttributesMap=" + serverPrivateAttributesMap +
", serverPublicAttributesMap=" + serverPublicAttributesMap +
'}';
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\rule\engine\DeviceAttributes.java | 1 |
请完成以下Java代码 | public void setDownloadURL (String DownloadURL)
{
set_Value (COLUMNNAME_DownloadURL, DownloadURL);
}
/** Get Download URL.
@return URL of the Download files
*/
public String getDownloadURL ()
{
return (String)get_Value(COLUMNNAME_DownloadURL);
}
/** Set Product Download.
@param M_ProductDownload_ID
Product downloads
*/
public void setM_ProductDownload_ID (int M_ProductDownload_ID)
{
if (M_ProductDownload_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, Integer.valueOf(M_ProductDownload_ID));
}
/** Get Product Download.
@return Product downloads
*/
public int getM_ProductDownload_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductDownload_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/ | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductDownload.java | 1 |
请完成以下Java代码 | public final class NamePairPredicates
{
private NamePairPredicates()
{
throw new IllegalStateException();
}
public static final INamePairPredicate ACCEPT_ALL = new INamePairPredicate()
{
@Override
public String toString()
{
return "ACCEPT_ALL";
}
@Override
public Set<String> getParameters(@Nullable final String contextTableName)
{
return ImmutableSet.of();
}
@Override
public boolean accept(final IValidationContext evalCtx, final NamePair item)
{
return true;
}
};
public static Composer compose()
{
return new Composer();
}
@EqualsAndHashCode
private static final class ComposedNamePairPredicate implements INamePairPredicate
{
private final ImmutableSet<INamePairPredicate> predicates;
private ComposedNamePairPredicate(final Set<INamePairPredicate> predicates)
{
// NOTE: we assume the predicates set is: not empty, has more than one element, does not contain nulls
this.predicates = ImmutableSet.copyOf(predicates);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper("composite")
.addValue(predicates)
.toString();
}
@Override
public ImmutableSet<String> getParameters(@Nullable final String contextTableName)
{
return predicates.stream()
.flatMap(predicate -> predicate.getParameters(contextTableName).stream())
.collect(ImmutableSet.toImmutableSet());
}
@Override
public boolean accept(final IValidationContext evalCtx, final NamePair item)
{
for (final INamePairPredicate predicate : predicates)
{
if (predicate.accept(evalCtx, item))
{
return true;
}
}
return false;
}
}
public static class Composer
{
private Set<INamePairPredicate> collectedPredicates = null;
private Composer()
{ | super();
}
public INamePairPredicate build()
{
if (collectedPredicates == null || collectedPredicates.isEmpty())
{
return ACCEPT_ALL;
}
else if (collectedPredicates.size() == 1)
{
return collectedPredicates.iterator().next();
}
else
{
return new ComposedNamePairPredicate(collectedPredicates);
}
}
public Composer add(@Nullable final INamePairPredicate predicate)
{
if (predicate == null || predicate == ACCEPT_ALL)
{
return this;
}
if (collectedPredicates == null)
{
collectedPredicates = new LinkedHashSet<>();
}
if (collectedPredicates.contains(predicate))
{
return this;
}
collectedPredicates.add(predicate);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\NamePairPredicates.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() { | return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
} | repos\Spring-Boot-Advanced-Projects-main\Springboot-Employee-Salary\src\main\java\spring\project\model\Employee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WEBUI_M_ReceiptSchedule_SelectHUsToReverse extends ReceiptScheduleBasedProcess
{
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
// Receipt schedule shall not be already closed
final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
final I_M_ReceiptSchedule receiptSchedule = context.getSelectedModel(I_M_ReceiptSchedule.class);
if(receiptScheduleBL.isClosed(receiptSchedule))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("already closed");
}
// Receipt schedule shall not be about packing materials
if (receiptSchedule.isPackagingMaterial())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not applying for packing materials");
}
if(receiptSchedule.getQtyMoved().signum()<=0)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no receipts to be reversed");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{ | final I_M_ReceiptSchedule receiptSchedule = getRecord(I_M_ReceiptSchedule.class);
final List<I_M_HU> hus = ReceiptCorrectHUsProcessor.builder()
.setM_ReceiptSchedule(receiptSchedule)
.build()
.getAvailableHUsToReverse();
if (hus.isEmpty())
{
throw new AdempiereException("@NotFound@ @M_HU_ID@");
}
getResult().setRecordsToOpen(TableRecordReference.ofCollection(hus));
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_SelectHUsToReverse.java | 2 |
请完成以下Java代码 | public List<HistoricCaseInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public boolean isNeedsCaseDefinitionOuterJoin() {
if (isNeedsPaging()) {
if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) {
// When using oracle, db2 or mssql we don't need outer join for the process definition join.
// It is not needed because the outer join order by is done by the row number instead
return false;
}
}
return hasOrderByForColumn(HistoricCaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName());
}
public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds;
}
public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) {
this.safeCaseInstanceIds = safeCaseInstanceIds;
} | public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public String getRootScopeId() {
return rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricCaseInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public String[][] toWordTagArray()
{
List<Word> wordList = toSimpleWordList();
String[][] pair = new String[2][wordList.size()];
Iterator<Word> iterator = wordList.iterator();
for (int i = 0; i < pair[0].length; i++)
{
Word word = iterator.next();
pair[0][i] = word.value;
pair[1][i] = word.label;
}
return pair;
}
/**
* word pos ner
*
* @param tagSet
* @return
*/
public String[][] toWordTagNerArray(NERTagSet tagSet)
{
List<String[]> tupleList = Utility.convertSentenceToNER(this, tagSet);
String[][] result = new String[3][tupleList.size()];
Iterator<String[]> iterator = tupleList.iterator();
for (int i = 0; i < result[0].length; i++)
{
String[] tuple = iterator.next();
for (int j = 0; j < 3; ++j)
{
result[j][i] = tuple[j];
}
}
return result;
} | public Sentence mergeCompoundWords()
{
ListIterator<IWord> listIterator = wordList.listIterator();
while (listIterator.hasNext())
{
IWord word = listIterator.next();
if (word instanceof CompoundWord)
{
listIterator.set(new Word(word.getValue(), word.getLabel()));
}
}
return this;
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Sentence sentence = (Sentence) o;
return toString().equals(sentence.toString());
}
@Override
public int hashCode()
{
return toString().hashCode();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\Sentence.java | 1 |
请完成以下Java代码 | public String getCamundaMapDecisionResult() {
return camundaMapDecisionResultAttribute.getValue(this);
}
@Override
public void setCamundaMapDecisionResult(String camundaMapDecisionResult) {
camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTask.class, CMMN_ELEMENT_DECISION_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionTask>() {
public DecisionTask newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTaskImpl(instanceContext);
}
});
decisionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DECISION_REF)
.build();
/** Camunda extensions */
camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE)
.namespace(CAMUNDA_NS)
.build(); | camundaDecisionBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_BINDING)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
camundaMapDecisionResultAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_MAP_DECISION_RESULT)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
decisionRefExpressionChild = sequenceBuilder.element(DecisionRefExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionTaskImpl.java | 1 |
请完成以下Java代码 | public class WebappLogger extends BaseLogger {
public static final String PROJECT_CODE = "WEBAPP";
public static final WebappLogger INSTANCE = BaseLogger.createLogger(WebappLogger.class, PROJECT_CODE,
"org.camunda.bpm.webapp", "00");
public InvalidRequestException invalidRequestEngineNotFoundForName(String engineName) {
return new InvalidRequestException(Status.BAD_REQUEST,
"Process engine with name " + engineName + " does not exist");
}
public InvalidRequestException setupActionNotAvailable() {
return new InvalidRequestException(Status.FORBIDDEN, "Setup action not available");
}
public RestException processEngineProviderNotFound() {
return new RestException(Status.BAD_REQUEST, "Could not find an implementation of the " + ProcessEngineProvider.class + "- SPI");
}
public void infoWebappSuccessfulLogin(String username) {
logInfo("001", "Successful login for user {}.", username);
}
public void infoWebappFailedLogin(String username, String reason) {
logInfo("002", "Failed login attempt for user {}. Reason: {}", username, reason);
}
public void infoWebappLogout(String username) {
logInfo("003", "Successful logout for user {}.", username);
}
public void traceCacheValidationTime(Date cacheValidationTime) { | logTrace("004", "Cache validation time: {}", cacheValidationTime);
}
public void traceCacheValidationTimeUpdated(Date cacheValidationTime, Date newCacheValidationTime) {
logTrace("005", "Cache validation time updated from: {} to: {}", cacheValidationTime, newCacheValidationTime);
}
public void traceAuthenticationUpdated(String engineName) {
logTrace("006", "Authentication updated: {}", engineName);
}
public void traceAuthenticationRemoved(String engineName) {
logTrace("007", "Authentication removed: {}", engineName);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\WebappLogger.java | 1 |
请完成以下Java代码 | private boolean hasDraftCandidatesForPickingSlot(final PickingSlotId pickingSlotId)
{
return pickingCandidatesRepoHolder.get().hasDraftCandidatesForPickingSlot(pickingSlotId);
}
private void releaseAndSave(final I_M_PickingSlot pickingSlot)
{
pickingSlot.setC_BPartner_ID(-1);
pickingSlot.setC_BPartner_Location_ID(-1);
pickingSlot.setM_Picking_Job_ID(-1);
pickingSlotDAO.save(pickingSlot);
}
@Override
public void releasePickingSlotIfPossible(final PickingSlotId pickingSlotId)
{
final I_M_PickingSlot pickingSlot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class);
releasePickingSlotIfPossible(pickingSlot);
}
@Override
public void releasePickingSlotsIfPossible(@NonNull final Collection<PickingSlotId> pickingSlotIds)
{
// tolerate empty
if (pickingSlotIds.isEmpty())
{
return;
}
pickingSlotIds.forEach(this::releasePickingSlotIfPossible);
}
@Override
public List<I_M_HU> retrieveAvailableSourceHUs(@NonNull final PickingHUsQuery query)
{
final SourceHUsService sourceHuService = SourceHUsService.get();
return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, sourceHuService::retrieveParentHusThatAreSourceHUs);
}
@Override
@NonNull
public List<I_M_HU> retrieveAvailableHUsToPick(@NonNull final PickingHUsQuery query)
{
return RetrieveAvailableHUsToPick.retrieveAvailableHUsToPick(query, RetrieveAvailableHUsToPickFilters::retrieveFullTreeAndExcludePickingHUs);
}
@Override
public ImmutableList<HuId> retrieveAvailableHUIdsToPick(@NonNull final PickingHUsQuery query)
{
return retrieveAvailableHUsToPick(query) | .stream()
.map(I_M_HU::getM_HU_ID)
.map(HuId::ofRepoId)
.collect(ImmutableList.toImmutableList());
}
@Override
public ImmutableList<HuId> retrieveAvailableHUIdsToPickForShipmentSchedule(@NonNull final RetrieveAvailableHUIdsToPickRequest request)
{
final I_M_ShipmentSchedule schedule = loadOutOfTrx(request.getScheduleId(), I_M_ShipmentSchedule.class);
final PickingHUsQuery query = PickingHUsQuery
.builder()
.onlyTopLevelHUs(request.isOnlyTopLevel())
.shipmentSchedule(schedule)
.onlyIfAttributesMatchWithShipmentSchedules(request.isConsiderAttributes())
.build();
return retrieveAvailableHUIdsToPick(query);
}
public boolean clearPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, final boolean removeQueuedHUsFromSlot)
{
final I_M_PickingSlot slot = pickingSlotDAO.getById(pickingSlotId, I_M_PickingSlot.class);
if (removeQueuedHUsFromSlot)
{
huPickingSlotDAO.retrieveAllHUs(slot)
.stream()
.map(hu -> HuId.ofRepoId(hu.getM_HU_ID()))
.forEach(queuedHU -> removeFromPickingSlotQueue(slot, queuedHU));
}
return huPickingSlotDAO.isEmpty(slot);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotBL.java | 1 |
请完成以下Java代码 | public class IMPProcessorDAO extends AbstractIMPProcessorDAO
{
@Override
public List<AdempiereProcessorLog> retrieveAdempiereProcessorLogs(final org.compiere.model.I_IMP_Processor impProcessor)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(impProcessor);
final String trxName = InterfaceWrapperHelper.getTrxName(impProcessor);
final String whereClause = I_IMP_Processor.COLUMNNAME_IMP_Processor_ID + "=?";
return new Query(ctx, I_IMP_ProcessorLog.Table_Name, whereClause, trxName)
.setParameters(impProcessor.getIMP_Processor_ID())
.setOrderBy(I_IMP_ProcessorLog.COLUMNNAME_Created + " DESC")
.list(AdempiereProcessorLog.class);
}
@Override
public int deleteLogs(final org.compiere.model.I_IMP_Processor impProcessor, final boolean deleteAll)
{
final int keepLogDays = impProcessor.getKeepLogDays();
if (!deleteAll && keepLogDays < 1)
{ | return 0;
}
final StringBuilder sql = new StringBuilder();
sql.append("DELETE FROM " + X_IMP_ProcessorLog.Table_Name + " ");
sql.append("WHERE " + X_IMP_ProcessorLog.COLUMNNAME_IMP_Processor_ID + "=?");
if (!deleteAll)
{
sql.append(" AND (Created+" + keepLogDays + ") < now()");
}
final String trxName = InterfaceWrapperHelper.getTrxName(impProcessor);
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(),
new Object[] { impProcessor.getIMP_Processor_ID() },
trxName);
return no;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\IMPProcessorDAO.java | 1 |
请完成以下Java代码 | public void setValue (java.lang.String Value)
{
set_Value (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);
}
/** Set Gang.
@param X
X-Dimension, z.B. Gang
*/
@Override
public void setX (java.lang.String X)
{
set_Value (COLUMNNAME_X, X);
}
/** Get Gang.
@return X-Dimension, z.B. Gang
*/
@Override
public java.lang.String getX ()
{
return (java.lang.String)get_Value(COLUMNNAME_X);
}
/** Set Regal.
@param X1 Regal */
@Override
public void setX1 (java.lang.String X1)
{
set_Value (COLUMNNAME_X1, X1);
}
/** Get Regal.
@return Regal */
@Override
public java.lang.String getX1 ()
{
return (java.lang.String)get_Value(COLUMNNAME_X1);
}
/** Set Fach.
@param Y
Y-Dimension, z.B. Fach
*/
@Override
public void setY (java.lang.String Y)
{
set_Value (COLUMNNAME_Y, Y);
} | /** Get Fach.
@return Y-Dimension, z.B. Fach
*/
@Override
public java.lang.String getY ()
{
return (java.lang.String)get_Value(COLUMNNAME_Y);
}
/** Set Ebene.
@param Z
Z-Dimension, z.B. Ebene
*/
@Override
public void setZ (java.lang.String Z)
{
set_Value (COLUMNNAME_Z, Z);
}
/** Get Ebene.
@return Z-Dimension, z.B. Ebene
*/
@Override
public java.lang.String getZ ()
{
return (java.lang.String)get_Value(COLUMNNAME_Z);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Locator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Optional<JsonRequestBPartnerUpsertItem> mapDoctor()
{
if (doctor == null)
{
return Optional.empty();
}
final JsonRequestBPartnerUpsertItem doctorUpsertRequest =
DataMapper.mapDoctorToUpsertRequest(doctor, orgCode);
bPartnerIdentifier2RelationRole.put(doctorUpsertRequest.getBpartnerIdentifier(), JsonBPRelationRole.PhysicianDoctor);
return Optional.of(doctorUpsertRequest);
}
private Optional<JsonRequestBPartnerUpsertItem> mapPayer()
{
if (payer == null)
{
return Optional.empty();
}
final JsonRequestBPartnerUpsertItem payerUpsertItem =
DataMapper.mapPayerToUpsertRequest(payer, orgCode);
bPartnerIdentifier2RelationRole.put(payerUpsertItem.getBpartnerIdentifier(), JsonBPRelationRole.Payer);
return Optional.of(payerUpsertItem);
}
private Optional<JsonRequestBPartnerUpsertItem> mapPharmacy()
{
if (pharmacy == null)
{
return Optional.empty();
}
final JsonRequestBPartnerUpsertItem pharmacyUpsertRequest =
DataMapper.mapPharmacyToUpsertRequest(pharmacy, orgCode);
bPartnerIdentifier2RelationRole.put(pharmacyUpsertRequest.getBpartnerIdentifier(), JsonBPRelationRole.Pharmacy);
return Optional.of(pharmacyUpsertRequest);
}
private Optional<JsonRequestBPartnerUpsertItem> mapCreatedUpdatedBy()
{
if (rootBPartnerIdForUsers == null || (createdBy == null && updatedBy == null))
{
return Optional.empty();
}
final JsonRequestContactUpsert.JsonRequestContactUpsertBuilder requestContactUpsert = JsonRequestContactUpsert.builder();
final Optional<JsonRequestContactUpsertItem> createdByContact = DataMapper.userToBPartnerContact(createdBy); | createdByContact.ifPresent(requestContactUpsert::requestItem);
DataMapper.userToBPartnerContact(updatedBy)
.filter(updatedByContact -> createdByContact.isEmpty() || !updatedByContact.getContactIdentifier().equals(createdByContact.get().getContactIdentifier()))
.ifPresent(requestContactUpsert::requestItem);
final JsonRequestComposite jsonRequestComposite = JsonRequestComposite.builder()
.contacts(requestContactUpsert.build())
.build();
return Optional.of(JsonRequestBPartnerUpsertItem
.builder()
.bpartnerIdentifier(String.valueOf(rootBPartnerIdForUsers.getValue()))
.bpartnerComposite(jsonRequestComposite)
.build());
}
@Value
@Builder
public static class BPartnerRequestProducerResult
{
@NonNull
String patientBPartnerIdentifier;
@NonNull
String patientMainAddressIdentifier;
@NonNull
Map<String, JsonBPRelationRole> bPartnerIdentifier2RelationRole;
@NonNull
JsonRequestBPartnerUpsert jsonRequestBPartnerUpsert;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\BPartnerUpsertRequestProducer.java | 2 |
请完成以下Java代码 | private void addToModelUserDetails(ModelAndView model) {
log.info("================= addToModelUserDetails ============================");
String loggedUsername = SecurityContextHolder.getContext()
.getAuthentication()
.getName();
model.addObject("loggedUsername", loggedUsername);
log.trace("session : " + model.getModel());
log.info("================= addToModelUserDetails ============================");
}
public static boolean isRedirectView(ModelAndView mv) {
String viewName = mv.getViewName();
if (viewName.startsWith("redirect:/")) {
return true;
} | View view = mv.getView();
return (view != null && view instanceof SmartView && ((SmartView) view).isRedirectView());
}
public static boolean isUserLogged() {
try {
return !SecurityContextHolder.getContext()
.getAuthentication()
.getName()
.equals("anonymousUser");
} catch (Exception e) {
return false;
}
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\web\interceptor\UserInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderId implements RepoIdAware
{
@JsonCreator
public static OrderId ofRepoId(final int repoId)
{
return new OrderId(repoId);
}
@Nullable
public static OrderId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new OrderId(repoId) : null;
}
public static int toRepoId(@Nullable final OrderId orderId)
{
return orderId != null ? orderId.getRepoId() : -1;
}
int repoId;
private OrderId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_Order_ID");
} | @Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final OrderId id1, @Nullable final OrderId id2)
{
return Objects.equals(id1, id2);
}
public TableRecordReference toRecordRef() {return TableRecordReference.of(I_C_Order.Table_Name, repoId);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\order\OrderId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void listenToOrderEvents() {
this.eventBus.subscribe(EVENT_ORDER_READY_FOR_SHIPMENT, new EventSubscriber() {
@Override
public <E extends ApplicationEvent> void onEvent(E event) {
shipOrder(Integer.parseInt(event.getPayloadValue("order_id")));
}
});
}
@Override
public Optional<Parcel> getParcelByOrderId(int orderId) {
return Optional.ofNullable(this.shippedParcels.get(orderId));
}
public void setOrderRepository(ShippingOrderRepository orderRepository) { | this.orderRepository = orderRepository;
}
@Override
public EventBus getEventBus() {
return eventBus;
}
@Override
public void setEventBus(EventBus eventBus) {
this.eventBus = eventBus;
}
} | repos\tutorials-master\patterns-modules\ddd-contexts\ddd-contexts-shippingcontext\src\main\java\com\baeldung\dddcontexts\shippingcontext\service\ParcelShippingService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JunctionStateMachineConfiguration extends StateMachineConfigurerAdapter<String, String> {
@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config)
throws Exception {
config
.withConfiguration()
.autoStartup(true)
.listener(new StateMachineListener());
}
@Override
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states
.withStates()
.initial("SI")
.junction("SJ")
.state("high")
.state("medium")
.state("low")
.end("SF");
}
@Override
public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
transitions.withExternal()
.source("SI").target("SJ").event("E1")
.and()
.withJunction()
.source("SJ") | .first("high", highGuard())
.then("medium", mediumGuard())
.last("low")
.and().withExternal()
.source("low").target("SF").event("end");
}
@Bean
public Guard<String, String> mediumGuard() {
return ctx -> false;
}
@Bean
public Guard<String, String> highGuard() {
return ctx -> false;
}
} | repos\tutorials-master\spring-state-machine\src\main\java\com\baeldung\spring\statemachine\config\JunctionStateMachineConfiguration.java | 2 |
请完成以下Java代码 | public void addLongParameter(String name, long value) {
addParameter(name, value, Types.BIGINT, "BIGINT");
}
public void addStringListParameter(String name, List<String> value) {
addParameter(name, value, Types.VARCHAR, "VARCHAR");
}
public void addBooleanParameter(String name, boolean value) {
addParameter(name, value, Types.BOOLEAN, "BOOLEAN");
}
public void addUuidListParameter(String name, List<UUID> value) {
addParameter(name, value, UUID_TYPE.getJdbcTypeCode(), UUID_TYPE.getFriendlyName());
}
public String getQuery() {
return query.toString();
}
public static class Parameter {
private final Object value;
private final int type;
private final String name;
public Parameter(Object value, int type, String name) {
this.value = value; | this.type = type;
this.name = name;
}
}
public TenantId getTenantId() {
return securityCtx.getTenantId();
}
public CustomerId getCustomerId() {
return securityCtx.getCustomerId();
}
public EntityType getEntityType() {
return securityCtx.getEntityType();
}
public boolean isIgnorePermissionCheck() {
return securityCtx.isIgnorePermissionCheck();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\SqlQueryContext.java | 1 |
请完成以下Java代码 | public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (!response.containsHeader(XSS_PROTECTION_HEADER)) {
response.setHeader(XSS_PROTECTION_HEADER, this.headerValue.toString());
}
}
/**
* Sets the value of the X-XSS-PROTECTION header.
* <p>
* If {@link HeaderValue#DISABLED}, will specify that X-XSS-Protection is disabled.
* For example:
*
* <pre>
* X-XSS-Protection: 0
* </pre>
* <p>
* If {@link HeaderValue#ENABLED}, will contain a value of 1, but will not specify the
* mode as blocked. In this instance, any content will be attempted to be fixed. For
* example:
*
* <pre>
* X-XSS-Protection: 1
* </pre>
* <p>
* If {@link HeaderValue#ENABLED_MODE_BLOCK}, will contain a value of 1 and will
* specify mode as blocked. The content will be replaced with "#". For example:
*
* <pre>
* X-XSS-Protection: 1; mode=block
* </pre>
* @param headerValue the new header value
* @throws IllegalArgumentException when headerValue is null
* @since 5.8
*/
public void setHeaderValue(HeaderValue headerValue) {
Assert.notNull(headerValue, "headerValue cannot be null");
this.headerValue = headerValue;
}
/**
* The value of the x-xss-protection header. One of: "0", "1", "1; mode=block"
*
* @author Daniel Garnier-Moiroux
* @since 5.8
*/
public enum HeaderValue {
DISABLED("0"), ENABLED("1"), ENABLED_MODE_BLOCK("1; mode=block"); | private final String value;
HeaderValue(String value) {
this.value = value;
}
public static @Nullable HeaderValue from(String headerValue) {
for (HeaderValue value : values()) {
if (value.toString().equals(headerValue)) {
return value;
}
}
return null;
}
@Override
public String toString() {
return this.value;
}
}
@Override
public String toString() {
return getClass().getName() + " [headerValue=" + this.headerValue + "]";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\XXssProtectionHeaderWriter.java | 1 |
请完成以下Java代码 | public boolean isParameterNextLine()
{
Object oo = get_Value(COLUMNNAME_IsParameterNextLine);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsParameterNextLine(boolean IsParameterNextLine)
{
set_Value (COLUMNNAME_IsParameterNextLine, Boolean.valueOf(IsParameterNextLine));
}
public void setParameterSeqNo (int ParameterSeqNo)
{
set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo));
}
public int getParameterSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
public void setParameterDisplayLogic (String ParameterDisplayLogic)
{
set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic);
}
public String getParameterDisplayLogic ()
{
return (String)get_Value(COLUMNNAME_ParameterDisplayLogic);
}
public void setColumnName (String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
public String getColumnName ()
{
return (String)get_Value(COLUMNNAME_ColumnName);
} | /** Set Query Criteria Function.
@param QueryCriteriaFunction
column used for adding a sql function to query criteria
*/
public void setQueryCriteriaFunction (String QueryCriteriaFunction)
{
set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction);
}
/** Get Query Criteria Function.
@return column used for adding a sql function to query criteria
*/
public String getQueryCriteriaFunction ()
{
return (String)get_Value(COLUMNNAME_QueryCriteriaFunction);
}
@Override
public void setDefaultValue (String DefaultValue)
{
set_Value (COLUMNNAME_DefaultValue, DefaultValue);
}
@Override
public String getDefaultValue ()
{
return (String)get_Value(COLUMNNAME_DefaultValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java | 1 |
请完成以下Java代码 | class Manager {
@Id //
private String id;
private String name;
/**
* Uses the {@literal this.id} to look up documents in the {@literal employee} collection
* that have a matching {@literal managerId} field value.
*/
@ReadOnlyProperty
@DocumentReference(lookup="{'managerId':?#{#self._id} }")
private List<Employee> employees;
public Manager() {
}
public Manager(String id, String name) {
this.id = id;
this.name = name;
}
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 List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
} | repos\spring-data-examples-main\mongodb\linking\src\main\java\example\springdata\mongodb\linking\docref\jpastyle\Manager.java | 1 |
请完成以下Java代码 | public CoNLLSentence parse(List<Term> termList, int beamWidth, int numOfThreads)
{
String[] words = new String[termList.size()];
String[] tags = new String[termList.size()];
int k = 0;
for (Term term : termList)
{
words[k] = term.word;
tags[k] = term.nature.toString();
++k;
}
Configuration bestParse;
try
{
bestParse = parser.parse(words, tags, false, beamWidth, numOfThreads);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
CoNLLWord[] wordArray = new CoNLLWord[termList.size()];
for (int i = 0; i < words.length; i++)
{
wordArray[i] = new CoNLLWord(i + 1, words[i], tags[i]);
}
for (int i = 0; i < words.length; i++) | {
wordArray[i].DEPREL = parser.idWord(bestParse.state.getDependent(i + 1));
int index = bestParse.state.getHead(i + 1) - 1;
if (index < 0 || index >= wordArray.length)
{
wordArray[i].HEAD = CoNLLWord.ROOT;
}
else
{
wordArray[i].HEAD = wordArray[index];
}
}
return new CoNLLSentence(wordArray);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\parser\KBeamArcEagerDependencyParser.java | 1 |
请完成以下Java代码 | 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 void setResources(Map<String, ResourceEntity> resources) {
this.resources = resources;
}
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
public boolean isValidatingSchema() {
return validatingSchema;
}
public void setValidatingSchema(boolean validatingSchema) {
this.validatingSchema = validatingSchema;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean isNew) {
this.isNew = isNew;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<ProcessDefinition> getDeployedProcessDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class);
} | @Override
public List<CaseDefinition> getDeployedCaseDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class);
}
@Override
public List<DecisionDefinition> getDeployedDecisionDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class);
}
@Override
public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class);
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", resources=" + resources
+ ", deploymentTime=" + deploymentTime
+ ", validatingSchema=" + validatingSchema
+ ", isNew=" + isNew
+ ", source=" + source
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EventDefinitionResourceDataResource extends BaseDeploymentResourceDataResource {
@ApiOperation(value = "Get an event definition resource content", tags = { "Event Definitions" })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates both event definition and resource have been found and the resource data has been returned."),
@ApiResponse(code = 404, message = "Indicates the requested event definition was not found or there is no resource with the given id present in the event definition. The status-description contains additional information.")
})
@GetMapping(value = "/event-registry-repository/event-definitions/{eventDefinitionId}/resourcedata")
public byte[] getEventDefinitionResource(@ApiParam(name = "eventDefinitionId") @PathVariable String eventDefinitionId, HttpServletResponse response) {
EventDefinition eventDefinition = getEventDefinitionFromRequest(eventDefinitionId);
return getDeploymentResourceData(eventDefinition.getDeploymentId(), eventDefinition.getResourceName(), response);
}
/**
* Returns the {@link EventDefinition} that is requested. Throws the right exceptions when bad request was made or definition was not found. | */
protected EventDefinition getEventDefinitionFromRequest(String eventDefinitionId) {
EventDefinition eventDefinition = repositoryService.createEventDefinitionQuery().eventDefinitionId(eventDefinitionId).singleResult();
if (eventDefinition == null) {
throw new FlowableObjectNotFoundException("Could not find an event definition with id '" + eventDefinitionId + "'.", EventDefinition.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessEventDefinitionById(eventDefinition);
}
return eventDefinition;
}
} | repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\EventDefinitionResourceDataResource.java | 2 |
请完成以下Java代码 | private void createAlbertaOrderRecords(
@Nullable final String orgCode,
@NonNull final OLCand olCand,
@NonNull final JsonAlbertaOrderInfo jsonAlbertaOrderInfo,
@NonNull final MasterdataProvider masterdataProvider)
{
final OLCandId olCandId = OLCandId.ofRepoId(olCand.getId());
final AlbertaOrderLineInfo albertaOrderLineInfo = jsonAlbertaOrderInfo.getJsonAlbertaOrderLineInfo() != null
? buildAlbertaOrderLineInfo(jsonAlbertaOrderInfo.getJsonAlbertaOrderLineInfo(), olCandId)
: null;
final AlbertaOrderInfo albertaOrderInfo = AlbertaOrderInfo.builder()
.orgId(OrgId.ofRepoId(olCand.getAD_Org_ID()))
.olCandId(olCandId)
.externalId(jsonAlbertaOrderInfo.getExternalId())
.rootId(jsonAlbertaOrderInfo.getRootId())
.creationDate(jsonAlbertaOrderInfo.getCreationDate())
.startDate(jsonAlbertaOrderInfo.getStartDate())
.endDate(jsonAlbertaOrderInfo.getEndDate())
.dayOfDelivery(jsonAlbertaOrderInfo.getDayOfDelivery())
.nextDelivery(jsonAlbertaOrderInfo.getNextDelivery())
.doctorBPartnerId(resolveExternalBPartnerIdentifier(orgCode, jsonAlbertaOrderInfo.getDoctorBPartnerIdentifier(), masterdataProvider))
.pharmacyBPartnerId(resolveExternalBPartnerIdentifier(orgCode, jsonAlbertaOrderInfo.getPharmacyBPartnerIdentifier(), masterdataProvider))
.isInitialCare(jsonAlbertaOrderInfo.getIsInitialCare())
.isSeriesOrder(jsonAlbertaOrderInfo.getIsSeriesOrder())
.isArchived(jsonAlbertaOrderInfo.getIsArchived())
.annotation(jsonAlbertaOrderInfo.getAnnotation()) | .deliveryInformation(jsonAlbertaOrderInfo.getDeliveryInformation())
.deliveryNote(jsonAlbertaOrderInfo.getDeliveryNote())
.updated(jsonAlbertaOrderInfo.getUpdated())
.orderLine(albertaOrderLineInfo)
.therapy(jsonAlbertaOrderInfo.getTherapy())
.therapyTypes(jsonAlbertaOrderInfo.getTherapyTypes())
.build();
albertaOrderService.saveAlbertaOrderInfo(albertaOrderInfo);
}
@NonNull
private AlbertaOrderLineInfo buildAlbertaOrderLineInfo(@NonNull final JsonAlbertaOrderLineInfo jsonAlbertaOrderLineInfo, @NonNull final OLCandId olCandId)
{
return AlbertaOrderLineInfo.builder()
.externalId(jsonAlbertaOrderLineInfo.getExternalId())
.olCandId(olCandId)
.salesLineId(jsonAlbertaOrderLineInfo.getSalesLineId())
.unit(jsonAlbertaOrderLineInfo.getUnit())
.isPrivateSale(jsonAlbertaOrderLineInfo.getIsPrivateSale())
.isRentalEquipment(jsonAlbertaOrderLineInfo.getIsRentalEquipment())
.durationAmount(jsonAlbertaOrderLineInfo.getDurationAmount())
.timePeriod(jsonAlbertaOrderLineInfo.getTimePeriod())
.updated(jsonAlbertaOrderLineInfo.getUpdated())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\OrderCandidateRestControllerService.java | 1 |
请完成以下Java代码 | protected void paintTrack(final Graphics g, final JComponent c, final Rectangle r)
{
g.setColor(trackColor);
g.fillRect(r.x, r.y, r.width, r.height);
}
@Override
protected JButton createDecreaseButton(final int orientation)
{
return noButton;
}
@Override
protected JButton createIncreaseButton(final int orientation)
{
return noButton;
}
@Override
protected TrackListener createTrackListener()
{
return new MetasTrackListener();
}
private class MetasTrackListener extends TrackListener | {
@Override
public void mousePressed(MouseEvent e)
{
isMouseButtonPressed = true;
super.mousePressed(e);
scrollbar.repaint(getThumbBounds());
}
@Override
public void mouseReleased(MouseEvent e)
{
isMouseButtonPressed = false;
super.mouseReleased(e);
scrollbar.repaint(getThumbBounds());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshScrollBarUI.java | 1 |
请完成以下Java代码 | public MFSession getSessionById(final Properties ctx, final int AD_Session_ID)
{
if (AD_Session_ID <= 0)
{
return null;
}
MFSession session = getFromCache(ctx, AD_Session_ID);
// Try to load from database
if (session == null)
{
final I_AD_Session sessionPO = InterfaceWrapperHelper.create(ctx, AD_Session_ID, I_AD_Session.class, ITrx.TRXNAME_None);
if (sessionPO == null || sessionPO.getAD_Session_ID() != AD_Session_ID)
{
// No session found for given AD_Session_ID, a warning shall be already logged
return null;
}
session = new MFSession(sessionPO);
s_sessions.put(session.getAD_Session_ID(), session);
}
return session;
}
private final MFSession getFromCache(final Properties ctx, final int AD_Session_ID)
{
if (AD_Session_ID <= 0)
{
return null;
}
final MFSession session = s_sessions.get(AD_Session_ID);
if (session == null)
{
return null;
}
if (session.getAD_Session_ID() != AD_Session_ID)
{
return null;
}
return session;
}
@Override
public void logoutCurrentSession()
{
final Properties ctx = Env.getCtx();
final MFSession session = getCurrentSession(ctx);
if (session == null) | {
// no currently running session
return;
}
final boolean alreadyDestroyed = session.isDestroyed();
// Fire BeforeLogout event only if current session is not yet closes(i.e. processed)
if (!alreadyDestroyed)
{
ModelValidationEngine.get().fireBeforeLogout(session);
}
session.setDestroyed();
Env.removeContext(ctx, Env.CTXNAME_AD_Session_ID);
s_sessions.remove(session.getAD_Session_ID());
// Fire AfterLogout event only if current session was closed right now
if (!alreadyDestroyed && session.isDestroyed())
{
ModelValidationEngine.get().fireAfterLogout(session);
}
}
@Override
public void setDisableChangeLogsForThread(final boolean disable)
{
disableChangeLogsThreadLocal.set(disable);
}
@Override
public boolean isChangeLogEnabled()
{
//
// Check if it's disabled for current thread
final Boolean disableChangeLogsThreadLocalValue = disableChangeLogsThreadLocal.get();
if (Boolean.TRUE.equals(disableChangeLogsThreadLocalValue))
{
return false;
}
//
// Check if role allows us to create the change log
final IUserRolePermissions role = Env.getUserRolePermissionsOrNull();
if (role != null && !role.hasPermission(IUserRolePermissions.PERMISSION_ChangeLog))
{
return false;
}
return true; // enabled
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\impl\SessionBL.java | 1 |
请完成以下Java代码 | private Optional<BPartnerId> findCustomerId(final String customerName)
{
return bpartnersRepo.retrieveBPartnerIdBy(BPartnerQuery.builder()
.bpartnerName(customerName)
.build());
}
private Optional<ProductId> findProductId(final BPartnerId customerId, final String customerProductSearchString)
{
final Optional<ProductId> productIdByProductNo = bpartnerProductsRepo.getProductIdByCustomerProductNo(customerId, customerProductSearchString);
if (productIdByProductNo.isPresent())
{
return productIdByProductNo;
} | final Optional<ProductId> productIdByProductName = bpartnerProductsRepo.getProductIdByCustomerProductName(customerId, customerProductSearchString);
if (productIdByProductName.isPresent())
{
return productIdByProductName;
}
return Optional.empty();
}
private String trl(final String message)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
return msgBL.parseTranslation(RestApiUtilsV1.getAdLanguage(), message);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_product\impl\BpartnerProductRestController.java | 1 |
请完成以下Java代码 | protected AppDefinitionEntity getMostRecentVersionOfAppDefinition(AppModel appModel, String tenantId) {
AppDefinitionEntityManager appDefinitionEntityManager = CommandContextUtil.getAppDefinitionEntityManager();
AppDefinitionEntity existingAppDefinition = null;
if (tenantId != null && !tenantId.equals(AppEngineConfiguration.NO_TENANT_ID)) {
existingAppDefinition = appDefinitionEntityManager.findLatestAppDefinitionByKeyAndTenantId(appModel.getKey(), tenantId);
} else {
existingAppDefinition = appDefinitionEntityManager.findLatestAppDefinitionByKey(appModel.getKey());
}
return existingAppDefinition;
}
protected AppDefinitionEntity getPersistedInstanceOfAppDefinition(String key, String deploymentId, String tenantId) {
AppDefinitionEntityManager appDefinitionEntityManager = CommandContextUtil.getAppDefinitionEntityManager();
AppDefinitionEntity persistedAppDefinitionEntity = null;
if (tenantId == null || AppEngineConfiguration.NO_TENANT_ID.equals(tenantId)) {
persistedAppDefinitionEntity = appDefinitionEntityManager.findAppDefinitionByDeploymentAndKey(deploymentId, key);
} else {
persistedAppDefinitionEntity = appDefinitionEntityManager.findAppDefinitionByDeploymentAndKeyAndTenantId(deploymentId, key, tenantId);
}
return persistedAppDefinitionEntity; | }
protected void updateCachingAndArtifacts(AppDefinitionEntity appDefinition, AppModel appResourceModel, AppDeploymentEntity deployment) {
AppEngineConfiguration appEngineConfiguration = CommandContextUtil.getAppEngineConfiguration();
DeploymentCache<AppDefinitionCacheEntry> appDefinitionCache = appEngineConfiguration.getAppDefinitionCache();
AppDefinitionCacheEntry cacheEntry = new AppDefinitionCacheEntry(appDefinition, appResourceModel);
appDefinitionCache.add(appDefinition.getId(), cacheEntry);
deployment.addDeployedArtifact(appDefinition);
deployment.addAppDefinitionCacheEntry(appDefinition.getId(), cacheEntry);
}
@Override
public void undeploy(EngineDeployment parentDeployment, boolean cascade) {
// Nothing to do
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\AppDeployer.java | 1 |
请完成以下Java代码 | public boolean lock() {
// 系统当前时间,纳秒
long nowTime = System.nanoTime();
// 请求锁超时时间,纳秒
long timeout = timeOut * 1000000;
final Random random = new Random();
// 不断循环向Master节点请求锁,当请求时间(System.nanoTime() - nano)超过设定的超时时间则放弃请求锁
// 这个可以防止一个客户端在某个宕掉的master节点上阻塞过长时间
// 如果一个master节点不可用了,应该尽快尝试下一个master节点
while ((System.nanoTime() - nowTime) < timeout) {
// 将锁作为key存储到redis缓存中,存储成功则获得锁
if (redisTemplate.opsForValue().setIfAbsent(key, LOCKED)) {
isLocked = true;
// 设置锁的有效期,也是锁的自动释放时间,也是一个客户端在其他客户端能抢占锁之前可以执行任务的时间
// 可以防止因异常情况无法释放锁而造成死锁情况的发生
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
// 上锁成功结束请求
break;
}
// 获取锁失败时,应该在随机延时后进行重试,避免不同客户端同时重试导致谁都无法拿到锁的情况出现
// 睡眠10毫秒后继续请求锁
try {
Thread.sleep(10, random.nextInt(50000));
} catch (InterruptedException e) {
logger.error("获取分布式锁休眠被中断:", e);
}
}
return isLocked; | }
public boolean isLock() {
return redisTemplate.hasKey(key);
}
public void unlock() {
// 释放锁
// 不管请求锁是否成功,只要已经上锁,客户端都会进行释放锁的操作
if (isLocked) {
redisTemplate.delete(key);
}
}
} | repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\redis\lock\RedisLock.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ServiceProperties {
private final HttpServiceProperties httpServiceProperties = new HttpServiceProperties();
private final MemcachedServerProperties memcachedServerProperties = new MemcachedServerProperties();
private final RedisServerProperties redisServerProperties = new RedisServerProperties();
public HttpServiceProperties getHttp() {
return this.httpServiceProperties;
}
public MemcachedServerProperties getMemcached() {
return this.memcachedServerProperties;
}
public RedisServerProperties getRedis() {
return this.redisServerProperties;
}
public static class DeveloperRestApiProperties {
private static final boolean DEFAULT_START = false;
private boolean start = DEFAULT_START;
public boolean isStart() {
return this.start;
}
public void setStart(boolean start) {
this.start = start;
}
}
public static class HttpServiceProperties {
private static final boolean DEFAULT_SSL_REQUIRE_AUTHENTICATION = false;
private static final int DEFAULT_PORT = 7070;
private boolean sslRequireAuthentication = DEFAULT_SSL_REQUIRE_AUTHENTICATION;
private int port = DEFAULT_PORT;
private final DeveloperRestApiProperties developerRestApiProperties = new DeveloperRestApiProperties();
private String bindAddress;
public String getBindAddress() {
return this.bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public DeveloperRestApiProperties getDevRestApi() {
return developerRestApiProperties;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public boolean isSslRequireAuthentication() {
return this.sslRequireAuthentication;
}
public void setSslRequireAuthentication(boolean sslRequireAuthentication) {
this.sslRequireAuthentication = sslRequireAuthentication;
}
}
public static class MemcachedServerProperties { | private static final int DEFAULT_PORT = 11211;
private int port = DEFAULT_PORT;
private EnableMemcachedServer.MemcachedProtocol protocol = EnableMemcachedServer.MemcachedProtocol.ASCII;
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public EnableMemcachedServer.MemcachedProtocol getProtocol() {
return this.protocol;
}
public void setProtocol(EnableMemcachedServer.MemcachedProtocol protocol) {
this.protocol = protocol;
}
}
public static class RedisServerProperties {
public static final int DEFAULT_PORT = 6379;
private int port = DEFAULT_PORT;
private String bindAddress;
public String getBindAddress() {
return this.bindAddress;
}
public void setBindAddress(String bindAddress) {
this.bindAddress = bindAddress;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ServiceProperties.java | 2 |
请完成以下Java代码 | public class PPOrderBOMLineProductStorage extends AbstractProductStorage
{
// Services
private final transient IPPOrderBOMBL ppOrderBOMBL = Services.get(IPPOrderBOMBL.class);
private final I_PP_Order_BOMLine orderBOMLine;
private final ProductId productId;
private boolean staled = false;
public PPOrderBOMLineProductStorage(@NonNull final I_PP_Order_BOMLine orderBOMLine)
{
this(orderBOMLine, null);
}
public PPOrderBOMLineProductStorage(
@NonNull final I_PP_Order_BOMLine orderBOMLine,
@Nullable final ProductId productId)
{
this.orderBOMLine = orderBOMLine;
this.productId = computeProductIdEffective(orderBOMLine, productId);
}
private static ProductId computeProductIdEffective(
@NonNull final I_PP_Order_BOMLine orderBOMLine,
@Nullable final ProductId productId)
{
final ProductId bomLineProductId = ProductId.ofRepoId(orderBOMLine.getM_Product_ID());
if (productId == null)
{
return bomLineProductId;
}
else if (orderBOMLine.isAllowIssuingAnyProduct())
{
return productId;
}
else
{
if (!ProductId.equals(productId, bomLineProductId))
{
throw new AdempiereException("Product " + productId + " is not matching BOM line product " + bomLineProductId)
.appendParametersToMessage()
.setParameter("orderBOMLine", orderBOMLine);
}
return bomLineProductId;
}
}
/**
* @return infinite capacity because we don't want to enforce how many items we can allocate on this storage
*/
@Override
protected Capacity retrieveTotalCapacity()
{
checkStaled();
final I_C_UOM uom = ppOrderBOMBL.getBOMLineUOM(orderBOMLine);
return Capacity.createInfiniteCapacity(productId, uom); | }
/**
* @return quantity that was already issued/received on this order BOM Line
*/
@Override
protected BigDecimal retrieveQtyInitial()
{
checkStaled();
final Quantity qtyCapacity;
final Quantity qtyToIssueOrReceive;
final BOMComponentType componentType = BOMComponentType.ofCode(orderBOMLine.getComponentType());
if (componentType.isReceipt())
{
qtyCapacity = ppOrderBOMBL.getQtyRequiredToReceive(orderBOMLine);
qtyToIssueOrReceive = ppOrderBOMBL.getQtyToReceive(orderBOMLine);
}
else
{
qtyCapacity = ppOrderBOMBL.getQtyRequiredToIssue(orderBOMLine);
qtyToIssueOrReceive = ppOrderBOMBL.getQtyToIssue(orderBOMLine);
}
final Quantity qtyIssued = qtyCapacity.subtract(qtyToIssueOrReceive);
return qtyIssued.toBigDecimal();
}
@Override
protected void beforeMarkingStalled()
{
staled = true;
}
/**
* refresh BOM line if staled
*/
private void checkStaled()
{
if (!staled)
{
return;
}
InterfaceWrapperHelper.refresh(orderBOMLine);
staled = false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderBOMLineProductStorage.java | 1 |
请完成以下Java代码 | public ShipperGatewayId getShipperGatewayId()
{
return DhlConstants.SHIPPER_GATEWAY_ID;
}
@Override
public ShipperGatewayClient newClientForShipperId(@NonNull final ShipperId shipperId)
{
final DhlClientConfig config = configRepo.getByShipperId(shipperId);
// Create the RestTemplate configured with OAuth2
final RestTemplate restTemplate = buildOAuth2RestTemplate(config);
// Return the DhlShipperGatewayClient instance
return DhlShipperGatewayClient.builder()
.config(config)
.databaseLogger(DhlDatabaseClientLogger.instance)
.restTemplate(restTemplate)
.build(); | }
/**
* Creates a RestTemplate configured to authenticate with OAuth2 using the provided DhlClientConfig.
*/
private RestTemplate buildOAuth2RestTemplate(final DhlClientConfig clientConfig)
{
final RestTemplate restTemplate = new RestTemplate();
// Add the CustomOAuth2TokenRetriever to handle DHL's OAuth2 flow
final CustomOAuth2TokenRetriever tokenRetriever = new CustomOAuth2TokenRetriever(new RestTemplate());
// Add an interceptor that dynamically retrieves and injects the `Authorization` header
restTemplate.getInterceptors().add(
new OAuth2AuthorizationInterceptor(tokenRetriever, clientConfig)
);
return restTemplate;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlShipperGatewayClientFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void validateEvent(@NonNull final PurchaseCandidateAdvisedEvent event)
{
// nothing to do; the event was already validated on construction time
}
/**
* Create a supply candidate
*/
@Override
public void handleEvent(@NonNull final PurchaseCandidateAdvisedEvent event)
{
final SupplyRequiredDescriptor supplyRequiredDescriptor = event.getSupplyRequiredDescriptor();
final DemandDetail demandDetail = DemandDetail.forSupplyRequiredDescriptorOrNull(supplyRequiredDescriptor);
final PurchaseDetail purchaseDetail = PurchaseDetail.builder()
.qty(supplyRequiredDescriptor.getQtyToSupplyBD())
.vendorRepoId(event.getVendorId())
.purchaseCandidateRepoId(-1)
.productPlanningRepoId(event.getProductPlanningId())
.advised(Flag.TRUE)
.build();
// see if there is an existing supply candidate to work with
Candidate.CandidateBuilder candidateBuilder = null;
if (supplyRequiredDescriptor.getSupplyCandidateId() > 0)
{
final CandidatesQuery supplyCandidateQuery = CandidatesQuery.fromId(
CandidateId.ofRepoId(supplyRequiredDescriptor.getSupplyCandidateId()));
final Candidate existingCandidate = candidateRepositoryRetrieval.retrieveLatestMatchOrNull(supplyCandidateQuery);
if (existingCandidate != null)
{
candidateBuilder = existingCandidate.toBuilder();
}
}
if (candidateBuilder == null)
{
candidateBuilder = Candidate.builder(); | }
// put out data into the new or preexisting candidate
final Candidate supplyCandidate = candidateBuilder
.clientAndOrgId(event.getClientAndOrgId())
.id(CandidateId.ofRepoIdOrNull(supplyRequiredDescriptor.getSupplyCandidateId()))
.type(CandidateType.SUPPLY)
.businessCase(CandidateBusinessCase.PURCHASE)
.materialDescriptor(supplyRequiredDescriptor.getMaterialDescriptor())
.businessCaseDetail(purchaseDetail)
.additionalDemandDetail(demandDetail)
.simulated(supplyRequiredDescriptor.isSimulated())
.build();
final MaterialDispoGroupId groupId = candidateChangeHandler.onCandidateNewOrChange(supplyCandidate).getGroupId().orElse(null);
if (event.isDirectlyCreatePurchaseCandidate())
{
if (groupId == null)
{
throw new AdempiereException("No groupId");
}
// the group contains just one item, i.e. the supplyCandidate, but for the same of generic-ness we use that same interface that's also used for production and distribution
requestMaterialOrderService.requestMaterialOrderForCandidates(groupId, event.getEventDescriptor());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateAdvisedHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PlainParametersDAO extends AbstractParametersDAO
{
@Override
public IParameterPO newParameterPO(final Object parent, final String parameterTable)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(parent);
final String trxName = InterfaceWrapperHelper.getTrxName(parent);
final IParameterPO paramPO = POJOWrapper.create(ctx, parameterTable, IParameterPO.class, trxName);
final int recordId = InterfaceWrapperHelper.getId(parent);
final String tableName = InterfaceWrapperHelper.getModelTableName(parent);
final String parentLinkColumnName = tableName + "_ID";
// We need to set it directly in map, because else it won't be recognized as an available attribute (hasColumnName method)
POJOWrapper.getWrapper(paramPO).setValue(parentLinkColumnName, recordId);
return paramPO;
}
@Override
public List<IParameterPO> retrieveParamPOs(final Properties ctx, final String parentTable, final int parentId, final String parameterTable, final String trxName)
{
final String parentLinkColumnName = parentTable + "_ID";
final List<IParameterPO> paramPOs = new ArrayList<>();
final List<Object> rawRecords = POJOLookupMap.get().getRawRecords(parameterTable);
for (final Object rawRecord : rawRecords) | {
final IParameterPO paramPO = InterfaceWrapperHelper.create(rawRecord, IParameterPO.class);
if (!POJOWrapper.getWrapper(paramPO).hasColumnName(parentLinkColumnName))
{
continue;
}
final Optional<Integer> currentParentId = InterfaceWrapperHelper.getValue(paramPO, parentLinkColumnName);
if (!currentParentId.isPresent())
{
continue;
}
if (currentParentId.get() != parentId)
{
continue;
}
paramPOs.add(paramPO);
}
return paramPOs;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\PlainParametersDAO.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CandidateSaveResult onCandidateNewOrChange(
@NonNull final Candidate candidate,
@NonNull final OnNewOrChangeAdvise advise)
{
if (!advise.isAttemptUpdate())
{
throw new AdempiereException("This handler does not how to deal with isAttemptUpdate=false").appendParametersToMessage()
.setParameter("handler", candidate)
.setParameter("candidate", candidate);
}
assertCorrectCandidateType(candidate);
final CandidateSaveResult candidateSaveResult = candidateRepositoryWriteService.addOrUpdateOverwriteStoredSeqNo(candidate);
//final Candidate candidateWithQtyDeltaAndId = candidateSaveResult.toCandidateWithQtyDelta();
if (!candidateSaveResult.isQtyChanged() && !candidateSaveResult.isDateChanged())
{
// this candidate didn't change anything
//return candidateWithQtyDeltaAndId;
return candidateSaveResult;
}
final AvailableToPromiseMultiQuery query = AvailableToPromiseMultiQuery.forDescriptorAndAllPossibleBPartnerIds(candidate.getMaterialDescriptor());
final BigDecimal projectedQty = availableToPromiseRepository.retrieveAvailableStockQtySum(query);
final BigDecimal requiredAdditionalQty = candidateSaveResult
.getQtyDelta()
.subtract(projectedQty);
if (requiredAdditionalQty.signum() > 0)
{
final Candidate candidateWithQtyDeltaAndId = candidateSaveResult.toCandidateWithQtyDelta();
final SupplyRequiredEvent supplyRequiredEvent = SupplyRequiredEventCreator.createSupplyRequiredEvent(candidateWithQtyDeltaAndId, requiredAdditionalQty, null); | materialEventService.enqueueEventAfterNextCommit(supplyRequiredEvent); // want to avoid the situation that some response comes back before the data here was even committed to DB
}
//return candidateWithQtyDeltaAndId;
return candidateSaveResult;
}
@Override
public void onCandidateDelete(@NonNull final Candidate candidate)
{
assertCorrectCandidateType(candidate);
final Function<CandidateId, CandidateRepositoryWriteService.DeleteResult> deleteCandidateFunc = CandidateHandlerUtil.getDeleteFunction(candidate.getBusinessCase(), candidateRepositoryWriteService);
deleteCandidateFunc.apply(candidate.getId());
}
private void assertCorrectCandidateType(@NonNull final Candidate candidate)
{
Preconditions.checkArgument(candidate.getType() == CandidateType.STOCK_UP,
"Given parameter 'candidate' has type=%s; demandCandidate=%s",
candidate.getType(), candidate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\handler\StockUpCandiateHandler.java | 2 |
请完成以下Java代码 | public int getPP_Plant_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Plant_ID);
}
@Override
public void setReplenishmentClass (final @Nullable java.lang.String ReplenishmentClass)
{
set_Value (COLUMNNAME_ReplenishmentClass, ReplenishmentClass);
}
@Override
public java.lang.String getReplenishmentClass()
{
return get_ValueAsString(COLUMNNAME_ReplenishmentClass);
}
@Override
public void setSeparator (final java.lang.String Separator)
{
set_Value (COLUMNNAME_Separator, Separator);
}
@Override
public java.lang.String getSeparator()
{
return get_ValueAsString(COLUMNNAME_Separator);
}
@Override
public void setValue (final java.lang.String Value)
{ | set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Warehouse.java | 1 |
请完成以下Java代码 | public void setISO_Code (java.lang.String ISO_Code)
{
set_ValueNoCheck (COLUMNNAME_ISO_Code, ISO_Code);
}
/** Get ISO Währungscode.
@return Three letter ISO 4217 Code of the Currency
*/
@Override
public java.lang.String getISO_Code ()
{
return (java.lang.String)get_Value(COLUMNNAME_ISO_Code);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_ValueNoCheck (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);
}
@Override
public org.compiere.model.I_C_Location getOrg_Location() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class);
}
@Override
public void setOrg_Location(org.compiere.model.I_C_Location Org_Location)
{
set_ValueFromPO(COLUMNNAME_Org_Location_ID, org.compiere.model.I_C_Location.class, Org_Location);
}
/** Set Org Address.
@param Org_Location_ID
Organization Location/Address
*/
@Override
public void setOrg_Location_ID (int Org_Location_ID)
{
if (Org_Location_ID < 1)
set_ValueNoCheck (COLUMNNAME_Org_Location_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Org_Location_ID, Integer.valueOf(Org_Location_ID));
}
/** Get Org Address.
@return Organization Location/Address
*/
@Override
public int getOrg_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Org_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone) | {
set_ValueNoCheck (COLUMNNAME_Phone, Phone);
}
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Steuer-ID.
@param TaxID
Tax Identification
*/
@Override
public void setTaxID (java.lang.String TaxID)
{
set_ValueNoCheck (COLUMNNAME_TaxID, TaxID);
}
/** Get Steuer-ID.
@return Tax Identification
*/
@Override
public java.lang.String getTaxID ()
{
return (java.lang.String)get_Value(COLUMNNAME_TaxID);
}
/** Set Titel.
@param Title
Name this entity is referred to as
*/
@Override
public void setTitle (java.lang.String Title)
{
set_ValueNoCheck (COLUMNNAME_Title, Title);
}
/** Get Titel.
@return Name this entity is referred to as
*/
@Override
public java.lang.String getTitle ()
{
return (java.lang.String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse_v.java | 1 |
请完成以下Java代码 | public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result; | }
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\mime\Foo.java | 1 |
请完成以下Java代码 | protected void adoptElement(DomXmlElement elementToAdopt) {
Document document = this.domElement.getOwnerDocument();
Element element = elementToAdopt.domElement;
if (!document.equals(element.getOwnerDocument())) {
Node node = document.adoptNode(element);
if (node == null) {
throw LOG.unableToAdoptElement(elementToAdopt);
}
}
}
public String toString() {
StringWriter writer = new StringWriter();
writeToWriter(writer);
return writer.toString();
}
public void writeToWriter(Writer writer) {
dataFormat.getWriter().writeToWriter(writer, this.domElement);
}
/** | * Returns a XPath Factory
*
* @return the XPath factory
*/
protected XPathFactory getXPathFactory() {
if (cachedXPathFactory == null) {
cachedXPathFactory = XPathFactory.newInstance();
}
return cachedXPathFactory;
}
public <C> C mapTo(Class<C> javaClass) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(this.domElement, javaClass);
}
public <C> C mapTo(String javaClass) {
DataFormatMapper mapper = dataFormat.getMapper();
return mapper.mapInternalToJava(this.domElement, javaClass);
}
} | repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlElement.java | 1 |
请完成以下Java代码 | public CaseFileItemTransition getStandardEvent() {
CaseFileItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(CaseFileItemTransition standardEvent) {
CaseFileItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItemOnPart.class, CMMN_ELEMENT_CASE_FILE_ITEM_ON_PART)
.extendsType(OnPart.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<CaseFileItemOnPart>() {
public CaseFileItemOnPart newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseFileItemOnPartImpl(instanceContext);
} | });
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(CaseFileItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemOnPartImpl.java | 1 |
请完成以下Java代码 | public String getDelay() {
return delay;
}
public void setDelay(String delay) {
this.delay = delay;
}
public String getMaxDelay() {
return maxDelay;
}
public void setMaxDelay(String maxDelay) {
this.maxDelay = maxDelay;
}
public String getMultiplier() {
return multiplier;
}
public void setMultiplier(String multiplier) {
this.multiplier = multiplier;
}
public String getRandom() {
return random;
}
public void setRandom(String random) {
this.random = random;
}
}
public static class TopicPartition { | protected String topic;
protected Collection<String> partitions;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Collection<String> getPartitions() {
return partitions;
}
public void setPartitions(Collection<String> partitions) {
this.partitions = partitions;
}
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\KafkaInboundChannelModel.java | 1 |
请完成以下Java代码 | public Optional<BPartnerId> getBPartnerId(final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final BPartnerQuery query = createBPartnerQuery(bpartnerIdentifier, orgId);
return bpartnersRepo.retrieveBPartnerIdBy(query);
}
private static BPartnerQuery createBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final Type type = bpartnerIdentifier.getType();
final BPartnerQuery.BPartnerQueryBuilder builder = BPartnerQuery.builder();
if (orgId != null)
{
builder.onlyOrgId(orgId);
}
if (Type.METASFRESH_ID.equals(type))
{
return builder
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
}
else if (Type.EXTERNAL_ID.equals(type))
{
return builder
.externalId(bpartnerIdentifier.asExternalId())
.build();
}
else if (Type.VALUE.equals(type))
{
return builder | .bpartnerValue(bpartnerIdentifier.asValue())
.build();
}
else if (Type.GLN.equals(type))
{
return builder
.gln(bpartnerIdentifier.asGLN())
.build();
}
else
{
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListServicesFacade.java | 1 |
请完成以下Java代码 | public class SysDepartModel {
/**ID*/
private String id;
/**父机构ID*/
private String parentId;
/**机构/部门名称*/
private String departName;
/**英文名*/
private String departNameEn;
/**缩写*/
private String departNameAbbr;
/**排序*/
private Integer departOrder;
/**描述*/
private String description;
/**机构类别 1组织机构,2岗位*/
private String orgCategory;
/**机构类型*/
private String orgType;
/**机构编码*/
private String orgCode;
/**手机号*/
private String mobile;
/**传真*/
private String fax;
/**地址*/
private String address;
/**备注*/
private String memo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getDepartName() {
return departName;
}
public void setDepartName(String departName) {
this.departName = departName;
}
public String getDepartNameEn() {
return departNameEn;
}
public void setDepartNameEn(String departNameEn) {
this.departNameEn = departNameEn;
}
public String getDepartNameAbbr() {
return departNameAbbr;
}
public void setDepartNameAbbr(String departNameAbbr) {
this.departNameAbbr = departNameAbbr;
}
public Integer getDepartOrder() {
return departOrder;
} | public void setDepartOrder(Integer departOrder) {
this.departOrder = departOrder;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrgCategory() {
return orgCategory;
}
public void setOrgCategory(String orgCategory) {
this.orgCategory = orgCategory;
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java | 1 |
请完成以下Java代码 | private static class DiscoveredJmxOperationParameter implements JmxOperationParameter {
private final String name;
private final Class<?> type;
private final @Nullable String description;
DiscoveredJmxOperationParameter(OperationParameter operationParameter) {
this.name = operationParameter.getName();
this.type = JmxType.get(operationParameter.getType());
this.description = null;
}
DiscoveredJmxOperationParameter(ManagedOperationParameter managedParameter,
OperationParameter operationParameter) {
this.name = managedParameter.getName();
this.type = JmxType.get(operationParameter.getType());
this.description = managedParameter.getDescription();
}
@Override
public String getName() {
return this.name;
}
@Override
public Class<?> getType() {
return this.type;
}
@Override
public @Nullable String getDescription() {
return this.description;
} | @Override
public String toString() {
StringBuilder result = new StringBuilder(this.name);
if (this.description != null) {
result.append(" (").append(this.description).append(")");
}
result.append(":").append(this.type);
return result.toString();
}
}
/**
* Utility to convert to JMX supported types.
*/
private static final class JmxType {
static Class<?> get(Class<?> source) {
if (source.isEnum()) {
return String.class;
}
if (Date.class.isAssignableFrom(source) || Instant.class.isAssignableFrom(source)) {
return String.class;
}
if (source.getName().startsWith("java.")) {
return source;
}
if (source.equals(Void.TYPE)) {
return source;
}
return Object.class;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\annotation\DiscoveredJmxOperation.java | 1 |
请完成以下Java代码 | public boolean closeIt()
{
fireDocValidateEvent(ModelValidator.TIMING_BEFORE_CLOSE);
handler.closeIt(model);
fireDocValidateEvent(ModelValidator.TIMING_AFTER_CLOSE);
return true;
}
@Override
public void unCloseIt()
{
fireDocValidateEvent(ModelValidator.TIMING_BEFORE_UNCLOSE);
handler.unCloseIt(model);
fireDocValidateEvent(ModelValidator.TIMING_AFTER_UNCLOSE);
}
@Override
public boolean reverseCorrectIt()
{
fireDocValidateEvent(ModelValidator.TIMING_BEFORE_REVERSECORRECT);
handler.reverseCorrectIt(model);
fireDocValidateEvent(ModelValidator.TIMING_AFTER_REVERSECORRECT);
return true;
}
@Override
public boolean reverseAccrualIt()
{
fireDocValidateEvent(ModelValidator.TIMING_BEFORE_REVERSEACCRUAL);
handler.reverseAccrualIt(model);
fireDocValidateEvent(ModelValidator.TIMING_AFTER_REVERSEACCRUAL);
return true;
}
@Override
public boolean reActivateIt()
{
fireDocValidateEvent(ModelValidator.TIMING_BEFORE_REACTIVATE);
handler.reactivateIt(model);
fireDocValidateEvent(ModelValidator.TIMING_AFTER_REACTIVATE);
return true;
}
@Override
public String getSummary()
{
return handler.getSummary(model);
}
@Override
public String getDocumentInfo()
{
return handler.getDocumentInfo(model);
}
@Override
public LocalDate getDocumentDate()
{
return handler.getDocumentDate(model);
}
@Override
public String getDocumentNo()
{
return model.getDocumentNo();
}
@Override
public File createPDF()
{
return handler.createPDF(model);
}
@Override
public String getProcessMsg()
{
return processMsg;
}
@Override
public int getDoc_User_ID()
{
return handler.getDoc_User_ID(model);
}
@Override
public int getC_Currency_ID()
{
return handler.getC_Currency_ID(model);
} | @Override
public BigDecimal getApprovalAmt()
{
return handler.getApprovalAmt(model);
}
@Override
public int getAD_Client_ID()
{
return model.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return model.getAD_Org_ID();
}
@Override
public String getDocAction()
{
return model.getDocAction();
}
@Override
public boolean save()
{
InterfaceWrapperHelper.save(model);
return true;
}
@Override
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(model);
}
@Override
public int get_ID()
{
return InterfaceWrapperHelper.getId(model);
}
@Override
public int get_Table_ID()
{
return InterfaceWrapperHelper.getModelTableId(model);
}
@Override
public String get_TrxName()
{
return InterfaceWrapperHelper.getTrxName(model);
}
@Override
public void set_TrxName(final String trxName)
{
InterfaceWrapperHelper.setTrxName(model, trxName);
}
@Override
public boolean isActive()
{
return model.isActive();
}
@Override
public Object getModel()
{
return getDocumentModel();
}
@Override
public Object getDocumentModel()
{
return model;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java | 1 |
请完成以下Java代码 | public List<HistoricCaseInstanceEntity> findHistoricCaseInstancesByCaseDefinitionId(String caseDefinitionId) {
return dataManager.findHistoricCaseInstancesByCaseDefinitionId(caseDefinitionId);
}
@Override
public List<String> findHistoricCaseInstanceIdsByParentIds(Collection<String> caseInstanceIds) {
return dataManager.findHistoricCaseInstanceIdsByParentIds(caseInstanceIds);
}
@Override
public List<HistoricCaseInstance> findByCriteria(HistoricCaseInstanceQuery query) {
return dataManager.findByCriteria((HistoricCaseInstanceQueryImpl) query);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findWithVariablesByQueryCriteria(HistoricCaseInstanceQuery query) {
return dataManager.findWithVariablesByQueryCriteria((HistoricCaseInstanceQueryImpl) query);
}
@Override
public List<HistoricCaseInstance> findIdsByCriteria(HistoricCaseInstanceQuery query) {
return dataManager.findIdsByCriteria((HistoricCaseInstanceQueryImpl) query);
} | @Override
public long countByCriteria(HistoricCaseInstanceQuery query) {
return dataManager.countByCriteria((HistoricCaseInstanceQueryImpl) query);
}
@Override
public void deleteHistoricCaseInstances(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
dataManager.deleteHistoricCaseInstances(historicCaseInstanceQuery);
}
@Override
public void bulkDeleteHistoricCaseInstances(Collection<String> caseInstanceIds) {
dataManager.bulkDeleteHistoricCaseInstances(caseInstanceIds);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricCaseInstanceEntityManagerImpl.java | 1 |
请完成以下Java代码 | public boolean isLeftValue() {
return false;
}
public boolean isMethodInvocation() {
return true;
}
public final ValueReference getValueReference(Bindings bindings, ELContext context) {
return null;
}
@Override
public void appendStructure(StringBuilder builder, Bindings bindings) {
property.appendStructure(builder, bindings);
params.appendStructure(builder, bindings);
}
protected Object eval(Bindings bindings, ELContext context, boolean answerNullIfBaseIsNull) {
Object base = property.getPrefix().eval(bindings, context);
if (base == null) {
if (answerNullIfBaseIsNull) {
return null;
}
throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", property.getPrefix()));
}
Object method = property.getProperty(bindings, context);
if (method == null) {
throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base));
}
String name = bindings.convert(method, String.class);
context.setPropertyResolved(false);
Object result = context.getELResolver().invoke(context, base, name, null, params.eval(bindings, context));
if (!context.isPropertyResolved()) {
throw new MethodNotFoundException(
LocalMessages.get("error.property.method.notfound", name, base.getClass())
);
} | return result;
}
@Override
public Object eval(Bindings bindings, ELContext context) {
return eval(bindings, context, true);
}
public Object invoke(
Bindings bindings,
ELContext context,
Class<?> returnType,
Class<?>[] paramTypes,
Object[] paramValues
) {
return eval(bindings, context, false);
}
public int getCardinality() {
return 2;
}
public Node getChild(int i) {
return i == 0 ? property : i == 1 ? params : null;
}
@Override
public String toString() {
return "<method>";
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstMethod.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
log.debug("actionPerformed - Text:" + getHtmlText());
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
m_text = editor.getHtmlText();
m_isPressedOK = true;
dispose();
}
else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
}
public String getHtmlText()
{
String text = m_text;
// us315: check if is plain rext
if (field instanceof CTextPane)
{
if ("text/plain".equals(((CTextPane)field).getContentType()))
{
text = MADBoilerPlate.getPlainText(m_text); | log.info("Converted html to plain text: "+text);
}
}
return text;
}
public void setHtmlText(String htmlText)
{
m_text = htmlText;
editor.setHtmlText(htmlText);
}
public boolean isPressedOK()
{
return m_isPressedOK ;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditorDialog.java | 1 |
请完成以下Java代码 | public Builder addPermissionRecursively(final OrgPermission oa)
{
if (hasPermission(oa))
{
return this;
}
addPermission(oa, CollisionPolicy.Override);
// Do we look for trees?
final AdTreeId adTreeOrgId = getOrgTreeId();
if (adTreeOrgId == null)
{
return this;
}
final OrgResource orgResource = oa.getResource();
if (!orgResource.isGroupingOrg())
{
return this;
}
// Summary Org - Get Dependents
final MTree_Base tree = MTree_Base.getById(adTreeOrgId);
final String sql = "SELECT "
+ " AD_Client_ID"
+ ", AD_Org_ID"
+ ", " + I_AD_Org.COLUMNNAME_IsSummary
+ " FROM AD_Org "
+ " WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + tree.getNodeTableName()
+ " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y')";
final Object[] sqlParams = new Object[] { tree.getAD_Tree_ID(), orgResource.getOrgId() };
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
while (rs.next())
{
final ClientId clientId = ClientId.ofRepoId(rs.getInt(1)); | final OrgId orgId = OrgId.ofRepoId(rs.getInt(2));
final boolean isGroupingOrg = StringUtils.toBoolean(rs.getString(3));
final OrgResource resource = OrgResource.of(clientId, orgId, isGroupingOrg);
final OrgPermission childOrgPermission = oa.copyWithResource(resource);
addPermissionRecursively(childOrgPermission);
}
return this;
}
catch (final SQLException e)
{
throw new DBException(e, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermissions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonManufacturingOrderEvent
{
//
// Activity Identifier
@NonNull String wfProcessId;
@NonNull String wfActivityId;
@Value
@Builder
@Jacksonized
public static class IssueTo
{
@NonNull String issueStepId;
@NonNull String huQRCode;
@Nullable BigDecimal huWeightGrossBeforeIssue;
@NonNull BigDecimal qtyIssued;
@Nullable BigDecimal qtyRejected;
@Nullable String qtyRejectedReasonCode;
}
@Nullable IssueTo issueTo;
@Value
@Builder
@Jacksonized
public static class ReceiveFrom
{
@NonNull String lineId;
@NonNull BigDecimal qtyReceived;
@Nullable String bestBeforeDate;
@Nullable String productionDate;
@Nullable String lotNo;
@Nullable BigDecimal catchWeight;
@Nullable String catchWeightUomSymbol;
@Nullable ScannedCode barcode;
@Nullable JsonLUReceivingTarget aggregateToLU;
@Nullable JsonTUReceivingTarget aggregateToTU;
@JsonIgnore
public FinishedGoodsReceiveLineId getFinishedGoodsReceiveLineId() {return FinishedGoodsReceiveLineId.ofString(lineId);}
}
@Nullable ReceiveFrom receiveFrom; | @Value
@Builder
@Jacksonized
public static class PickTo
{
@NonNull String wfProcessId;
@NonNull String activityId;
@NonNull String lineId;
}
@Nullable PickTo pickTo;
@Builder
@Jacksonized
private JsonManufacturingOrderEvent(
@NonNull final String wfProcessId,
@NonNull final String wfActivityId,
//
@Nullable final IssueTo issueTo,
@Nullable final ReceiveFrom receiveFrom,
@Nullable final PickTo pickTo)
{
if (CoalesceUtil.countNotNulls(issueTo, receiveFrom) != 1)
{
throw new AdempiereException("One and only one action like issueTo, receiveFrom etc shall be specified in an event.");
}
this.wfProcessId = wfProcessId;
this.wfActivityId = wfActivityId;
this.issueTo = issueTo;
this.receiveFrom = receiveFrom;
this.pickTo = pickTo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\rest_api\json\JsonManufacturingOrderEvent.java | 2 |
请完成以下Java代码 | public @Nullable Duration getMaxAge() {
return this.maxAge;
}
public void setMaxAge(@Nullable Duration maxAge) {
this.maxAge = maxAge;
}
public @Nullable SameSite getSameSite() {
return this.sameSite;
}
public void setSameSite(@Nullable SameSite sameSite) {
this.sameSite = sameSite;
}
public @Nullable Boolean getPartitioned() {
return this.partitioned;
}
public void setPartitioned(@Nullable Boolean partitioned) {
this.partitioned = partitioned;
}
/**
* SameSite values.
*/
public enum SameSite {
/**
* SameSite attribute will be omitted when creating the cookie.
*/
OMITTED(null), | /**
* SameSite attribute will be set to None. Cookies are sent in both first-party
* and cross-origin requests.
*/
NONE("None"),
/**
* SameSite attribute will be set to Lax. Cookies are sent in a first-party
* context, also when following a link to the origin site.
*/
LAX("Lax"),
/**
* SameSite attribute will be set to Strict. Cookies are only sent in a
* first-party context (i.e. not when following a link to the origin site).
*/
STRICT("Strict");
private @Nullable final String attributeValue;
SameSite(@Nullable String attributeValue) {
this.attributeValue = attributeValue;
}
public @Nullable String attributeValue() {
return this.attributeValue;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\Cookie.java | 1 |
请完成以下Java代码 | public class Product {
private String name;
private String description;
private Double price;
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 Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
} | repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\mvc_mvp\mvp\Product.java | 1 |
请完成以下Java代码 | public B authorizationRequestUri(String authorizationRequestUri) {
this.authorizationRequestUri = authorizationRequestUri;
return getThis();
}
/**
* A {@code Function} to be provided a {@code UriBuilder} representation of the
* OAuth 2.0 Authorization Request allowing for further customizations.
* @param authorizationRequestUriFunction a {@code Function} to be provided a
* {@code UriBuilder} representation of the OAuth 2.0 Authorization Request
* @return the {@link AbstractBuilder}
* @since 5.3
*/
public B authorizationRequestUri(Function<UriBuilder, URI> authorizationRequestUriFunction) {
if (authorizationRequestUriFunction != null) {
this.authorizationRequestUriFunction = authorizationRequestUriFunction;
}
return getThis();
}
public abstract T build();
private String buildAuthorizationRequestUri() {
Map<String, Object> parameters = getParameters(); // Not encoded
this.parametersConsumer.accept(parameters);
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
parameters.forEach((k, v) -> {
String key = encodeQueryParam(k);
if (v instanceof Iterable) {
((Iterable<?>) v).forEach((value) -> queryParams.add(key, encodeQueryParam(String.valueOf(value))));
}
else if (v != null && v.getClass().isArray()) {
Object[] values = (Object[]) v;
for (Object value : values) {
queryParams.add(key, encodeQueryParam(String.valueOf(value)));
}
}
else {
queryParams.set(key, encodeQueryParam(String.valueOf(v)));
}
});
UriBuilder uriBuilder = this.uriBuilderFactory.uriString(this.authorizationUri).queryParams(queryParams);
return this.authorizationRequestUriFunction.apply(uriBuilder).toString();
}
protected Map<String, Object> getParameters() {
Map<String, Object> parameters = new LinkedHashMap<>();
parameters.put(OAuth2ParameterNames.RESPONSE_TYPE, this.responseType.getValue()); | parameters.put(OAuth2ParameterNames.CLIENT_ID, this.clientId);
if (!CollectionUtils.isEmpty(this.scopes)) {
parameters.put(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(this.scopes, " "));
}
if (this.state != null) {
parameters.put(OAuth2ParameterNames.STATE, this.state);
}
if (this.redirectUri != null) {
parameters.put(OAuth2ParameterNames.REDIRECT_URI, this.redirectUri);
}
parameters.putAll(this.additionalParameters);
return parameters;
}
// Encode query parameter value according to RFC 3986
private static String encodeQueryParam(String value) {
return UriUtils.encodeQueryParam(value, StandardCharsets.UTF_8);
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationRequest.java | 1 |
请完成以下Java代码 | public void setImplementationType(String implementationType) {
implementationTypeAttribute.setValue(this, implementationType);
}
public Collection<InputProcessParameter> getInputs() {
return inputCollection.get(this);
}
public Collection<OutputProcessParameter> getOutputs() {
return outputCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Process.class, CMMN_ELEMENT_PROCESS)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Process>() {
public Process newInstance(ModelTypeInstanceContext instanceContext) {
return new ProcessImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build(); | implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE)
.defaultValue("http://www.omg.org/spec/CMMN/ProcessType/Unspecified")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputCollection = sequenceBuilder.elementCollection(InputProcessParameter.class)
.build();
outputCollection = sequenceBuilder.elementCollection(OutputProcessParameter.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ProcessImpl.java | 1 |
请完成以下Java代码 | public LocalDateAndOrgId getValueAsLocalDateOrNull(@NonNull final String columnName)
{
@NonNull final PO docLinePO = getPO();
final int index = docLinePO.get_ColumnIndex(columnName);
if (index < 0)
{
return null;
}
final Timestamp ts = docLinePO.get_ValueAsTimestamp(index);
if (ts == null)
{
return null;
}
OrgId orgId = OrgId.ofRepoId(docLinePO.getAD_Org_ID());
if (orgId.isAny())
{
orgId = getDoc().getOrgId();
}
return LocalDateAndOrgId.ofTimestamp(ts, orgId, services::getTimeZone);
}
public final String getValueAsString(final String columnName)
{
final PO po = getPO();
final int index = po.get_ColumnIndex(columnName);
if (index != -1)
{
final Object valueObj = po.get_Value(index);
return valueObj != null ? valueObj.toString() : null;
}
return null;
}
/**
* Set ReversalLine_ID
* store original (voided/reversed) document line
*/
public final void setReversalLine_ID(final int ReversalLine_ID)
{
m_ReversalLine_ID = ReversalLine_ID;
} // setReversalLine_ID
/**
* @return get original (voided/reversed) document line
*/
public final int getReversalLine_ID()
{
return m_ReversalLine_ID;
}
/**
* @return is the reversal document line (not the original)
*/
public final boolean isReversalLine()
{
return m_ReversalLine_ID > 0 // has a reversal counterpart
&& get_ID() > m_ReversalLine_ID; // this document line was created after it's reversal counterpart
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("id", get_ID()) | .add("description", getDescription())
.add("productId", getProductId())
.add("qty", getQty())
.add("amtSource", getAmtSource())
.toString();
}
/**
* Is Tax Included
*
* @return true if tax is included in amounts
*/
public final boolean isTaxIncluded()
{
return _taxIncluded;
} // isTaxIncluded
/**
* Set Tax Included
*
* @param taxIncluded Is Tax Included?
*/
protected final void setIsTaxIncluded(final boolean taxIncluded)
{
_taxIncluded = taxIncluded;
}
/**
* @see Doc#isSOTrx()
*/
public boolean isSOTrx()
{
return m_doc.isSOTrx();
}
/**
* @return document currency precision
* @see Doc#getStdPrecision()
*/
protected final CurrencyPrecision getStdPrecision()
{
return m_doc.getStdPrecision();
}
/**
* @return document (header)
*/
protected final DT getDoc()
{
return m_doc;
}
public final PostingException newPostingException()
{
return m_doc.newPostingException()
.setDocument(getDoc())
.setDocLine(this);
}
public final PostingException newPostingException(final Throwable ex)
{
return m_doc.newPostingException(ex)
.setDocument(getDoc())
.setDocLine(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AppConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
/**
* Static resource locations including themes
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**/*")
.addResourceLocations("/", "/resources/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
/**
* View resolver for JSP
*/
@Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
} | /**
* Configuration for async thread bean
*
* More: https://docs.spring.io/autorepo/docs/spring-framework/5.0.3.RELEASE/javadoc-api/org/springframework/scheduling/SchedulingTaskExecutor.html
*/
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("CsvThread");
executor.initialize();
return executor;
}
} | repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\config\AppConfig.java | 2 |
请完成以下Java代码 | private static class ChangesCollector
{
private final ContactPersonsEventBus contactPersonsEventBus;
private HashMap<ContactPersonId, ContactPerson> contacts = new HashMap<>();
private ChangesCollector(@NonNull final ContactPersonsEventBus contactPersonsEventBus)
{
this.contactPersonsEventBus = contactPersonsEventBus;
}
public void collectChangedContact(final ContactPerson contact)
{
if (contacts == null)
{
throw new AdempiereException("collector already committed");
}
contacts.put(contact.getContactPersonId(), contact); | }
public void commit()
{
if (contacts == null)
{
return;
}
final ImmutableList<ContactPerson> contacts = ImmutableList.copyOf(this.contacts.values());
this.contacts = null;
if (contacts.isEmpty())
{
return;
}
contactPersonsEventBus.notifyChanged(contacts);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\interceptor\MKTG_ContactPerson.java | 1 |
请完成以下Java代码 | private static int getDisplayType(@NonNull final MColumn column, @NonNull final I_EXP_FormatLine formatLine)
{
if (formatLine.getAD_Reference_Override_ID() > 0)
{
return formatLine.getAD_Reference_Override_ID();
}
return column.getAD_Reference_ID();
}
private void createAttachment(@NonNull final CreateAttachmentRequest request)
{
try
{
final String documentAsString = writeDocumentToString(outDocument);
final byte[] data = documentAsString.getBytes();
final AttachmentEntryService attachmentEntryService = SpringContextHolder.instance.getBean(AttachmentEntryService.class);
attachmentEntryService.createNewAttachment(request.getTarget(), request.getAttachmentName(), data);
} | catch (final Exception exception)
{
throw AdempiereException.wrapIfNeeded(exception);
}
}
private static String writeDocumentToString(@NonNull final Document document) throws TransformerException
{
final TransformerFactory tranFactory = TransformerFactory.newInstance();
final Transformer aTransformer = tranFactory.newTransformer();
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
final Source src = new DOMSource(document);
final Writer writer = new StringWriter();
final Result dest2 = new StreamResult(writer);
aTransformer.transform(src, dest2);
return writer.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\exp\ExportHelper.java | 1 |
请完成以下Java代码 | public KeyInfoType getKeyInfo() {
return keyInfo;
}
/**
* Sets the value of the keyInfo property.
*
* @param value
* allowed object is
* {@link KeyInfoType }
*
*/
public void setKeyInfo(KeyInfoType value) {
this.keyInfo = value;
}
/**
* Gets the value of the object property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the object property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getObject().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ObjectType }
*
*
*/
public List<ObjectType> getObject() {
if (object == null) {
object = new ArrayList<ObjectType>(); | }
return this.object;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\SignatureType.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertsCompletableFuture\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | private DirContextOperations bindWithDn(String userDnStr, String username, String password, Attributes attrs) {
BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
Name userDn = LdapUtils.newLdapName(userDnStr);
Name fullDn = LdapUtils.prepend(userDn, ctxSource.getBaseLdapName());
logger.trace(LogMessage.format("Attempting to bind as %s", fullDn));
DirContext ctx = null;
try {
ctx = getContextSource().getContext(fullDn.toString(), password);
// Check for password policy control
PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx);
if (attrs == null || attrs.size() == 0) {
attrs = ctx.getAttributes(userDn, getUserAttributes());
}
DirContextAdapter result = new DirContextAdapter(attrs, userDn, ctxSource.getBaseLdapName());
if (ppolicy != null) {
result.setAttributeValue(ppolicy.getID(), ppolicy);
}
logger.debug(LogMessage.format("Bound %s", fullDn));
return result;
}
catch (NamingException ex) {
// This will be thrown if an invalid user name is used and the method may
// be called multiple times to try different names, so we trap the exception
// unless a subclass wishes to implement more specialized behaviour.
handleIfBindException(userDnStr, username, ex);
}
catch (javax.naming.NamingException ex) {
if (!this.alsoHandleJavaxNamingBindExceptions) {
throw LdapUtils.convertLdapException(ex);
}
handleIfBindException(userDnStr, username, LdapUtils.convertLdapException(ex));
}
finally {
LdapUtils.closeContext(ctx);
}
return null;
}
private void handleIfBindException(String dn, String username, org.springframework.ldap.NamingException naming) {
if ((naming instanceof org.springframework.ldap.AuthenticationException)
|| (naming instanceof org.springframework.ldap.OperationNotSupportedException)) {
handleBindException(dn, username, naming);
}
else {
throw naming;
}
}
/**
* Allows subclasses to inspect the exception thrown by an attempt to bind with a
* particular DN. The default implementation just reports the failure to the debug | * logger.
*/
protected void handleBindException(String userDn, String username, Throwable cause) {
logger.trace(LogMessage.format("Failed to bind as %s", userDn), cause);
}
/**
* Set whether javax-based bind exceptions should also be delegated to
* {@code #handleBindException} (only Spring-based bind exceptions are handled by
* default)
*
* <p>
* For passivity reasons, defaults to {@code false}, though may change to {@code true}
* in future releases.
* @param alsoHandleJavaxNamingBindExceptions - whether to delegate javax-based bind
* exceptions to #handleBindException
* @since 6.4
*/
public void setAlsoHandleJavaxNamingBindExceptions(boolean alsoHandleJavaxNamingBindExceptions) {
this.alsoHandleJavaxNamingBindExceptions = alsoHandleJavaxNamingBindExceptions;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\authentication\BindAuthenticator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private boolean isNotSupported(Throwable ex) {
return ex instanceof CommandNotFoundException;
}
private boolean checkIfSupported(String app, String ip, int port) {
try {
return Optional.ofNullable(appManagement.getDetailApp(app))
.flatMap(e -> e.getMachine(ip, port))
.flatMap(m -> VersionUtils.parseVersion(m.getVersion())
.map(v -> v.greaterOrEqual(version140)))
.orElse(true);
// If error occurred or cannot retrieve machine info, return true.
} catch (Exception ex) {
return true;
}
}
private Result<Boolean> checkValidRequest(ClusterModifyRequest request) {
if (StringUtil.isEmpty(request.getApp())) {
return Result.ofFail(-1, "app cannot be empty");
}
if (StringUtil.isEmpty(request.getIp())) { | return Result.ofFail(-1, "ip cannot be empty");
}
if (request.getPort() == null || request.getPort() < 0) {
return Result.ofFail(-1, "invalid port");
}
if (request.getMode() == null || request.getMode() < 0) {
return Result.ofFail(-1, "invalid mode");
}
if (!checkIfSupported(request.getApp(), request.getIp(), request.getPort())) {
return unsupportedVersion();
}
return null;
}
private <R> Result<R> unsupportedVersion() {
return Result.ofFail(4041, "Sentinel client not supported for cluster flow control (unsupported version or dependency absent)");
}
private static final String KEY_MODE = "mode";
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\cluster\ClusterConfigController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OAuth2ClientMapperProvider {
@Autowired
@Qualifier("basicOAuth2ClientMapper")
private OAuth2ClientMapper basicOAuth2ClientMapper;
@Autowired
@Qualifier("customOAuth2ClientMapper")
private OAuth2ClientMapper customOAuth2ClientMapper;
@Autowired
@Qualifier("githubOAuth2ClientMapper")
private OAuth2ClientMapper githubOAuth2ClientMapper;
@Autowired
@Qualifier("appleOAuth2ClientMapper")
private OAuth2ClientMapper appleOAuth2ClientMapper; | public OAuth2ClientMapper getOAuth2ClientMapperByType(MapperType oauth2MapperType) {
switch (oauth2MapperType) {
case CUSTOM:
return customOAuth2ClientMapper;
case BASIC:
return basicOAuth2ClientMapper;
case GITHUB:
return githubOAuth2ClientMapper;
case APPLE:
return appleOAuth2ClientMapper;
default:
throw new RuntimeException("OAuth2ClientRegistrationMapper with type " + oauth2MapperType + " is not supported!");
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\OAuth2ClientMapperProvider.java | 2 |
请完成以下Java代码 | public <T extends ModelElementInstance> T getModelElementById(String id) {
if (id == null) {
return null;
}
DomElement element = document.getElementById(id);
if(element != null) {
return (T) ModelUtil.getModelElement(element, this);
} else {
return null;
}
}
public Collection<ModelElementInstance> getModelElementsByType(ModelElementType type) {
Collection<ModelElementType> extendingTypes = type.getAllExtendingTypes();
List<ModelElementInstance> instances = new ArrayList<ModelElementInstance>();
for (ModelElementType modelElementType : extendingTypes) {
if(!modelElementType.isAbstract()) {
instances.addAll(modelElementType.getInstances(this));
}
}
return instances; | }
@SuppressWarnings("unchecked")
public <T extends ModelElementInstance> Collection<T> getModelElementsByType(Class<T> referencingClass) {
return (Collection<T>) getModelElementsByType(getModel().getType(referencingClass));
}
@Override
public ModelInstance clone() {
return new ModelInstanceImpl(model, modelBuilder, document.clone());
}
@Override
public ValidationResults validate(Collection<ModelElementValidator<?>> validators) {
return new ModelInstanceValidator(this, validators).validate();
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\ModelInstanceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Article editContent(User requester, Article article, String content) {
if (article.isNotAuthor(requester)) {
throw new IllegalArgumentException("you can't edit articles written by others.");
}
article.setContent(content);
return articleRepository.save(article);
}
/**
* Delete article.
*
* @param requester user who requested
* @param article article
*/
public void delete(User requester, Article article) {
if (article.isNotAuthor(requester)) {
throw new IllegalArgumentException("you can't delete articles written by others.");
}
articleRepository.delete(article);
}
/**
* Check if the requester has favorited the article.
*
* @param requester user who requested
* @param article article
* @return Returns true if already favorited
*/
public boolean isFavorite(User requester, Article article) {
return articleFavoriteRepository.existsBy(requester, article);
}
/**
* Favorite article.
*
* @param requester user who requested
* @param article article
*/
public void favorite(User requester, Article article) {
if (this.isFavorite(requester, article)) {
throw new IllegalArgumentException("you already favorited this article.");
} | articleFavoriteRepository.save(new ArticleFavorite(requester, article));
}
/**
* Unfavorite article.
*
* @param requester user who requested
* @param article article
*/
public void unfavorite(User requester, Article article) {
if (!this.isFavorite(requester, article)) {
throw new IllegalArgumentException("you already unfavorited this article.");
}
articleFavoriteRepository.deleteBy(requester, article);
}
/**
* Get article details for anonymous users
*
* @param article article
* @return Returns article details
*/
public ArticleDetails getArticleDetails(Article article) {
return articleRepository.findArticleDetails(article);
}
/**
* Get article details for user.
*
* @param requester user who requested
* @param article article
* @return Returns article details
*/
public ArticleDetails getArticleDetails(User requester, Article article) {
return articleRepository.findArticleDetails(requester, article);
}
} | repos\realworld-java21-springboot3-main\module\core\src\main\java\io\zhc1\realworld\service\ArticleService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private ImmutableSet<BPartnerId> getIdsByQuery(@NonNull final BPartnerQuery query)
{
return bpartnersRepo.retrieveBPartnerIdsBy(query);
}
public ImmutableList<BPartnerComposite> getByIds(@NonNull final Collection<BPartnerId> bpartnerIds)
{
final Collection<BPartnerComposite> bpartnerComposites = bpartnerCompositeCache.getAllOrLoad(bpartnerIds, this::retrieveByIds);
final ImmutableList.Builder<BPartnerComposite> result = ImmutableList.builder();
for (final BPartnerComposite bpartnerComposite : bpartnerComposites)
{
result.add(bpartnerComposite.deepCopy()); // important because the instance is mutable!
}
return result.build();
}
private ImmutableMap<BPartnerId, BPartnerComposite> retrieveByIds(@NonNull final Collection<BPartnerId> bpartnerIds)
{
final BPartnerCompositesLoader loader = BPartnerCompositesLoader.builder()
.recordChangeLogRepository(recordChangeLogRepository) | .userRoleRepository(userRoleRepository)
.bPartnerCreditLimitRepository(bPartnerCreditLimitRepository)
.build();
return loader.retrieveByIds(bpartnerIds);
}
/**
* @param validatePermissions Use-Case for {@code false}: when transferring a customer to another org, the user who does the transfer might not have access to the target-org.
*/
public void save(@NonNull final BPartnerComposite bpartnerComposite, final boolean validatePermissions)
{
final BPartnerCompositeSaver saver = new BPartnerCompositeSaver(bpartnerBL);
saver.save(bpartnerComposite, validatePermissions );
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\BPartnerCompositeRepository.java | 2 |
请完成以下Java代码 | public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId; | }
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getExternalTaskId() {
return externalTaskId;
}
public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java | 1 |
请完成以下Java代码 | public HistoricCaseDefinitionRestService getCaseDefinitionService() {
return new HistoricCaseDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public UserOperationLogRestService getUserOperationLogRestService() {
return new UserOperationLogRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricDetailRestService getDetailService() {
return new HistoricDetailRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricTaskInstanceRestService getTaskInstanceService() {
return new HistoricTaskInstanceRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricIncidentRestService getIncidentService() {
return new HistoricIncidentRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricIdentityLinkLogRestService getIdentityLinkService() {
return new HistoricIdentityLinkLogRestServiceImpl(getObjectMapper(), getProcessEngine());
} | public HistoricJobLogRestService getJobLogService() {
return new HistoricJobLogRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricDecisionInstanceRestService getDecisionInstanceService() {
return new HistoricDecisionInstanceRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricBatchRestService getBatchService() {
return new HistoricBatchRestServiceImpl(getObjectMapper(), getProcessEngine());
}
@Override
public HistoricExternalTaskLogRestService getExternalTaskLogService() {
return new HistoricExternalTaskLogRestServiceImpl(getObjectMapper(), getProcessEngine());
}
@Override
public HistoryCleanupRestService getHistoryCleanupRestService() {
return new HistoryCleanupRestServiceImpl(getObjectMapper(), getProcessEngine());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoryRestServiceImpl.java | 1 |
请完成以下Java代码 | public void setPA_ReportSource_ID (int PA_ReportSource_ID)
{
if (PA_ReportSource_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportSource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportSource_ID, Integer.valueOf(PA_ReportSource_ID));
}
/** Get Report Source.
@return Restriction of what will be shown in Report Line
*/
public int getPA_ReportSource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportSource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
}
/** Get User Element 1.
@return User defined accounting Element | */
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportSource.java | 1 |
请完成以下Java代码 | public class ListQueryParameterObject implements Serializable {
private static final long serialVersionUID = 1L;
protected AuthorizationCheck authCheck = new AuthorizationCheck();
protected TenantCheck tenantCheck = new TenantCheck();
protected List<QueryOrderingProperty> orderingProperties = new ArrayList<QueryOrderingProperty>();
protected int maxResults = Integer.MAX_VALUE;
protected int firstResult = 0;
protected Object parameter;
protected String databaseType;
public ListQueryParameterObject() {
}
public ListQueryParameterObject(Object parameter, int firstResult, int maxResults) {
this.parameter = parameter;
this.firstResult = firstResult;
this.maxResults = maxResults;
}
public int getFirstResult() {
return firstResult;
}
public int getFirstRow() {
return firstResult +1;
}
public int getLastRow() {
if(maxResults == Integer.MAX_VALUE) {
return maxResults;
}
return firstResult + maxResults + 1;
}
public int getMaxResults() {
return maxResults;
}
public Object getParameter() {
return parameter;
}
public void setFirstResult(int firstResult) {
this.firstResult = firstResult;
}
public void setMaxResults(int maxResults) {
this.maxResults = maxResults;
}
public void setParameter(Object parameter) {
this.parameter = parameter;
}
public void setDatabaseType(String databaseType) {
this.databaseType = databaseType;
} | public String getDatabaseType() {
return databaseType;
}
public AuthorizationCheck getAuthCheck() {
return authCheck;
}
public void setAuthCheck(AuthorizationCheck authCheck) {
this.authCheck = authCheck;
}
public TenantCheck getTenantCheck() {
return tenantCheck;
}
public void setTenantCheck(TenantCheck tenantCheck) {
this.tenantCheck = tenantCheck;
}
public List<QueryOrderingProperty> getOrderingProperties() {
return orderingProperties;
}
public void setOrderingProperties(List<QueryOrderingProperty> orderingProperties) {
this.orderingProperties = orderingProperties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\ListQueryParameterObject.java | 1 |
请完成以下Java代码 | public static final StandardDocumentReportType ofProcessIdOrNull(@Nullable final AdProcessId adProcessId)
{
if (adProcessId == null)
{
return null;
}
else if (adProcessId.getRepoId() == 110)
{
return StandardDocumentReportType.ORDER;
}
else if (adProcessId.getRepoId() == 116)
{
return StandardDocumentReportType.INVOICE;
}
else if (adProcessId.getRepoId() == 117)
{
return StandardDocumentReportType.SHIPMENT;
}
else if (adProcessId.getRepoId() == 217)
{
return StandardDocumentReportType.PROJECT;
}
else if (adProcessId.getRepoId() == 159)
{
return StandardDocumentReportType.DUNNING;
}
// else if(adProcessId == 313) // Payment // => will be handled on upper level
// return;
if (adProcessId.getRepoId() == 53028) // Rpt PP_Order
{
return StandardDocumentReportType.MANUFACTURING_ORDER; | }
if (adProcessId.getRepoId() == 53044) // Rpt DD_Order
{
return StandardDocumentReportType.DISTRIBUTION_ORDER;
}
else
{
return null;
}
}
@Nullable
public static StandardDocumentReportType ofTableNameOrNull(@NonNull final String tableName)
{
for (StandardDocumentReportType type : values())
{
if (tableName.equals(type.getBaseTableName()))
{
return type;
}
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\StandardDocumentReportType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MetricFilter implements Filter {
@Autowired
private InMemoryMetricService metricService;
@Autowired
private CustomActuatorMetricService actMetricService;
@Override
public void init(final FilterConfig config) {
if (metricService == null || actMetricService == null) {
WebApplicationContext appContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(config.getServletContext());
metricService = appContext.getBean(InMemoryMetricService.class);
actMetricService = appContext.getBean(CustomActuatorMetricService.class);
} | }
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws java.io.IOException, ServletException {
final HttpServletRequest httpRequest = ((HttpServletRequest) request);
final String req = httpRequest.getMethod() + " " + httpRequest.getRequestURI();
chain.doFilter(request, response);
final int status = ((HttpServletResponse) response).getStatus();
metricService.increaseCount(req, status);
actMetricService.increaseCount(status);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\java\com\baeldung\metrics\filter\MetricFilter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void groupOrderLinesIfNeeded(@NonNull final QuotationLinesGroupAggregator linesGroup)
{
final GroupTemplate groupTemplate = linesGroup.getGroupTemplate();
if (groupTemplate == null)
{
return;
}
final ImmutableList<OrderLineId> orderLineIds = getOrderLineIds(linesGroup);
if (orderLineIds.isEmpty())
{
return;
}
orderGroupRepository.prepareNewGroup()
.groupTemplate(groupTemplate)
.createGroup(orderLineIds);
}
private static ImmutableList<OrderLineId> getOrderLineIds(@NonNull final QuotationLinesGroupAggregator linesGroup)
{
return linesGroup.streamQuotationLineIdsIndexedByCostCollectorId()
.map(entry -> entry.getValue().getOrderLineId())
.distinct()
.collect(ImmutableList.toImmutableList());
}
private QuotationLinesGroupAggregator createGroupAggregator(@NonNull final QuotationLinesGroupKey key)
{
if (key.getType() == QuotationLinesGroupKey.Type.REPAIRED_PRODUCT)
{
final ServiceRepairProjectTask task = tasksById.get(key.getTaskId());
if (task == null)
{
// shall not happen
throw new AdempiereException("No task found for " + key);
}
final int groupIndex = nextRepairingGroupIndex.getAndIncrement();
return RepairedProductAggregator.builder()
.priceCalculator(priceCalculator)
.key(key)
.groupCaption(String.valueOf(groupIndex))
.repairOrderSummary(task.getRepairOrderSummary())
.repairServicePerformedId(task.getRepairServicePerformedId())
.build();
}
else if (key.getType() == QuotationLinesGroupKey.Type.OTHERS)
{ | return OtherLinesAggregator.builder()
.priceCalculator(priceCalculator)
.build();
}
else
{
throw new AdempiereException("Unknown key type: " + key);
}
}
private OrderFactory newOrderFactory()
{
return OrderFactory.newSalesOrder()
.docType(quotationDocTypeId)
.orgId(pricingInfo.getOrgId())
.dateOrdered(extractDateOrdered(project, pricingInfo.getOrgTimeZone()))
.datePromised(pricingInfo.getDatePromised())
.shipBPartner(project.getBpartnerId(), project.getBpartnerLocationId(), project.getBpartnerContactId())
.salesRepId(project.getSalesRepId())
.pricingSystemId(pricingInfo.getPricingSystemId())
.warehouseId(project.getWarehouseId())
.paymentTermId(project.getPaymentTermId())
.campaignId(project.getCampaignId())
.projectId(project.getProjectId());
}
public final QuotationLineIdsByCostCollectorIdIndex getQuotationLineIdsIndexedByCostCollectorId()
{
Objects.requireNonNull(generatedQuotationLineIdsIndexedByCostCollectorId, "generatedQuotationLineIdsIndexedByCostCollectorId");
return generatedQuotationLineIdsIndexedByCostCollectorId;
}
public QuotationAggregator addAll(@NonNull final List<ServiceRepairProjectCostCollector> costCollectors)
{
this.costCollectorsToAggregate.addAll(costCollectors);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\QuotationAggregator.java | 2 |
请完成以下Java代码 | public final class PickingBOMsReversedIndex
{
public static PickingBOMsReversedIndex EMPTY = new PickingBOMsReversedIndex();
public static PickingBOMsReversedIndex ofBOMProductIdsByComponentId(final SetMultimap<ProductId, ProductId> bomProductIdsByComponentId)
{
return !bomProductIdsByComponentId.isEmpty()
? new PickingBOMsReversedIndex(bomProductIdsByComponentId)
: EMPTY;
}
private final ImmutableSetMultimap<ProductId, ProductId> bomProductIdsByComponentId;
private PickingBOMsReversedIndex()
{
bomProductIdsByComponentId = ImmutableSetMultimap.of();
}
private PickingBOMsReversedIndex(final SetMultimap<ProductId, ProductId> bomProductIdsByComponentId)
{
this.bomProductIdsByComponentId = ImmutableSetMultimap.copyOf(bomProductIdsByComponentId);
}
public ImmutableSet<ProductId> getBOMProductIdsByComponentId(@NonNull final ProductId componentId) | {
return bomProductIdsByComponentId.get(componentId);
}
public ImmutableSet<ProductId> getBOMProductIdsByComponentIds(@NonNull final Collection<ProductId> componentIds)
{
if (!componentIds.isEmpty())
{
return componentIds.stream()
.flatMap(componentId -> getBOMProductIdsByComponentId(componentId).stream())
.collect(ImmutableSet.toImmutableSet());
}
else
{
return ImmutableSet.of();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\picking_bom\PickingBOMsReversedIndex.java | 1 |
请完成以下Java代码 | private void assertDailyFlatrateDataEntriesAreFullyAllocated(final I_C_Flatrate_Term contract)
{
for (final DailyFlatrateDataEntry entry : _flatrateDataEntriesByDay.values())
{
if (!entry.isFullyAllocated())
{
throw new AdempiereException("Daily entry shall be fully allocated: " + entry
+ "\n Contract period: " + contract.getStartDate() + "->" + contract.getEndDate());
}
}
}
private static final class DailyFlatrateDataEntry
{
public static DailyFlatrateDataEntry of(final Date day)
{
return new DailyFlatrateDataEntry(day);
}
private final Date day;
private BigDecimal qtyPlanned = BigDecimal.ZERO;
private BigDecimal qtyPlannedAllocated = BigDecimal.ZERO;
private DailyFlatrateDataEntry(final Date day)
{
super();
Check.assumeNotNull(day, "day not null");
this.day = day;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("day", day)
.add("qtyPlanned", qtyPlanned)
.add("qtyPlannedAllocated", qtyPlannedAllocated)
.toString();
}
public Date getDay() | {
return day;
}
public void addQtyPlanned(final BigDecimal qtyPlannedToAdd)
{
if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0)
{
return;
}
qtyPlanned = qtyPlanned.add(qtyPlannedToAdd);
}
public BigDecimal allocateQtyPlanned()
{
final BigDecimal qtyPlannedToAllocate = qtyPlanned.subtract(qtyPlannedAllocated);
qtyPlannedAllocated = qtyPlanned;
return qtyPlannedToAllocate;
}
public boolean isFullyAllocated()
{
return qtyPlannedAllocated.compareTo(qtyPlanned) == 0;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\PMMContractBuilder.java | 1 |
请完成以下Java代码 | public I_C_UOM getC_UOM()
{
return uom;
}
private int getC_UOM_ID()
{
final int uomId = uom == null ? -1 : uom.getC_UOM_ID();
return uomId > 0 ? uomId : -1;
}
public I_M_Locator getM_Locator()
{
return locator;
}
private int getM_Locator_ID()
{
final int locatorId = locator == null ? -1 : locator.getM_Locator_ID();
return locatorId > 0 ? locatorId : -1;
}
public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1;
}
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID()
|| getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{
throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different | addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java | 1 |
请完成以下Java代码 | public static void removeSession(Session session) {
// 从 SESSION_USER_MAP 中移除
String user = SESSION_USER_MAP.remove(session);
// 从 USER_SESSION_MAP 中移除
if (user != null && user.length() > 0) {
USER_SESSION_MAP.remove(user);
}
}
// ========== 消息相关 ==========
/**
* 广播发送消息给所有在线用户
*
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
*/
public static <T extends Message> void broadcast(String type, T message) {
// 创建消息
String messageText = buildTextMessage(type, message);
// 遍历 SESSION_USER_MAP ,进行逐个发送
for (Session session : SESSION_USER_MAP.keySet()) {
sendTextMessage(session, messageText);
}
}
/**
* 发送消息给单个用户的 Session
*
* @param session Session
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
*/
public static <T extends Message> void send(Session session, String type, T message) {
// 创建消息
String messageText = buildTextMessage(type, message);
// 遍历给单个 Session ,进行逐个发送
sendTextMessage(session, messageText);
}
/**
* 发送消息给指定用户
*
* @param user 指定用户
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
* @return 发送是否成功你那个
*/
public static <T extends Message> boolean send(String user, String type, T message) {
// 获得用户对应的 Session | Session session = USER_SESSION_MAP.get(user);
if (session == null) {
LOGGER.error("[send][user({}) 不存在对应的 session]", user);
return false;
}
// 发送消息
send(session, type, message);
return true;
}
/**
* 构建完整的消息
*
* @param type 消息类型
* @param message 消息体
* @param <T> 消息类型
* @return 消息
*/
private static <T extends Message> String buildTextMessage(String type, T message) {
JSONObject messageObject = new JSONObject();
messageObject.put("type", type);
messageObject.put("body", message);
return messageObject.toString();
}
/**
* 真正发送消息
*
* @param session Session
* @param messageText 消息
*/
private static void sendTextMessage(Session session, String messageText) {
if (session == null) {
LOGGER.error("[sendTextMessage][session 为 null]");
return;
}
RemoteEndpoint.Basic basic = session.getBasicRemote();
if (basic == null) {
LOGGER.error("[sendTextMessage][session 的 为 null]");
return;
}
try {
basic.sendText(messageText);
} catch (IOException e) {
LOGGER.error("[sendTextMessage][session({}) 发送消息{}) 发生异常",
session, messageText, e);
}
}
} | repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\util\WebSocketUtil.java | 1 |
请完成以下Java代码 | public class UserCredentials extends BaseDataWithAdditionalInfo<UserCredentialsId> {
@Serial
private static final long serialVersionUID = -2108436378880529163L;
private UserId userId;
private boolean enabled;
private String password;
private String activateToken;
private Long activateTokenExpTime;
private String resetToken;
private Long resetTokenExpTime;
private Long lastLoginTs;
private Integer failedLoginAttempts;
public UserCredentials() {
super();
}
public UserCredentials(UserCredentialsId id) {
super(id);
}
@JsonIgnore
public boolean isActivationTokenExpired() {
return getActivationTokenTtl() == 0;
} | @JsonIgnore
public long getActivationTokenTtl() {
return activateTokenExpTime != null ? Math.max(activateTokenExpTime - System.currentTimeMillis(), 0) : 0;
}
@JsonIgnore
public boolean isResetTokenExpired() {
return getResetTokenTtl() == 0;
}
@JsonIgnore
public long getResetTokenTtl() {
return resetTokenExpTime != null ? Math.max(resetTokenExpTime - System.currentTimeMillis(), 0) : 0;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\security\UserCredentials.java | 1 |
请完成以下Java代码 | public String getUOMSymbol(@NonNull final UomId uomId)
{
final I_C_UOM uom = uomsRepo.getById(uomId);
return uom.getUOMSymbol();
}
@NonNull
public String getX12DE355(@NonNull final UomId uomId)
{
final I_C_UOM uom = uomsRepo.getById(uomId);
return uom.getX12DE355();
}
public List<I_C_BPartner_Product> getBPartnerProductRecords(final Set<ProductId> productIds)
{
return partnerProductsRepo.retrieveForProductIds(productIds);
}
public List<I_M_HU_PI_Item_Product> getMHUPIItemProductRecords(final Set<ProductId> productIds)
{
return huPIItemProductDAO.retrieveAllForProducts(productIds);
}
public List<UOMConversionsMap> getProductUOMConversions(final Set<ProductId> productIds)
{
if (productIds.isEmpty())
{
return ImmutableList.of();
}
return productIds.stream().map(uomConversionDAO::getProductConversions).collect(ImmutableList.toImmutableList());
}
public Stream<I_M_Product_Category> streamAllProductCategories()
{ | return productsRepo.streamAllProductCategories();
}
public List<I_C_BPartner> getPartnerRecords(@NonNull final ImmutableSet<BPartnerId> manufacturerIds)
{
return queryBL.createQueryBuilder(I_C_BPartner.class)
.addInArrayFilter(I_C_BPartner.COLUMN_C_BPartner_ID, manufacturerIds)
.create()
.list();
}
@NonNull
public JsonCreatedUpdatedInfo extractCreatedUpdatedInfo(@NonNull final I_M_Product_Category record)
{
final ZoneId orgZoneId = orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID()));
return JsonCreatedUpdatedInfo.builder()
.created(TimeUtil.asZonedDateTime(record.getCreated(), orgZoneId))
.createdBy(UserId.optionalOfRepoId(record.getCreatedBy()).orElse(UserId.SYSTEM))
.updated(TimeUtil.asZonedDateTime(record.getUpdated(), orgZoneId))
.updatedBy(UserId.optionalOfRepoId(record.getUpdatedBy()).orElse(UserId.SYSTEM))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductsServicesFacade.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SyncUser implements IConfirmableDTO
{
String uuid;
boolean deleted;
long syncConfirmationId;
String email;
String password;
String language;
@JsonCreator
@Builder(toBuilder = true)
public SyncUser(
@JsonProperty("uuid") final String uuid,
@JsonProperty("deleted") final boolean deleted,
@JsonProperty("syncConfirmationId") final long syncConfirmationId,
@JsonProperty("email") final String email,
@JsonProperty("password") final String password,
@JsonProperty("language") final String language)
{
this.uuid = uuid;
this.deleted = deleted;
this.syncConfirmationId = syncConfirmationId;
this.email = email; | this.password = password;
this.language = language;
}
@Override
public String toString()
{
return "SyncUser [email=" + email
+ ", password=" + (password != null && !password.isEmpty() ? "********" : "(none)")
+ ", language=" + language
+ "]";
}
@Override
public IConfirmableDTO withNotDeleted()
{
return toBuilder().deleted(false).build();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-procurement\src\main\java\de\metas\common\procurement\sync\protocol\dto\SyncUser.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.