instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public final class HttpSessionCsrfTokenRepository implements CsrfTokenRepository {
private static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
private static final String DEFAULT_CSRF_HEADER_NAME = "X-CSRF-TOKEN";
private static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = HttpSessionCsrfTokenRepository.class.getName()
.concat(".CSRF_TOKEN");
private String parameterName = DEFAULT_CSRF_PARAMETER_NAME;
private String headerName = DEFAULT_CSRF_HEADER_NAME;
private String sessionAttributeName = DEFAULT_CSRF_TOKEN_ATTR_NAME;
@Override
public void saveToken(@Nullable CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
if (token == null) {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(this.sessionAttributeName);
}
}
else {
HttpSession session = request.getSession();
session.setAttribute(this.sessionAttributeName, token);
}
}
@Override
public @Nullable CsrfToken loadToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return null;
}
return (CsrfToken) session.getAttribute(this.sessionAttributeName);
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
} | /**
* Sets the {@link HttpServletRequest} parameter name that the {@link CsrfToken} is
* expected to appear on
* @param parameterName the new parameter name to use
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName cannot be null or empty");
this.parameterName = parameterName;
}
/**
* Sets the header name that the {@link CsrfToken} is expected to appear on and the
* header that the response will contain the {@link CsrfToken}.
* @param headerName the new header name to use
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
this.headerName = headerName;
}
/**
* Sets the {@link HttpSession} attribute name that the {@link CsrfToken} is stored in
* @param sessionAttributeName the new attribute name to use
*/
public void setSessionAttributeName(String sessionAttributeName) {
Assert.hasLength(sessionAttributeName, "sessionAttributename cannot be null or empty");
this.sessionAttributeName = sessionAttributeName;
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\HttpSessionCsrfTokenRepository.java | 2 |
请完成以下Java代码 | public abstract class AbstractInstanceCancellationCmd extends AbstractProcessInstanceModificationCommand {
protected String cancellationReason;
public AbstractInstanceCancellationCmd(String processInstanceId) {
super(processInstanceId);
this.cancellationReason = "Cancellation due to process instance modifcation";
}
public AbstractInstanceCancellationCmd(String processInstanceId, String cancellationReason) {
super(processInstanceId);
this.cancellationReason = cancellationReason;
}
public Void execute(CommandContext commandContext) {
ExecutionEntity sourceInstanceExecution = determineSourceInstanceExecution(commandContext);
// Outline:
// 1. find topmost scope execution beginning at scopeExecution that has exactly
// one child (this is the topmost scope we can cancel)
// 2. cancel all children of the topmost execution
// 3. cancel the activity of the topmost execution itself (if applicable)
// 4. remove topmost execution (and concurrent parent) if topmostExecution is not the process instance
ExecutionEntity topmostCancellableExecution = sourceInstanceExecution;
ExecutionEntity parentScopeExecution = (ExecutionEntity) topmostCancellableExecution.getParentScopeExecution(false);
// if topmostCancellableExecution's scope execution has no other non-event-scope children,
// we have reached the correct execution | while (parentScopeExecution != null && (parentScopeExecution.getNonEventScopeExecutions().size() <= 1)) {
topmostCancellableExecution = parentScopeExecution;
parentScopeExecution = (ExecutionEntity) topmostCancellableExecution.getParentScopeExecution(false);
}
if (topmostCancellableExecution.isPreserveScope()) {
topmostCancellableExecution.interrupt(cancellationReason, skipCustomListeners, skipIoMappings, externallyTerminated);
topmostCancellableExecution.leaveActivityInstance();
topmostCancellableExecution.setActivity(null);
} else {
topmostCancellableExecution.deleteCascade(cancellationReason, skipCustomListeners, skipIoMappings, externallyTerminated, false);
ModificationUtil.handleChildRemovalInScope(topmostCancellableExecution);
}
return null;
}
protected abstract ExecutionEntity determineSourceInstanceExecution(CommandContext commandContext);
protected ExecutionEntity findSuperExecution(ExecutionEntity parentScopeExecution, ExecutionEntity topmostCancellableExecution){
ExecutionEntity superExecution = null;
if(parentScopeExecution == null) {
superExecution = topmostCancellableExecution.getSuperExecution();
}
return superExecution;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractInstanceCancellationCmd.java | 1 |
请完成以下Java代码 | protected List<CustomValueMapper> getValueMappers() {
SpinValueMapperFactory spinValueMapperFactory = new SpinValueMapperFactory();
CustomValueMapper javaValueMapper = new JavaValueMapper();
CustomValueMapper spinValueMapper = spinValueMapperFactory.createInstance();
if (spinValueMapper != null) {
return toScalaList(javaValueMapper, spinValueMapper);
} else {
return toScalaList(javaValueMapper);
}
}
@SafeVarargs
protected final <T> List<T> toScalaList(T... elements) {
java.util.List<T> listAsJava = Arrays.asList(elements);
return toList(listAsJava);
} | protected <T> List<T> toList(java.util.List list) {
return ListHasAsScala(list).asScala().toList();
}
protected org.camunda.feel.FeelEngine buildFeelEngine(CustomFunctionTransformer transformer,
CompositeValueMapper valueMapper) {
return new Builder()
.functionProvider(transformer)
.valueMapper(valueMapper)
.enableExternalFunctions(false)
.build();
}
} | repos\camunda-bpm-platform-master\engine-dmn\feel-scala\src\main\java\org\camunda\bpm\dmn\feel\impl\scala\ScalaFeelEngine.java | 1 |
请完成以下Java代码 | public void setCurrentDiEdge(CmmnDiEdge currentDiEdge) {
this.currentDiEdge = currentDiEdge;
}
public List<Stage> getStages() {
return stages;
}
public List<PlanFragment> getPlanFragments() {
return planFragments;
}
public List<Criterion> getEntryCriteria() {
return entryCriteria;
}
public List<Criterion> getExitCriteria() {
return exitCriteria;
}
public List<Sentry> getSentries() {
return sentries;
}
public List<SentryOnPart> getSentryOnParts() {
return sentryOnParts;
}
public List<SentryIfPart> getSentryIfParts() {
return sentryIfParts; | }
public List<PlanItem> getPlanItems() {
return planItems;
}
public List<PlanItemDefinition> getPlanItemDefinitions() {
return planItemDefinitions;
}
public List<CmmnDiShape> getDiShapes() {
return diShapes;
}
public List<CmmnDiEdge> getDiEdges() {
return diEdges;
}
public GraphicInfo getCurrentLabelGraphicInfo() {
return currentLabelGraphicInfo;
}
public void setCurrentLabelGraphicInfo(GraphicInfo labelGraphicInfo) {
this.currentLabelGraphicInfo = labelGraphicInfo;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\ConversionHelper.java | 1 |
请完成以下Java代码 | protected ConsistencyLevel getDefaultWriteConsistencyLevel() {
if (defaultWriteConsistencyLevel == null) {
if (writeConsistencyLevel != null) {
defaultWriteConsistencyLevel = DefaultConsistencyLevel.valueOf(writeConsistencyLevel.toUpperCase());
} else {
defaultWriteConsistencyLevel = DefaultConsistencyLevel.ONE;
}
}
return defaultWriteConsistencyLevel;
}
private void initSocketOptions(ProgrammaticDriverConfigLoaderBuilder driverConfigBuilder) {
driverConfigBuilder.withDuration(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT,
Duration.ofMillis(this.connectTimeoutMillis));
driverConfigBuilder.withDuration(DefaultDriverOption.REQUEST_TIMEOUT,
Duration.ofMillis(this.readTimeoutMillis));
if (this.keepAlive != null) {
driverConfigBuilder.withBoolean(DefaultDriverOption.SOCKET_KEEP_ALIVE,
this.keepAlive);
}
if (this.reuseAddress != null) {
driverConfigBuilder.withBoolean(DefaultDriverOption.SOCKET_REUSE_ADDRESS,
this.reuseAddress);
}
if (this.soLinger != null) {
driverConfigBuilder.withInt(DefaultDriverOption.SOCKET_LINGER_INTERVAL,
this.soLinger);
}
if (this.tcpNoDelay != null) {
driverConfigBuilder.withBoolean(DefaultDriverOption.SOCKET_TCP_NODELAY,
this.tcpNoDelay);
}
if (this.receiveBufferSize != null) {
driverConfigBuilder.withInt(DefaultDriverOption.SOCKET_RECEIVE_BUFFER_SIZE,
this.receiveBufferSize);
}
if (this.sendBufferSize != null) {
driverConfigBuilder.withInt(DefaultDriverOption.SOCKET_SEND_BUFFER_SIZE,
this.sendBufferSize);
}
}
private void initPoolingOptions(ProgrammaticDriverConfigLoaderBuilder driverConfigBuilder) { | driverConfigBuilder.withInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS,
this.max_requests_local);
}
private void initQueryOptions(ProgrammaticDriverConfigLoaderBuilder driverConfigBuilder) {
driverConfigBuilder.withInt(DefaultDriverOption.REQUEST_PAGE_SIZE,
this.defaultFetchSize);
}
private List<String> getContactPoints(String url) {
List<String> result;
if (StringUtils.isBlank(url)) {
result = Collections.emptyList();
} else {
result = new ArrayList<>();
for (String hostPort : url.split(COMMA)) {
result.add(hostPort);
}
}
return result;
}
} | repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\CassandraDriverOptions.java | 1 |
请完成以下Java代码 | protected PartitionedRegion getPartitionRegion() {
return this.partitionRegion;
}
@Override
public long getHitCount() throws StatisticsDisabledException {
return this.hitCount;
}
@Override
public float getHitRatio() throws StatisticsDisabledException {
return this.hitRatio;
}
@Override
public long getLastAccessedTime() throws StatisticsDisabledException {
return this.lastAccessedTime;
}
@Override
public long getLastModifiedTime() {
return this.lastModifiedTime;
}
@Override | public long getMissCount() throws StatisticsDisabledException {
return this.missCount;
}
@Override
public void resetCounts() throws StatisticsDisabledException {
this.hitCount = 0L;
this.hitRatio = 0.0f;
this.lastAccessedTime = 0L;
this.lastModifiedTime = 0L;
this.missCount = 0L;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator\src\main\java\org\springframework\geode\boot\actuate\health\support\RegionStatisticsResolver.java | 1 |
请完成以下Java代码 | private static final String bytesToString(final long sizeBytes)
{
if (sizeBytes < 1024)
{
return sizeBytes + " bytes";
}
else
{
final long sizeKb = sizeBytes / 1024;
if (sizeKb < 1024)
{
return sizeKb + "k";
}
else
{
final long sizeMb = sizeKb / 1024;
return sizeMb + "M";
}
}
}
/**************************************************************************
* Init
*
* @param config config
* @throws javax.servlet.ServletException
*/
@Override
public void init(ServletConfig config) throws ServletException
{
// NOTE: actually here we are starting all servers
m_serverMgr = AdempiereServerMgr.get();
}
/**
* Destroy
*/
@Override
public void destroy()
{
log.info("destroy");
m_serverMgr = null;
} // destroy
/**
* Log error/warning
*
* @param message message
* @param e exception
*/ | @Override
public void log(final String message, final Throwable e)
{
if (e == null)
{
log.warn(message);
}
log.error(message, e);
} // log
/**
* Log debug
*
* @param message message
*/
@Override
public void log(String message)
{
log.debug(message);
} // log
@Override
public String getServletName()
{
return NAME;
}
@Override
public String getServletInfo()
{
return "Server Monitor";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ServerMonitor.java | 1 |
请完成以下Java代码 | public static ShipmentScheduleId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
// NOTE: we need this String deserializer in order to use ShipmentScheduleId as a map key in a map that needs to deserialized from json
@JsonCreator
public static ShipmentScheduleId ofString(@NonNull final String repoIdStr)
{
return RepoIdAwares.ofObject(repoIdStr, ShipmentScheduleId.class, ShipmentScheduleId::ofRepoId);
}
public static ImmutableSet<Integer> toIntSet(@NonNull final Collection<ShipmentScheduleId> ids)
{
if (ids.isEmpty())
{
return ImmutableSet.of();
}
return ids.stream().map(ShipmentScheduleId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
public static ImmutableSet<ShipmentScheduleId> fromIntSet(@NonNull final Collection<Integer> repoIds)
{
if (repoIds.isEmpty())
{
return ImmutableSet.of();
}
return repoIds.stream().map(ShipmentScheduleId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet());
}
int repoId;
private ShipmentScheduleId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_ShipmentSchedule_ID"); | }
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final ShipmentScheduleId id)
{
return id != null ? id.getRepoId() : -1;
}
public TableRecordReference toTableRecordReference()
{
return TableRecordReference.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, getRepoId());
}
public static boolean equals(@Nullable final ShipmentScheduleId id1, @Nullable final ShipmentScheduleId id2) {return Objects.equals(id1, id2);}
public static TableRecordReferenceSet toTableRecordReferenceSet(@NonNull final Collection<ShipmentScheduleId> ids)
{
return TableRecordReferenceSet.of(M_SHIPMENT_SCHEDULE_TABLE_NAME, ids);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\ShipmentScheduleId.java | 1 |
请完成以下Java代码 | private IQuery<I_C_Order> createAllOrdersQuery(final I_EDI_Desadv desadv)
{
return queryBL.createQueryBuilder(I_C_Order.class, desadv)
// .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Order.COLUMNNAME_EDI_Desadv_ID, desadv.getEDI_Desadv_ID())
.create();
}
private IQueryBuilder<I_C_OrderLine> createAllOrderLinesQuery(final I_EDI_DesadvLine desadvLine)
{
return queryBL.createQueryBuilder(I_C_OrderLine.class, desadvLine)
// .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_EDI_DesadvLine_ID, desadvLine.getEDI_DesadvLine_ID());
}
@Override
public de.metas.handlingunits.model.I_M_ShipmentSchedule retrieveM_ShipmentScheduleOrNull(@NonNull final I_EDI_DesadvLine desadvLine)
{
final IQueryBuilder<I_C_OrderLine> orderLinesQuery = createAllOrderLinesQuery(desadvLine);
final IQueryBuilder<I_M_ShipmentSchedule> queryBuilder = orderLinesQuery
.andCollectChildren(I_M_ShipmentSchedule.COLUMN_C_OrderLine_ID, I_M_ShipmentSchedule.class);
queryBuilder.orderBy()
.addColumn(I_M_ShipmentSchedule.COLUMN_M_ShipmentSchedule_ID);
return queryBuilder.create().first(de.metas.handlingunits.model.I_M_ShipmentSchedule.class);
}
@Override
public BigDecimal retrieveMinimumSumPercentage()
{
final String minimumPercentageAccepted_Value = sysConfigBL.getValue(
SYS_CONFIG_DefaultMinimumPercentage, SYS_CONFIG_DefaultMinimumPercentage_DEFAULT);
try
{
return new BigDecimal(minimumPercentageAccepted_Value);
}
catch (final NumberFormatException e)
{
Check.errorIf(true, "AD_SysConfig {} = {} can't be parsed as a number", SYS_CONFIG_DefaultMinimumPercentage, minimumPercentageAccepted_Value);
return null; // shall not be reached
} | }
@Override
public void save(@NonNull final I_EDI_Desadv ediDesadv)
{
InterfaceWrapperHelper.save(ediDesadv);
}
@Override
public void save(@NonNull final I_EDI_DesadvLine ediDesadvLine)
{
InterfaceWrapperHelper.save(ediDesadvLine);
}
@Override
@NonNull
public List<I_M_InOut> retrieveShipmentsWithStatus(@NonNull final I_EDI_Desadv desadv, @NonNull final ImmutableSet<EDIExportStatus> statusSet)
{
return queryBL.createQueryBuilder(I_M_InOut.class, desadv)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut.COLUMNNAME_EDI_Desadv_ID, desadv.getEDI_Desadv_ID())
.addInArrayFilter(I_M_InOut.COLUMNNAME_EDI_ExportStatus, statusSet)
.create()
.list(I_M_InOut.class);
}
@Override
@NonNull
public I_M_InOut_Desadv_V getInOutDesadvByInOutId(@NonNull final InOutId shipmentId)
{
return queryBL.createQueryBuilder(I_M_InOut_Desadv_V.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut_Desadv_V.COLUMNNAME_M_InOut_ID, shipmentId)
.create()
.firstOnlyNotNull(I_M_InOut_Desadv_V.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\DesadvDAO.java | 1 |
请完成以下Java代码 | public class Jsr250Voter implements AccessDecisionVoter<Object> {
/**
* The specified config attribute is supported if its an instance of a
* {@link Jsr250SecurityConfig}.
* @param configAttribute The config attribute.
* @return whether the config attribute is supported.
*/
@Override
public boolean supports(ConfigAttribute configAttribute) {
return configAttribute instanceof Jsr250SecurityConfig;
}
/**
* All classes are supported.
* @param clazz the class.
* @return true
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
/**
* Votes according to JSR 250.
* <p>
* If no JSR-250 attributes are found, it will abstain, otherwise it will grant or
* deny access based on the attributes that are found. | * @param authentication The authentication object.
* @param object The access object.
* @param definition The configuration definition.
* @return The vote.
*/
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> definition) {
boolean jsr250AttributeFound = false;
for (ConfigAttribute attribute : definition) {
if (Jsr250SecurityConfig.PERMIT_ALL_ATTRIBUTE.equals(attribute)) {
return ACCESS_GRANTED;
}
if (Jsr250SecurityConfig.DENY_ALL_ATTRIBUTE.equals(attribute)) {
return ACCESS_DENIED;
}
if (supports(attribute)) {
jsr250AttributeFound = true;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authentication.getAuthorities()) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\annotation\Jsr250Voter.java | 1 |
请完成以下Java代码 | public void setTrxAmt (final @Nullable BigDecimal TrxAmt)
{
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
@Override
public BigDecimal getTrxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* TrxType AD_Reference_ID=215
* Reference name: C_Payment Trx Type
*/
public static final int TRXTYPE_AD_Reference_ID=215;
/** Sales = S */
public static final String TRXTYPE_Sales = "S";
/** DelayedCapture = D */
public static final String TRXTYPE_DelayedCapture = "D";
/** CreditPayment = C */
public static final String TRXTYPE_CreditPayment = "C";
/** VoiceAuthorization = F */
public static final String TRXTYPE_VoiceAuthorization = "F";
/** Authorization = A */
public static final String TRXTYPE_Authorization = "A";
/** Void = V */
public static final String TRXTYPE_Void = "V";
/** Rückzahlung = R */ | public static final String TRXTYPE_Rueckzahlung = "R";
@Override
public void setTrxType (final @Nullable java.lang.String TrxType)
{
set_Value (COLUMNNAME_TrxType, TrxType);
}
@Override
public java.lang.String getTrxType()
{
return get_ValueAsString(COLUMNNAME_TrxType);
}
@Override
public void setValutaDate (final @Nullable java.sql.Timestamp ValutaDate)
{
set_Value (COLUMNNAME_ValutaDate, ValutaDate);
}
@Override
public java.sql.Timestamp getValutaDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValutaDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_I_BankStatement.java | 1 |
请完成以下Java代码 | public boolean isCalled ()
{
Object oo = get_Value(COLUMNNAME_IsCalled);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Auftrag erteilt.
@param IsOrdered Auftrag erteilt */
@Override
public void setIsOrdered (boolean IsOrdered)
{
set_Value (COLUMNNAME_IsOrdered, Boolean.valueOf(IsOrdered));
}
/** Get Auftrag erteilt.
@return Auftrag erteilt */
@Override
public boolean isOrdered ()
{
Object oo = get_Value(COLUMNNAME_IsOrdered);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone)
{
throw new IllegalArgumentException ("Phone is virtual column"); }
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Anrufdatum.
@param PhonecallDate Anrufdatum */
@Override
public void setPhonecallDate (java.sql.Timestamp PhonecallDate)
{
set_Value (COLUMNNAME_PhonecallDate, PhonecallDate);
}
/** Get Anrufdatum.
@return Anrufdatum */
@Override
public java.sql.Timestamp getPhonecallDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallDate);
}
/** Set Erreichbar bis.
@param PhonecallTimeMax Erreichbar bis */
@Override
public void setPhonecallTimeMax (java.sql.Timestamp PhonecallTimeMax)
{
set_Value (COLUMNNAME_PhonecallTimeMax, PhonecallTimeMax); | }
/** Get Erreichbar bis.
@return Erreichbar bis */
@Override
public java.sql.Timestamp getPhonecallTimeMax ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMax);
}
/** Set Erreichbar von.
@param PhonecallTimeMin Erreichbar von */
@Override
public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin)
{
set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin);
}
/** Get Erreichbar von.
@return Erreichbar von */
@Override
public java.sql.Timestamp getPhonecallTimeMin ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin);
}
/** Set Kundenbetreuer.
@param SalesRep_ID Kundenbetreuer */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Kundenbetreuer.
@return Kundenbetreuer */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schedule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public InternalVariableInstanceQueryImpl getParameter() {
return this;
}
@Override
public boolean isRetained(Collection<VariableInstanceEntity> databaseEntities, Collection<CachedEntity> cachedEntities,
VariableInstanceEntity entity, Object param) {
return isRetained(entity, (InternalVariableInstanceQueryImpl) param);
}
@Override
public boolean isRetained(VariableInstanceEntity entity, Object param) {
return isRetained(entity, (InternalVariableInstanceQueryImpl) param);
}
public boolean isRetained(VariableInstanceEntity entity, InternalVariableInstanceQueryImpl param) {
if (param.executionId != null && !param.executionId.equals(entity.getExecutionId())) {
return false;
}
if (param.scopeId != null && !param.scopeId.equals(entity.getScopeId())) {
return false;
}
if (param.scopeIds != null && !param.scopeIds.contains(entity.getScopeId())) {
return false;
}
if (param.taskId != null && !param.taskId.equals(entity.getTaskId())) {
return false;
}
if (param.processInstanceId != null && !param.processInstanceId.equals(entity.getProcessInstanceId())) {
return false;
}
if (param.withoutTaskId && entity.getTaskId() != null) {
return false;
}
if (param.subScopeId != null && !param.subScopeId.equals(entity.getSubScopeId())) {
return false;
}
if (param.subScopeIds != null && !param.subScopeIds.contains(entity.getSubScopeId())) {
return false;
} | if (param.withoutSubScopeId && entity.getSubScopeId() != null) {
return false;
}
if (param.scopeType != null && !param.scopeType.equals(entity.getScopeType())) {
return false;
}
if (param.scopeTypes != null && !param.scopeTypes.isEmpty() && !param.scopeTypes.contains(entity.getScopeType())) {
return false;
}
if (param.id != null && !param.id.equals(entity.getId())) {
return false;
}
if (param.taskIds != null && !param.taskIds.contains(entity.getTaskId())) {
return false;
}
if (param.executionIds != null && !param.executionIds.contains(entity.getExecutionId())) {
return false;
}
if (param.name != null && !param.name.equals(entity.getName())) {
return false;
}
if (param.names != null && !param.names.isEmpty() && !param.names.contains(entity.getName())) {
return false;
}
return true;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\InternalVariableInstanceQueryImpl.java | 2 |
请完成以下Java代码 | public Incoterms getById(@NonNull final IncotermsId id)
{
final Incoterms incoterms = byId.get(id);
if (incoterms == null)
{
throw new AdempiereException("Incoterms not found by ID: " + id);
}
return incoterms;
}
@Nullable
public Incoterms getDefaultByOrgId(@NonNull final OrgId orgId)
{
return CoalesceUtil.coalesce(defaultByOrgId.get(orgId), defaultByOrgId.get(OrgId.ANY));
}
@NonNull Incoterms getByValue(@NonNull final String value, @NonNull final OrgId orgId)
{ | final Incoterms incoterms = CoalesceUtil.coalesce(byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(orgId).build()),
byValueAndOrgId.get(ValueAndOrgId.builder().value(value).orgId(OrgId.ANY).build()));
if (incoterms == null)
{
throw new AdempiereException("Incoterms not found by value: " + value + " and orgIds: " + orgId + " or " + OrgId.ANY);
}
return incoterms;
}
@Builder
@Value
private static class ValueAndOrgId
{
@NonNull String value;
@NonNull OrgId orgId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\incoterms\IncotermsRepository.java | 1 |
请完成以下Java代码 | public class Picture implements Serializable {
//主键
private Integer id;
//图片地址
private String path;
//备注
private String remark;
//添加时间
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPath() {
return path;
} | public void setPath(String path) {
this.path = path;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\entity\Picture.java | 1 |
请完成以下Java代码 | public int getXsize_()
{
return xsize_;
}
public void setXsize_(int xsize_)
{
this.xsize_ = xsize_;
}
public int getMax_xsize_()
{
return max_xsize_;
}
public void setMax_xsize_(int max_xsize_)
{
this.max_xsize_ = max_xsize_;
}
public int getThreadNum_()
{
return threadNum_;
}
public void setThreadNum_(int threadNum_)
{
this.threadNum_ = threadNum_;
}
public List<String> getUnigramTempls_()
{
return unigramTempls_;
}
public void setUnigramTempls_(List<String> unigramTempls_)
{
this.unigramTempls_ = unigramTempls_;
}
public List<String> getBigramTempls_()
{
return bigramTempls_;
}
public void setBigramTempls_(List<String> bigramTempls_) | {
this.bigramTempls_ = bigramTempls_;
}
public List<String> getY_()
{
return y_;
}
public void setY_(List<String> y_)
{
this.y_ = y_;
}
public List<List<Path>> getPathList_()
{
return pathList_;
}
public void setPathList_(List<List<Path>> pathList_)
{
this.pathList_ = pathList_;
}
public List<List<Node>> getNodeList_()
{
return nodeList_;
}
public void setNodeList_(List<List<Node>> nodeList_)
{
this.nodeList_ = nodeList_;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\FeatureIndex.java | 1 |
请完成以下Java代码 | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
KerberosServiceRequestToken auth = (KerberosServiceRequestToken) authentication;
byte[] token = auth.getToken();
LOG.debug("Try to validate Kerberos Token");
KerberosTicketValidation ticketValidation = this.ticketValidator.validateTicket(token);
LOG.debug("Successfully validated " + ticketValidation.username());
UserDetails userDetails = this.userDetailsService.loadUserByUsername(ticketValidation.username());
this.userDetailsChecker.check(userDetails);
additionalAuthenticationChecks(userDetails, auth);
KerberosServiceRequestToken responseAuth = new KerberosServiceRequestToken(userDetails, ticketValidation,
userDetails.getAuthorities(), token);
responseAuth.setDetails(authentication.getDetails());
return responseAuth;
}
@Override
public boolean supports(Class<? extends Object> auth) {
return KerberosServiceRequestToken.class.isAssignableFrom(auth);
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.ticketValidator, "ticketValidator must be specified");
Assert.notNull(this.userDetailsService, "userDetailsService must be specified");
}
/**
* The <code>UserDetailsService</code> to use, for loading the user properties and the
* <code>GrantedAuthorities</code>.
* @param userDetailsService the new user details service
*/
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
} | /**
* The <code>KerberosTicketValidator</code> to use, for validating the Kerberos/SPNEGO
* tickets.
* @param ticketValidator the new ticket validator
*/
public void setTicketValidator(KerberosTicketValidator ticketValidator) {
this.ticketValidator = ticketValidator;
}
/**
* Allows subclasses to perform any additional checks of a returned
* <code>UserDetails</code> for a given authentication request.
* @param userDetails as retrieved from the {@link UserDetailsService}
* @param authentication validated {@link KerberosServiceRequestToken}
* @throws AuthenticationException AuthenticationException if the credentials could
* not be validated (generally a <code>BadCredentialsException</code>, an
* <code>AuthenticationServiceException</code>)
*/
protected void additionalAuthenticationChecks(UserDetails userDetails, KerberosServiceRequestToken authentication)
throws AuthenticationException {
}
} | repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\KerberosServiceAuthenticationProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Builder initializeEmbeddedOptions(R2dbcProperties properties,
EmbeddedDatabaseConnection embeddedDatabaseConnection) {
String url = embeddedDatabaseConnection.getUrl(determineEmbeddedDatabaseName(properties));
if (url == null) {
throw connectionFactoryBeanCreationException("Failed to determine a suitable R2DBC Connection URL", url,
embeddedDatabaseConnection);
}
Builder builder = ConnectionFactoryOptions.parse(url).mutate();
String username = determineEmbeddedUsername(properties);
if (StringUtils.hasText(username)) {
builder.option(ConnectionFactoryOptions.USER, username);
}
if (StringUtils.hasText(properties.getPassword())) {
builder.option(ConnectionFactoryOptions.PASSWORD, properties.getPassword());
}
return builder;
}
private String determineEmbeddedDatabaseName(R2dbcProperties properties) {
String databaseName = determineDatabaseName(properties);
return (databaseName != null) ? databaseName : "testdb";
}
private @Nullable String determineDatabaseName(R2dbcProperties properties) {
if (properties.isGenerateUniqueName()) {
return properties.determineUniqueName();
}
if (StringUtils.hasLength(properties.getName())) {
return properties.getName();
}
return null;
}
private String determineEmbeddedUsername(R2dbcProperties properties) {
String username = ifHasText(properties.getUsername());
return (username != null) ? username : "sa";
}
private ConnectionFactoryBeanCreationException connectionFactoryBeanCreationException(String message, | @Nullable String r2dbcUrl, EmbeddedDatabaseConnection embeddedDatabaseConnection) {
return new ConnectionFactoryBeanCreationException(message, r2dbcUrl, embeddedDatabaseConnection);
}
private @Nullable String ifHasText(@Nullable String candidate) {
return (StringUtils.hasText(candidate)) ? candidate : null;
}
static class ConnectionFactoryBeanCreationException extends BeanCreationException {
private final @Nullable String url;
private final EmbeddedDatabaseConnection embeddedDatabaseConnection;
ConnectionFactoryBeanCreationException(String message, @Nullable String url,
EmbeddedDatabaseConnection embeddedDatabaseConnection) {
super(message);
this.url = url;
this.embeddedDatabaseConnection = embeddedDatabaseConnection;
}
@Nullable String getUrl() {
return this.url;
}
EmbeddedDatabaseConnection getEmbeddedDatabaseConnection() {
return this.embeddedDatabaseConnection;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryOptionsInitializer.java | 2 |
请完成以下Java代码 | public long findHistoricActivityInstanceCountByQueryCriteria(
HistoricActivityInstanceQueryImpl historicActivityInstanceQuery
) {
return historicActivityInstanceDataManager.findHistoricActivityInstanceCountByQueryCriteria(
historicActivityInstanceQuery
);
}
@Override
public List<HistoricActivityInstance> findHistoricActivityInstancesByQueryCriteria(
HistoricActivityInstanceQueryImpl historicActivityInstanceQuery,
Page page
) {
return historicActivityInstanceDataManager.findHistoricActivityInstancesByQueryCriteria(
historicActivityInstanceQuery,
page
);
}
@Override
public List<HistoricActivityInstance> findHistoricActivityInstancesByNativeQuery(
Map<String, Object> parameterMap,
int firstResult,
int maxResults
) {
return historicActivityInstanceDataManager.findHistoricActivityInstancesByNativeQuery(
parameterMap,
firstResult,
maxResults
);
} | @Override
public long findHistoricActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return historicActivityInstanceDataManager.findHistoricActivityInstanceCountByNativeQuery(parameterMap);
}
public HistoricActivityInstanceDataManager getHistoricActivityInstanceDataManager() {
return historicActivityInstanceDataManager;
}
public void setHistoricActivityInstanceDataManager(
HistoricActivityInstanceDataManager historicActivityInstanceDataManager
) {
this.historicActivityInstanceDataManager = historicActivityInstanceDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricActivityInstanceEntityManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
static class SecurityContextHolderStrategyFactory implements FactoryBean<SecurityContextHolderStrategy> {
@Override
public SecurityContextHolderStrategy getObject() throws Exception {
return SecurityContextHolder.getContextHolderStrategy();
}
@Override
public Class<?> getObjectType() {
return SecurityContextHolderStrategy.class;
}
} | static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\MethodSecurityBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public final LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public final boolean isHighVolume()
{
// NOTE: method will never be called because isCached() == true
return false;
}
@Override
public LookupSource getLookupSourceType()
{
return LookupSource.list;
}
@Override
public boolean hasParameters()
{
return !getDependsOnFieldNames().isEmpty();
}
@Override
public abstract boolean isNumericKey();
@Override
public abstract Set<String> getDependsOnFieldNames();
//
//
//
// -----------------------
//
//
@Override
public LookupDataSourceContext.Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builderWithoutTableName();
}
@Override
@Nullable
public abstract LookupValue retrieveLookupValueById(@NonNull LookupDataSourceContext evalCtx); | @Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return LookupDataSourceContext.builderWithoutTableName();
}
@Override
public abstract LookupValuesPage retrieveEntities(LookupDataSourceContext evalCtx);
@Override
@Nullable
public final String getCachePrefix()
{
// NOTE: method will never be called because isCached() == true
return null;
}
@Override
public final boolean isCached()
{
return true;
}
@Override
public void cacheInvalidate()
{
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\SimpleLookupDescriptorTemplate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMEASUREVALUE() {
return measurevalue;
}
/**
* Sets the value of the measurevalue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMEASUREVALUE(String value) {
this.measurevalue = value;
}
/**
* Gets the value of the ppack1 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 ppack1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPPACK1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PPACK1 }
*
*
*/
public List<PPACK1> getPPACK1() {
if (ppack1 == null) {
ppack1 = new ArrayList<PPACK1>(); | }
return this.ppack1;
}
/**
* Gets the value of the detail 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 detail property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDETAIL().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DETAILXlief }
*
*
*/
public List<DETAILXlief> getDETAIL() {
if (detail == null) {
detail = new ArrayList<DETAILXlief>();
}
return this.detail;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PACKINXlief.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getPassword() {
return password;
}
/**
* Sets the value of the password property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPassword(String value) {
this.password = value;
}
/**
* Gets the value of the messageLanguage property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getMessageLanguage() {
return messageLanguage;
}
/**
* Sets the value of the messageLanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageLanguage(String value) {
this.messageLanguage = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\GetAuth.java | 2 |
请完成以下Java代码 | public class X_PP_Product_BOMVersions extends org.compiere.model.PO implements I_PP_Product_BOMVersions, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1030246596L;
/** Standard Constructor */
public X_PP_Product_BOMVersions (final Properties ctx, final int PP_Product_BOMVersions_ID, @Nullable final String trxName)
{
super (ctx, PP_Product_BOMVersions_ID, trxName);
}
/** Load Constructor */
public X_PP_Product_BOMVersions (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final java.lang.String Name)
{ | set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID)
{
if (PP_Product_BOMVersions_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID);
}
@Override
public int getPP_Product_BOMVersions_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOMVersions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | JvmMemoryMetrics jvmMemoryMetrics(ObjectProvider<JvmMemoryMeterConventions> jvmMemoryMeterConventions) {
JvmMemoryMeterConventions conventions = jvmMemoryMeterConventions.getIfAvailable();
return (conventions != null) ? new JvmMemoryMetrics(Collections.emptyList(), conventions)
: new JvmMemoryMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmThreadMetrics jvmThreadMetrics(ObjectProvider<JvmThreadMeterConventions> jvmThreadMeterConventions) {
JvmThreadMeterConventions conventions = jvmThreadMeterConventions.getIfAvailable();
return (conventions != null) ? new JvmThreadMetrics(Collections.emptyList(), conventions)
: new JvmThreadMetrics();
}
@Bean
@ConditionalOnMissingBean
ClassLoaderMetrics classLoaderMetrics(
ObjectProvider<JvmClassLoadingMeterConventions> jvmClassLoadingMeterConventions) {
JvmClassLoadingMeterConventions conventions = jvmClassLoadingMeterConventions.getIfAvailable();
return (conventions != null) ? new ClassLoaderMetrics(conventions) : new ClassLoaderMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmInfoMetrics jvmInfoMetrics() {
return new JvmInfoMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmCompilationMetrics jvmCompilationMetrics() {
return new JvmCompilationMetrics();
} | @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = VIRTUAL_THREAD_METRICS_CLASS)
static class VirtualThreadMetricsConfiguration {
@Bean
@ConditionalOnMissingBean(type = VIRTUAL_THREAD_METRICS_CLASS)
@ImportRuntimeHints(VirtualThreadMetricsRuntimeHintsRegistrar.class)
MeterBinder virtualThreadMetrics() throws ClassNotFoundException {
Class<?> virtualThreadMetricsClass = ClassUtils.forName(VIRTUAL_THREAD_METRICS_CLASS,
getClass().getClassLoader());
return (MeterBinder) BeanUtils.instantiateClass(virtualThreadMetricsClass);
}
}
static final class VirtualThreadMetricsRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection()
.registerTypeIfPresent(classLoader, VIRTUAL_THREAD_METRICS_CLASS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
}
}
} | repos\spring-boot-main\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\jvm\JvmMetricsAutoConfiguration.java | 2 |
请完成以下Java代码 | public IDocumentNoBuilder forDocType(final int C_DocType_ID, final boolean useDefiniteSequence)
{
return createDocumentNoBuilder()
.setDocumentSequenceByDocTypeId(C_DocType_ID, useDefiniteSequence);
}
@Override
public IDocumentNoBuilder forSequenceId(final DocSequenceId sequenceId)
{
return createDocumentNoBuilder()
.setDocumentSequenceInfoBySequenceId(sequenceId);
}
@Override
public DocumentNoBuilder createDocumentNoBuilder()
{
return new DocumentNoBuilder();
}
@Override
public IDocumentNoBuilder createValueBuilderFor(@NonNull final Object modelRecord)
{
final IClientOrgAware clientOrg = create(modelRecord, IClientOrgAware.class);
final ClientId clientId = ClientId.ofRepoId(clientOrg.getAD_Client_ID()); | final ProviderResult providerResult = getDocumentSequenceInfo(modelRecord);
return createDocumentNoBuilder()
.setDocumentSequenceInfo(providerResult.getInfoOrNull())
.setClientId(clientId)
.setDocumentModel(modelRecord)
.setFailOnError(false);
}
private ProviderResult getDocumentSequenceInfo(@NonNull final Object modelRecord)
{
for (final ValueSequenceInfoProvider provider : additionalProviders)
{
final ProviderResult result = provider.computeValueInfo(modelRecord);
if (result.hasInfo())
{
return result;
}
}
return tableNameBasedProvider.computeValueInfo(modelRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilderFactory.java | 1 |
请完成以下Java代码 | private boolean process(final I_Fact_Acct_ActivityChangeRequest request)
{
// Already processed, shall not happen
if (request.isProcessed())
{
return false;
}
final IActivityAware activityAware = getDocLineActivityAwareOrNull(request);
if (activityAware == null)
{
// shall not happen
addLog("Skip {0} because it does not provide an activity", request);
return false;
}
//
// Update document line
final int activityIdToSet = request.getC_Activity_Override_ID();
activityAware.setC_Activity_ID(activityIdToSet);
InterfaceWrapperHelper.save(activityAware);
//
// Update all fact lines which are about our document line.
factAcctDAO.updateActivityForDocumentLine(getCtx(), request.getAD_Table_ID(), request.getRecord_ID(), request.getLine_ID(), activityIdToSet);
//
// Delete this request because it was processed
InterfaceWrapperHelper.delete(request);
return true;
}
private final Class<?> getDocLineClass(final int adTableId)
{
final String tableName = tableDAO.retrieveTableName(adTableId);
return headerTableName2lineModelClass.get(tableName);
}
private final IActivityAware getDocLineActivityAwareOrNull(final I_Fact_Acct_ActivityChangeRequest request) | {
final Class<?> lineClass = getDocLineClass(request.getAD_Table_ID());
if (lineClass == null)
{
addLog("Skip {0} because it's not supported", request);
return null;
}
final int lineId = request.getLine_ID();
if (lineId <= 0)
{
addLog("Skip {0} because it does not have the Line_ID set", request);
return null;
}
final Object line = InterfaceWrapperHelper.create(getCtx(), lineId, lineClass, ITrx.TRXNAME_ThreadInherited);
final IActivityAware activityAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(line, IActivityAware.class);
if (activityAware == null)
{
// no activity on line level
addLog("Skip {0} because it does not provide an activity", line);
return null;
}
return activityAware;
}
@VisibleForTesting
static interface IActivityAware
{
String COLUMNNAME_C_Activity_ID = "C_Activity_ID";
int getC_Activity_ID();
void setC_Activity_ID(final int activityId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\Fact_Acct_ActivityChangeRequest_Process.java | 1 |
请完成以下Java代码 | public int getLast()
{
return data[size - 1];
}
public void setLast(int value)
{
data[size - 1] = value;
}
public int pop()
{
return data[--size];
}
@Override
public void save(DataOutputStream out) throws IOException
{
out.writeInt(size);
for (int i = 0; i < size; i++)
{
out.writeInt(data[i]);
}
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
@Override
public boolean load(ByteArray byteArray)
{
if (byteArray == null)
{
return false;
}
size = byteArray.nextInt();
data = new int[size];
for (int i = 0; i < size; i++) | {
data[i] = byteArray.nextInt();
}
linearExpandFactor = byteArray.nextInt();
exponentialExpanding = byteArray.nextBoolean();
exponentialExpandFactor = byteArray.nextDouble();
return true;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
loseWeight();
out.writeInt(size);
out.writeObject(data);
out.writeInt(linearExpandFactor);
out.writeBoolean(exponentialExpanding);
out.writeDouble(exponentialExpandFactor);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
size = in.readInt();
data = (int[]) in.readObject();
linearExpandFactor = in.readInt();
exponentialExpanding = in.readBoolean();
exponentialExpandFactor = in.readDouble();
}
@Override
public String toString()
{
ArrayList<Integer> head = new ArrayList<Integer>(20);
for (int i = 0; i < Math.min(size, 20); ++i)
{
head.add(data[i]);
}
return head.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\IntArrayList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class AdviseRegionOnRegionAdviceEnabledProperty { }
@Conditional(PdxReadSerializedCondition.class)
static class AdviseRegionOnPdxReadSerializedCondition { }
}
static class PdxReadSerializedCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return isPdxReadSerializedEnabled(context.getEnvironment()) || isCachePdxReadSerializedEnabled();
}
private boolean isCachePdxReadSerializedEnabled() {
return SimpleCacheResolver.getInstance().resolve()
.filter(GemFireCache::getPdxReadSerialized)
.isPresent();
}
private boolean isPdxReadSerializedEnabled(@NonNull Environment environment) {
return Optional.ofNullable(environment)
.filter(env -> env.getProperty(PDX_READ_SERIALIZED_PROPERTY, Boolean.class, false))
.isPresent();
}
}
private static final boolean DEFAULT_EXPORT_ENABLED = false;
private static final Predicate<Environment> disableGemFireShutdownHookPredicate = environment ->
Optional.ofNullable(environment)
.filter(env -> env.getProperty(CacheDataImporterExporterReference.EXPORT_ENABLED_PROPERTY_NAME,
Boolean.class, DEFAULT_EXPORT_ENABLED))
.isPresent();
static abstract class AbstractDisableGemFireShutdownHookSupport {
boolean shouldDisableGemFireShutdownHook(@Nullable Environment environment) { | return disableGemFireShutdownHookPredicate.test(environment);
}
/**
* If we do not disable Apache Geode's {@link org.apache.geode.distributed.DistributedSystem} JRE/JVM runtime
* shutdown hook then the {@link org.apache.geode.cache.Region} is prematurely closed by the JRE/JVM shutdown hook
* before Spring's {@link org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor}s can do
* their work of exporting data from the {@link org.apache.geode.cache.Region} as JSON.
*/
void disableGemFireShutdownHook(@Nullable Environment environment) {
System.setProperty(GEMFIRE_DISABLE_SHUTDOWN_HOOK, Boolean.TRUE.toString());
}
}
static abstract class CacheDataImporterExporterReference extends AbstractCacheDataImporterExporter {
static final String EXPORT_ENABLED_PROPERTY_NAME =
AbstractCacheDataImporterExporter.CACHE_DATA_EXPORT_ENABLED_PROPERTY_NAME;
}
static class DisableGemFireShutdownHookCondition extends AbstractDisableGemFireShutdownHookSupport
implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return shouldDisableGemFireShutdownHook(context.getEnvironment());
}
}
public static class DisableGemFireShutdownHookEnvironmentPostProcessor
extends AbstractDisableGemFireShutdownHookSupport implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
if (shouldDisableGemFireShutdownHook(environment)) {
disableGemFireShutdownHook(environment);
}
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\DataImportExportAutoConfiguration.java | 2 |
请完成以下Java代码 | public Customer findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(customerRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public Customer findByTenantIdAndName(UUID tenantId, String name) {
return findCustomerByTenantIdAndTitle(tenantId, name).orElse(null);
}
@Override
public PageData<Customer> findByTenantId(UUID tenantId, PageLink pageLink) {
return findCustomersByTenantId(tenantId, pageLink);
}
@Override
public CustomerId getExternalIdByInternal(CustomerId internalId) {
return Optional.ofNullable(customerRepository.getExternalIdById(internalId.getId()))
.map(CustomerId::new).orElse(null);
}
@Override
public PageData<Customer> findCustomersWithTheSameTitle(PageLink pageLink) {
return DaoUtil.toPageData(
customerRepository.findCustomersWithTheSameTitle(DaoUtil.toPageable(pageLink))
);
}
@Override
public List<Customer> findCustomersByTenantIdAndIds(UUID tenantId, List<UUID> customerIds) {
return DaoUtil.convertDataList(customerRepository.findCustomersByTenantIdAndIdIn(tenantId, customerIds));
} | @Override
public PageData<Customer> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<CustomerFields> findNextBatch(UUID id, int batchSize) {
return customerRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) {
return customerRepository.findEntityInfosByNamePrefix(tenantId.getId(), name);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\customer\JpaCustomerDao.java | 1 |
请完成以下Java代码 | public void setCreated(DateTime created) {
this.created = created;
}
public DateTime getUpdated() {
return updated;
}
public void setUpdated(DateTime updated) {
this.updated = updated;
}
@Override
public int hashCode() {
int hash = 1;
if (id != null) {
hash = hash * 31 + id.hashCode();
}
if (firstName != null) { | hash = hash * 31 + firstName.hashCode();
}
if (lastName != null) {
hash = hash * 31 + lastName.hashCode();
}
return hash;
}
@Override
public boolean equals(Object obj) {
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
if (obj == this)
return true;
Person other = (Person) obj;
return this.hashCode() == other.hashCode();
}
} | repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Person.java | 1 |
请完成以下Java代码 | public class InOutCostsView_CreateMatchInv extends InOutCostsViewBasedProcess
{
private final MoneyService moneyService = SpringContextHolder.instance.getBean(MoneyService.class);
@Override
protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final ExplainedOptional<CreateMatchInvoiceRequest> optionalRequest = createMatchInvoiceRequest();
if (!optionalRequest.isPresent())
{
return ProcessPreconditionsResolution.rejectWithInternalReason(optionalRequest.getExplanation());
}
final CreateMatchInvoicePlan plan = orderCostService.createMatchInvoiceSimulation(optionalRequest.get());
final Amount invoicedAmtDiff = plan.getInvoicedAmountDiff().toAmount(moneyService::getCurrencyCodeByCurrencyId);
return ProcessPreconditionsResolution.accept().withCaptionMapper(captionMapper(invoicedAmtDiff));
}
@Nullable
private ProcessPreconditionsResolution.ProcessCaptionMapper captionMapper(@Nullable final Amount invoicedAmtDiff)
{
if (invoicedAmtDiff == null || invoicedAmtDiff.isZero())
{
return null;
}
else
{
return originalProcessCaption -> TranslatableStrings.builder()
.append(originalProcessCaption)
.append(" (Diff: ").append(invoicedAmtDiff).append(")")
.build();
}
} | protected String doIt()
{
final CreateMatchInvoiceRequest request = createMatchInvoiceRequest().orElseThrow();
orderCostService.createMatchInvoice(request);
invalidateView();
return MSG_OK;
}
private ExplainedOptional<CreateMatchInvoiceRequest> createMatchInvoiceRequest()
{
final ImmutableSet<InOutCostId> selectedInOutCostIds = getSelectedInOutCostIds();
if (selectedInOutCostIds.isEmpty())
{
return ExplainedOptional.emptyBecause("No selection");
}
return ExplainedOptional.of(
CreateMatchInvoiceRequest.builder()
.invoiceAndLineId(getView().getInvoiceLineId())
.inoutCostIds(selectedInOutCostIds)
.build());
}
private ImmutableSet<InOutCostId> getSelectedInOutCostIds()
{
final ImmutableList<InOutCostRow> rows = getSelectedRows();
return rows.stream().map(InOutCostRow::getInoutCostId).collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoice\match_inout_costs\InOutCostsView_CreateMatchInv.java | 1 |
请完成以下Java代码 | public void setCategory(String category) {
this.category = category;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public void setHasGraphicalNotation(boolean hasGraphicalNotation) {
this.isGraphicalNotationDefined = hasGraphicalNotation;
}
@Override
public void setDiagramResourceName(String diagramResourceName) {
this.diagramResourceName = diagramResourceName;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<IdentityLinkEntity> getIdentityLinks() {
if (!isIdentityLinksInitialized) {
definitionIdentityLinkEntities = CommandContextUtil.getCmmnEngineConfiguration().getIdentityLinkServiceConfiguration() | .getIdentityLinkService().findIdentityLinksByScopeDefinitionIdAndType(id, ScopeTypes.CMMN);
isIdentityLinksInitialized = true;
}
return definitionIdentityLinkEntities;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | public static final Nature fromString(String name)
{
Integer id = idMap.get(name);
if (id == null)
return null;
return values[id];
}
/**
* 创建自定义词性,如果已有该对应词性,则直接返回已有的词性
*
* @param name 字符串词性
* @return Enum词性
*/
public static final Nature create(String name)
{
Nature nature = fromString(name);
if (nature == null)
return new Nature(name); | return nature;
}
@Override
public String toString()
{
return name;
}
public int ordinal()
{
return ordinal;
}
public static Nature[] values()
{
return values;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\tag\Nature.java | 1 |
请完成以下Java代码 | public int getES_FTS_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID);
}
@Override
public void setES_FTS_Index_Queue_ID (final int ES_FTS_Index_Queue_ID)
{
if (ES_FTS_Index_Queue_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Index_Queue_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Index_Queue_ID, ES_FTS_Index_Queue_ID);
}
@Override
public int getES_FTS_Index_Queue_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Index_Queue_ID);
}
/**
* EventType AD_Reference_ID=541373
* Reference name: ES_FTS_Index_Queue_EventType
*/
public static final int EVENTTYPE_AD_Reference_ID=541373;
/** Update = U */
public static final String EVENTTYPE_Update = "U";
/** Delete = D */
public static final String EVENTTYPE_Delete = "D";
@Override
public void setEventType (final java.lang.String EventType)
{
set_ValueNoCheck (COLUMNNAME_EventType, EventType);
}
@Override
public java.lang.String getEventType()
{
return get_ValueAsString(COLUMNNAME_EventType);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override | public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessingTag (final @Nullable java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
@Override
public java.lang.String getProcessingTag()
{
return get_ValueAsString(COLUMNNAME_ProcessingTag);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Index_Queue.java | 1 |
请完成以下Java代码 | public Builder setC_BPartner_ID(final int bpartnerId)
{
setAttribute(VAR_C_BPartner_ID, bpartnerId);
return this;
}
public Builder setC_BPartner_Location_ID(final int bpartnerLocationId)
{
setAttribute(VAR_C_BPartner_Location_ID, bpartnerLocationId);
return this;
}
public Builder setUser(final I_AD_User user)
{
setAttribute(VAR_AD_User, user);
setAttribute(VAR_AD_User_ID, user != null ? user.getAD_User_ID() : null);
return this;
}
public void setCCUser(final I_AD_User ccUser)
{
setAttribute(VAR_CC_User, ccUser);
setAttribute(VAR_CC_User_ID, ccUser != null ? ccUser.getAD_User_ID() : null);
}
public Builder setEmail(final String email)
{
setAttribute(VAR_EMail, email);
return this;
}
public Builder setCCEmail(final String ccEmail)
{
setAttribute(VAR_CC_EMail, ccEmail);
return this;
}
public Builder setAD_Org_ID(final int adOrgId)
{
setAttribute(VAR_AD_Org_ID, adOrgId);
return this;
}
public Builder setCustomAttribute(final String attributeName, final Object value)
{
setAttribute(attributeName, value);
return this;
}
}
}
public interface SourceDocument
{
String NAME = "__SourceDocument";
default int getWindowNo()
{
return Env.WINDOW_None;
}
boolean hasFieldValue(String fieldName);
Object getFieldValue(String fieldName);
default int getFieldValueAsInt(final String fieldName, final int defaultValue)
{
final Object value = getFieldValue(fieldName);
return value != null ? (int)value : defaultValue;
}
@Nullable
default <T extends RepoIdAware> T getFieldValueAsRepoId(final String fieldName, final Function<Integer, T> idMapper)
{
final int id = getFieldValueAsInt(fieldName, -1);
if (id > 0)
{
return idMapper.apply(id);
}
else
{
return null;
}
}
static SourceDocument toSourceDocumentOrNull(final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof SourceDocument)
{ | return (SourceDocument)obj;
}
final PO po = getPO(obj);
return new POSourceDocument(po);
}
}
@AllArgsConstructor
private static final class POSourceDocument implements SourceDocument
{
@NonNull
private final PO po;
@Override
public boolean hasFieldValue(final String fieldName)
{
return po.get_ColumnIndex(fieldName) >= 0;
}
@Override
public Object getFieldValue(final String fieldName)
{
return po.get_Value(fieldName);
}
}
@AllArgsConstructor
private static final class GridTabSourceDocument implements SourceDocument
{
@NonNull
private final GridTab gridTab;
@Override
public boolean hasFieldValue(final String fieldName)
{
return gridTab.getField(fieldName) != null;
}
@Override
public Object getFieldValue(final String fieldName)
{
return gridTab.getValue(fieldName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java | 1 |
请完成以下Java代码 | public class UelExpressionCondition implements Condition {
protected Expression expression;
public UelExpressionCondition(Expression expression) {
this.expression = expression;
}
public boolean evaluate(String sequenceFlowId, DelegateExecution execution) {
Object result = expression.getValue(execution);
if (result == null) {
throw new ActivitiException(
"condition expression returns null (sequenceFlowId: " +
sequenceFlowId +
" execution: " +
execution +
")"
);
}
if (!(result instanceof Boolean)) { | throw new ActivitiException(
"condition expression returns non-Boolean (sequenceFlowId: " +
sequenceFlowId +
" execution: " +
execution +
"): " +
result +
" (" +
result.getClass().getName() +
")"
);
}
return (Boolean) result;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\UelExpressionCondition.java | 1 |
请完成以下Spring Boot application配置 | # HTTP
quarkus.http.test-port=8081
# REST
mp.openapi.scan.disable=true
quarkus.swagger-ui.urls.default=/openapi.yml
quarkus.jackson.property-naming-strategy=SNAKE_CASE
# CORS
quarkus.http.cors=true
quarkus.http.cors.origins=*
quarkus.http.cors.headers=origin, accept, authorization, content-type, x-requested-with
quarkus.http.cors.access-control-allow-credentials=true
quarkus.http.cors.methods=GET,PUT,POST
quarkus.http.cors.access-control-max-age=0
quarkus.tls.trust-all=true
# Database
%dev.quarkus.hibern | ate-orm.database.generation=update
# Messaging
mp.messaging.outgoing.todos.topic=todo-events
%test.quarkus.kafka.devservices.enabled=false
# Citrus-specific
%test.quarkus.arc.ignored-split-packages=org.citrusframework.* | repos\tutorials-master\quarkus-modules\quarkus-citrus\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void unCloseIt(final DocumentTableFields docFields)
{
final I_C_RfQ rfq = extractRfQ(docFields);
//
rfqEventDispacher.fireBeforeUnClose(rfq);
//
// Mark as completed
rfq.setDocStatus(X_C_RfQ.DOCSTATUS_Completed);
rfq.setDocAction(X_C_RfQ.DOCACTION_Close);
InterfaceWrapperHelper.save(rfq);
//
// UnClose RfQ Responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
if (!rfqBL.isClosed(rfqResponse))
{
continue;
}
rfqBL.unclose(rfqResponse);
}
//
rfqEventDispacher.fireAfterUnClose(rfq);
// Make sure it's saved
InterfaceWrapperHelper.save(rfq);
}
@Override
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{ | final I_C_RfQ rfq = extractRfQ(docFields);
//
// Void and delete all responses
for (final I_C_RfQResponse rfqResponse : rfqDAO.retrieveAllResponses(rfq))
{
voidAndDelete(rfqResponse);
}
rfq.setIsRfQResponseAccepted(false);
rfq.setDocAction(IDocument.ACTION_Complete);
rfq.setProcessed(false);
}
private void voidAndDelete(final I_C_RfQResponse rfqResponse)
{
// Prevent deleting/voiding an already closed RfQ response
if (rfqBL.isClosed(rfqResponse))
{
throw new RfQDocumentClosedException(rfqBL.getSummary(rfqResponse));
}
// TODO: FRESH-402 shall we throw exception if the rfqResponse was published?
rfqResponse.setProcessed(false);
InterfaceWrapperHelper.delete(rfqResponse);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\RfQDocumentHandler.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getActivityId() {
return activityId;
}
public String getActivityName() {
return activityName;
}
public String getActivityType() {
return activityType;
}
public String getActivityDescription() {
return activityDescription;
}
public String getParentId() {
return parentId;
}
public String getTenantId() {
return tenantId;
}
public boolean isRequired() {
return required;
}
public boolean isEnabled() {
return enabled;
}
public boolean isActive() {
return active;
} | public boolean isDisabled() {
return disabled;
}
public static CaseExecutionDto fromCaseExecution(CaseExecution caseExecution) {
CaseExecutionDto dto = new CaseExecutionDto();
dto.id = caseExecution.getId();
dto.caseInstanceId = caseExecution.getCaseInstanceId();
dto.caseDefinitionId = caseExecution.getCaseDefinitionId();
dto.activityId = caseExecution.getActivityId();
dto.activityName = caseExecution.getActivityName();
dto.activityType = caseExecution.getActivityType();
dto.activityDescription = caseExecution.getActivityDescription();
dto.parentId = caseExecution.getParentId();
dto.tenantId = caseExecution.getTenantId();
dto.required = caseExecution.isRequired();
dto.active = caseExecution.isActive();
dto.enabled = caseExecution.isEnabled();
dto.disabled = caseExecution.isDisabled();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\CaseExecutionDto.java | 1 |
请完成以下Spring Boot application配置 | # mongodb \u914D\u7F6E
spring.data.mongodb.uri=mongodb://localhost:27017/manage
# \u6D4B\u8BD5\u73AF\u5883\u53D6\u6D88thymeleaf\u7F13\u5B58
spring.thymeleaf.cache=false
# \u8BBE\u7F6Esession\u5931\u6548\u65F6\u95F4
server.session-timeout=60
spring.redis.database=0
# Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=192.168.0.71
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=6379
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=
# \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-active=8
# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-wait=-1
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\ | u5927\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.max-idle=8
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.min-idle=0
# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=0
spring.mail.host=smtp.126.com
spring.mail.username=youremail@126.com
spring.mail.password=yourpass
spring.mail.default-encoding=UTF-8 | repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public Builder streetAddress(String streetAddress) {
this.streetAddress = streetAddress;
return this;
}
/**
* Sets the city or locality.
* @param locality the city or locality
* @return the {@link Builder}
*/
public Builder locality(String locality) {
this.locality = locality;
return this;
}
/**
* Sets the state, province, prefecture, or region.
* @param region the state, province, prefecture, or region
* @return the {@link Builder}
*/
public Builder region(String region) {
this.region = region;
return this;
}
/**
* Sets the zip code or postal code.
* @param postalCode the zip code or postal code
* @return the {@link Builder}
*/
public Builder postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Sets the country.
* @param country the country
* @return the {@link Builder}
*/
public Builder country(String country) {
this.country = country; | return this;
}
/**
* Builds a new {@link DefaultAddressStandardClaim}.
* @return a {@link AddressStandardClaim}
*/
public AddressStandardClaim build() {
DefaultAddressStandardClaim address = new DefaultAddressStandardClaim();
address.formatted = this.formatted;
address.streetAddress = this.streetAddress;
address.locality = this.locality;
address.region = this.region;
address.postalCode = this.postalCode;
address.country = this.country;
return address;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\DefaultAddressStandardClaim.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Konst. Zusagbar (ATP) Wert.
@param FixedQtyAvailableToPromise Konst. Zusagbar (ATP) Wert */
@Override
public void setFixedQtyAvailableToPromise (int FixedQtyAvailableToPromise)
{
set_Value (COLUMNNAME_FixedQtyAvailableToPromise, Integer.valueOf(FixedQtyAvailableToPromise));
}
/** Get Konst. Zusagbar (ATP) Wert.
@return Konst. Zusagbar (ATP) Wert */
@Override
public int getFixedQtyAvailableToPromise ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_FixedQtyAvailableToPromise);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MSV3 Server.
@param MSV3_Server_ID MSV3 Server */
@Override
public void setMSV3_Server_ID (int MSV3_Server_ID)
{
if (MSV3_Server_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_Server_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_Server_ID, Integer.valueOf(MSV3_Server_ID));
}
/** Get MSV3 Server.
@return MSV3 Server */
@Override
public int getMSV3_Server_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Server_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Warehouse_PickingGroup getM_Warehouse_PickingGroup() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class);
}
@Override
public void setM_Warehouse_PickingGroup(org.compiere.model.I_M_Warehouse_PickingGroup M_Warehouse_PickingGroup)
{ | set_ValueFromPO(COLUMNNAME_M_Warehouse_PickingGroup_ID, org.compiere.model.I_M_Warehouse_PickingGroup.class, M_Warehouse_PickingGroup);
}
/** Set Kommissionier-Lagergruppe .
@param M_Warehouse_PickingGroup_ID Kommissionier-Lagergruppe */
@Override
public void setM_Warehouse_PickingGroup_ID (int M_Warehouse_PickingGroup_ID)
{
if (M_Warehouse_PickingGroup_ID < 1)
set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, null);
else
set_Value (COLUMNNAME_M_Warehouse_PickingGroup_ID, Integer.valueOf(M_Warehouse_PickingGroup_ID));
}
/** Get Kommissionier-Lagergruppe .
@return Kommissionier-Lagergruppe */
@Override
public int getM_Warehouse_PickingGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_PickingGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java-gen\de\metas\vertical\pharma\msv3\server\model\X_MSV3_Server.java | 1 |
请完成以下Java代码 | public static Optional<OrderLineId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static OrderLineId cast(@NonNull final RepoIdAware id)
{
return (OrderLineId)id;
}
public static int toRepoId(@Nullable final OrderLineId orderLineId)
{
return orderLineId != null ? orderLineId.getRepoId() : -1;
}
public static Set<Integer> toIntSet(final Collection<OrderLineId> orderLineIds)
{
return orderLineIds.stream().map(OrderLineId::getRepoId).collect(ImmutableSet.toImmutableSet()); | }
int repoId;
private OrderLineId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final OrderLineId id1, @Nullable final OrderLineId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineId.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Zebra_Config getAD_Zebra_Config()
{
return get_ValueAsPO(COLUMNNAME_AD_Zebra_Config_ID, org.compiere.model.I_AD_Zebra_Config.class);
}
@Override
public void setAD_Zebra_Config(final org.compiere.model.I_AD_Zebra_Config AD_Zebra_Config)
{
set_ValueFromPO(COLUMNNAME_AD_Zebra_Config_ID, org.compiere.model.I_AD_Zebra_Config.class, AD_Zebra_Config);
}
@Override
public void setAD_Zebra_Config_ID (final int AD_Zebra_Config_ID)
{
if (AD_Zebra_Config_ID < 1)
set_Value (COLUMNNAME_AD_Zebra_Config_ID, null);
else
set_Value (COLUMNNAME_AD_Zebra_Config_ID, AD_Zebra_Config_ID);
}
@Override
public int getAD_Zebra_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Zebra_Config_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setC_BP_PrintFormat_ID (final int C_BP_PrintFormat_ID)
{
if (C_BP_PrintFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, C_BP_PrintFormat_ID);
}
@Override
public int getC_BP_PrintFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_PrintFormat_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null); | else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
}
@Override
public void setDocumentCopies_Override (final int DocumentCopies_Override)
{
set_Value (COLUMNNAME_DocumentCopies_Override, DocumentCopies_Override);
}
@Override
public int getDocumentCopies_Override()
{
return get_ValueAsInt(COLUMNNAME_DocumentCopies_Override);
}
@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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_PrintFormat.java | 1 |
请完成以下Java代码 | public IHUContextProcessorExecutor createHUContextProcessorExecutor(final IContextAware context)
{
final IHUContext huContext = Services.get(IHUContextFactory.class).createMutableHUContextForProcessing(context);
return new HUContextProcessorExecutor(huContext);
}
@Override
public List<IHUTransactionCandidate> aggregateTransactions(final List<IHUTransactionCandidate> transactions)
{
final Map<ArrayKey, IHUTransactionCandidate> transactionsAggregateMap = new HashMap<>();
final List<IHUTransactionCandidate> notAggregated = new ArrayList<>();
for (final IHUTransactionCandidate trx : transactions)
{
if (trx.getCounterpart() != null)
{
// we don't want to aggregate paired trxCandidates because we want to discard the trxCandidates this method was called with.
// unless we don't have to, we don't want to delve into those intricacies...
notAggregated.add(trx);
}
// note that we use the ID if we can, because we don't want this to fail e.g. because of two different versions of the "same" VHU-item
final ArrayKey key = Util.mkKey(
// trxCandidate.getCounterpart(),
trx.getDate(),
trx.getHUStatus(),
// trxCandidate.getM_HU(), just delegates to HU_Item
trx.getM_HU_Item() == null ? -1 : trx.getM_HU_Item().getM_HU_Item_ID(),
trx.getLocatorId(),
trx.getProductId() == null ? -1 : trx.getProductId().getRepoId(),
// trxCandidate.getQuantity(),
trx.getReferencedModel() == null ? -1 : TableRecordReference.of(trx.getReferencedModel()),
// trxCandidate.getVHU(), just delegates to VHU_Item
trx.getVHU_Item() == null ? -1 : trx.getVHU_Item().getM_HU_Item_ID(),
trx.isSkipProcessing());
transactionsAggregateMap.merge(key,
trx,
(existingCand, newCand) -> { | final HUTransactionCandidate mergedCandidate = new HUTransactionCandidate(existingCand.getReferencedModel(),
existingCand.getM_HU_Item(),
existingCand.getVHU_Item(),
existingCand.getProductId(),
existingCand.getQuantity().add(newCand.getQuantity()),
existingCand.getDate(),
existingCand.getLocatorId(),
existingCand.getHUStatus());
if (existingCand.isSkipProcessing())
{
mergedCandidate.setSkipProcessing();
}
return mergedCandidate;
});
}
return ImmutableList.<IHUTransactionCandidate>builder()
.addAll(notAggregated)
.addAll(transactionsAggregateMap.values())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\hutransaction\impl\HUTrxBL.java | 1 |
请完成以下Java代码 | public static String getBeforeChangeWarning(final GridTab tab, final boolean newRecord)
{
final List<I_AD_Index_Table> indexes = getAffectedIndexes(tab, newRecord);
if (indexes.isEmpty())
{
return null;
}
// metas start: R.Craciunescu@metas.ro : 02280
final int rowCount = tab.getRowCount();
// metas end: R.Craciunescu@metas.ro : 02280
final StringBuilder msg = new StringBuilder();
for (final I_AD_Index_Table index : indexes)
{
if (Check.isEmpty(index.getBeforeChangeWarning()))
{
continue;
}
// metas start: R.Craciunescu@metas.ro : 02280
// if the new entry is the only row, there is nothing to be changed, so a before change warning is not needed.
if (rowCount == 1)
{
return null;
}
// metas end: R.Craciunescu@metas.ro : 02280
if (msg.length() > 0)
{
msg.append("\n");
}
msg.append(index.getBeforeChangeWarning());
}
return msg.toString();
}
private static final boolean isValueChanged(final GridTab tab, final String columnName,
final boolean newRecord)
{
final GridTable table = tab.getTableModel();
final int index = table.findColumn(columnName);
if (index == -1)
{
return false;
}
if (newRecord)
{
return true;
}
final Object valueOld = table.getOldValue(tab.getCurrentRow(), index);
if (valueOld == null)
{
return false;
}
final Object value = tab.getValue(columnName);
if (!valueOld.equals(value))
{
return true;
}
return false;
}
@Override
public String toString()
{ | final StringBuilder sb = new StringBuilder("MTableIndex[");
sb.append(get_ID()).append("-").append(getName()).append(
",AD_Table_ID=").append(getAD_Table_ID()).append("]");
return sb.toString();
}
private static class TableIndexesMap
{
private final ImmutableListMultimap<String, MIndexTable> indexesByTableName;
private final ImmutableMap<String, MIndexTable> indexesByNameUC;
public TableIndexesMap(final List<MIndexTable> indexes)
{
indexesByTableName = Multimaps.index(indexes, MIndexTable::getTableName);
indexesByNameUC = Maps.uniqueIndex(indexes, index -> index.getName().toUpperCase());
}
public ImmutableList<MIndexTable> getByTableName(@NonNull final String tableName)
{
return indexesByTableName.get(tableName);
}
public MIndexTable getByNameIgnoringCase(@NonNull final String name)
{
String nameUC = name.toUpperCase();
return indexesByNameUC.get(nameUC);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MIndexTable.java | 1 |
请完成以下Java代码 | private String convertLoginConfigToUrl() throws IOException {
String loginConfigPath;
try {
loginConfigPath = this.loginConfig.getFile().getAbsolutePath().replace(File.separatorChar, '/');
if (!loginConfigPath.startsWith("/")) {
loginConfigPath = "/" + loginConfigPath;
}
return new URL("file", "", loginConfigPath).toString();
}
catch (IOException ex) {
// SEC-1700: May be inside a jar
return this.loginConfig.getURL().toString();
}
}
/**
* Publishes the {@link JaasAuthenticationFailedEvent}. Can be overridden by
* subclasses for different functionality
* @param token The authentication token being processed
* @param ase The exception that caused the authentication failure
*/
@Override
protected void publishFailureEvent(UsernamePasswordAuthenticationToken token, AuthenticationException ase) {
// exists for passivity (the superclass does a null check before publishing)
getApplicationEventPublisher().publishEvent(new JaasAuthenticationFailedEvent(token, ase));
}
public Resource getLoginConfig() {
return this.loginConfig;
} | /**
* Set the JAAS login configuration file.
* @param loginConfig
*
* @see <a href=
* "https://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/JAASRefGuide.html">JAAS
* Reference</a>
*/
public void setLoginConfig(Resource loginConfig) {
this.loginConfig = loginConfig;
}
/**
* If set, a call to {@code Configuration#refresh()} will be made by
* {@code #configureJaas(Resource) } method. Defaults to {@code true}.
* @param refresh set to {@code false} to disable reloading of the configuration. May
* be useful in some environments.
* @see <a href="https://jira.springsource.org/browse/SEC-1320">SEC-1320</a>
*/
public void setRefreshConfigurationOnStartup(boolean refresh) {
this.refreshConfigurationOnStartup = refresh;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\jaas\JaasAuthenticationProvider.java | 1 |
请完成以下Java代码 | public synchronized void registerImportTable(final String importTableName)
{
importTableNames.add(importTableName);
registerProcessToImportTableNames(deleteImportDataProcessRegistration);
}
public synchronized void setDeleteImportDataProcessClass(@NonNull final Class<?> deleteImportDataProcessClass)
{
setProcessAndUpdate(deleteImportDataProcessRegistration, deleteImportDataProcessClass);
}
private void setProcessAndUpdate(
@NonNull final ImportTableRelatedProcess registration,
@NonNull final Class<?> processClass)
{
final AdProcessId processId;
try
{
processId = adProcessesRepo.retrieveProcessIdByClass(processClass);
}
catch (Exception ex)
{
logger.warn("Failed fetching process ID for {}. Skip", processClass, ex);
return;
}
registration.setProcessId(processId);
logger.info("{}: set process class: {} ({})", registration.getName(), processClass, registration.getProcessId());
registerProcessToImportTableNames(registration);
}
private void registerProcessToImportTableNames(@NonNull final ImportTableRelatedProcess registration)
{
if (registration.getProcessId() == null)
{
return;
}
for (final String importTableName : ImmutableSet.copyOf(this.importTableNames))
{
if (registration.hasTableName(importTableName))
{
continue;
}
registerRelatedProcessNoFail(importTableName, registration.getProcessId());
registration.addTableName(importTableName);
}
}
private void registerRelatedProcessNoFail(
@NonNull final String importTableName,
@NonNull final AdProcessId processId)
{
try
{
final IADTableDAO tablesRepo = Services.get(IADTableDAO.class); | final AdTableId importTableId = AdTableId.ofRepoId(tablesRepo.retrieveTableId(importTableName));
adProcessesRepo.registerTableProcess(RelatedProcessDescriptor.builder()
.processId(processId)
.tableId(importTableId)
.displayPlace(DisplayPlace.ViewActionsMenu)
.build());
}
catch (final Exception ex)
{
logger.warn("Cannot register process {} to {}. Skip", processId, importTableName, ex);
}
}
@ToString
private static class ImportTableRelatedProcess
{
@Getter
private final String name;
@Getter
private AdProcessId processId;
private final HashSet<String> registeredOnTableNames = new HashSet<>();
public ImportTableRelatedProcess(@NonNull final String name)
{
this.name = name;
}
public void setProcessId(@NonNull final AdProcessId processId)
{
if (this.processId != null && !Objects.equals(this.processId, processId))
{
throw new AdempiereException("Changing process from " + this.processId + " to " + processId + " is not allowed.");
}
this.processId = processId;
}
public boolean hasTableName(@NonNull final String tableName)
{
return registeredOnTableNames.contains(tableName);
}
public void addTableName(@NonNull final String tableName)
{
registeredOnTableNames.add(tableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportTablesRelatedProcessesRegistry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id private String id;
private String username;
@Column(name = "first_name") String firstname;
@Column(name = "last_name") String lastname;
// @OneToMany
// private List<Post> posts;
Instant registrationDate;
Instant lastSeen;
public User() {}
public User(String id, String username) {
this.id = id;
this.username = username;
}
public String getId() {
return id;
}
public String getUsername() {
return username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
} | public Instant getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Instant registrationDate) {
this.registrationDate = registrationDate;
}
public Instant getLastSeen() {
return lastSeen;
}
public void setLastSeen(Instant lastSeen) {
this.lastSeen = lastSeen;
}
// public List<Post> getPosts() {
// return posts;
// }
//
// public void setPosts(List<Post> posts) {
// this.posts = posts;
// }
@Override
public String toString() {
return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", firstname='" + firstname + '\''
+ ", lastname='" + lastname + '\'' + ", registrationDate=" + registrationDate + ", lastSeen=" + lastSeen +
// ", posts=" + posts +
'}';
}
} | repos\spring-data-examples-main\jpa\aot-optimization\src\main\java\example\springdata\aot\User.java | 2 |
请完成以下Java代码 | public void setTablePrefixIsSchema(boolean tablePrefixIsSchema) {
this.tablePrefixIsSchema = tablePrefixIsSchema;
}
public boolean isTablePrefixIsSchema() {
return tablePrefixIsSchema;
}
public List<Class<? extends Entity>> getInsertionOrder() {
return insertionOrder;
}
public void setInsertionOrder(List<Class<? extends Entity>> insertionOrder) {
this.insertionOrder = insertionOrder;
}
public List<Class<? extends Entity>> getDeletionOrder() {
return deletionOrder;
}
public void setDeletionOrder(List<Class<? extends Entity>> deletionOrder) {
this.deletionOrder = deletionOrder;
}
public Collection<Class<? extends Entity>> getImmutableEntities() {
return immutableEntities;
}
public void setImmutableEntities(Collection<Class<? extends Entity>> immutableEntities) {
this.immutableEntities = immutableEntities;
}
public void addLogicalEntityClassMapping(String logicalName, Class<?> entityClass) { | logicalNameToClassMapping.put(logicalName, entityClass);
}
public Map<String, Class<?>> getLogicalNameToClassMapping() {
return logicalNameToClassMapping;
}
public void setLogicalNameToClassMapping(Map<String, Class<?>> logicalNameToClassMapping) {
this.logicalNameToClassMapping = logicalNameToClassMapping;
}
public boolean isUsePrefixId() {
return usePrefixId;
}
public void setUsePrefixId(boolean usePrefixId) {
this.usePrefixId = usePrefixId;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\DbSqlSessionFactory.java | 1 |
请完成以下Java代码 | public static Integer findMajorityElementUsingMooreVoting(int[] nums) {
int majorityThreshold = nums.length / 2;
int candidate = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
candidate = nums[i];
count = 1;
} else if (candidate == nums[i]) {
count++;
} else {
count--;
}
System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]");
}
count = 0;
for (int num : nums) {
if (num == candidate) { | count++;
}
}
return count > majorityThreshold ? candidate : null;
}
public static void main(String[] args) {
int[] nums = { 2, 3, 2, 4, 2, 5, 2 };
Integer majorityElement = findMajorityElementUsingMooreVoting(nums);
if (majorityElement != null) {
System.out.println("Majority element with maximum occurrences: " + majorityElement);
} else {
System.out.println("No majority element found");
}
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\majorityelement\FindMajorityElement.java | 1 |
请完成以下Java代码 | public static String getStringFromInputStream(InputStream inputStream) throws IOException {
return getStringFromInputStream(inputStream, true);
}
/**
* Convert an {@link InputStream} to a {@link String}
*
* @param inputStream the {@link InputStream} to convert
* @param trim trigger if whitespaces are trimmed in the output
* @return the resulting {@link String}
* @throws IOException
*/
public static String getStringFromInputStream(InputStream inputStream, boolean trim) throws IOException {
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (trim) {
stringBuilder.append(line.trim());
} else {
stringBuilder.append(line).append("\n");
}
}
} finally {
closeSilently(bufferedReader);
}
return stringBuilder.toString();
}
/**
* Convert an {@link Reader} to a {@link String}
*
* @param reader the {@link Reader} to convert
* @return the resulting {@link String}
* @throws IOException
*/
public static String getStringFromReader(Reader reader) throws IOException {
return getStringFromReader(reader, true);
}
/**
* Convert an {@link Reader} to a {@link String} | *
* @param reader the {@link Reader} to convert
* @param trim trigger if whitespaces are trimmed in the output
* @return the resulting {@link String}
* @throws IOException
*/
public static String getStringFromReader(Reader reader, boolean trim) throws IOException {
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (trim) {
stringBuilder.append(line.trim());
} else {
stringBuilder.append(line).append("\n");
}
}
} finally {
closeSilently(bufferedReader);
}
return stringBuilder.toString();
}
public static Reader classpathResourceAsReader(String fileName) {
try {
File classpathFile = getClasspathFile(fileName);
return new FileReader(classpathFile);
} catch (FileNotFoundException e) {
throw LOG.fileNotFoundException(fileName, e);
}
}
public static Reader stringAsReader(String string) {
return new StringReader(string);
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\SpinIoUtil.java | 1 |
请完成以下Java代码 | public class LdapUtils {
/**
* 校验密码
*
* @param ldapPassword ldap 加密密码
* @param inputPassword 用户输入
* @return boolean
* @throws NoSuchAlgorithmException 加解密异常
*/
public static boolean verify(String ldapPassword, String inputPassword) throws NoSuchAlgorithmException {
// MessageDigest 提供了消息摘要算法,如 MD5 或 SHA,的功能,这里LDAP使用的是SHA-1
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 取出加密字符
if (ldapPassword.startsWith("{SSHA}")) {
ldapPassword = ldapPassword.substring(6);
} else if (ldapPassword.startsWith("{SHA}")) {
ldapPassword = ldapPassword.substring(5);
}
// 解码BASE64
byte[] ldapPasswordByte = Base64.decode(ldapPassword);
byte[] shaCode;
byte[] salt;
// 前20位是SHA-1加密段,20位后是最初加密时的随机明文
if (ldapPasswordByte.length <= 20) {
shaCode = ldapPasswordByte;
salt = new byte[0];
} else {
shaCode = new byte[20];
salt = new byte[ldapPasswordByte.length - 20];
System.arraycopy(ldapPasswordByte, 0, shaCode, 0, 20);
System.arraycopy(ldapPasswordByte, 20, salt, 0, salt.length);
} | // 把用户输入的密码添加到摘要计算信息
md.update(inputPassword.getBytes());
// 把随机明文添加到摘要计算信息
md.update(salt);
// 按SSHA把当前用户密码进行计算
byte[] inputPasswordByte = md.digest();
// 返回校验结果
return MessageDigest.isEqual(shaCode, inputPasswordByte);
}
/**
* Ascii转换为字符串
*
* @param value Ascii串
* @return 字符串
*/
public static String asciiToString(String value) {
StringBuilder sbu = new StringBuilder();
String[] chars = value.split(",");
for (String aChar : chars) {
sbu.append((char) Integer.parseInt(aChar));
}
return sbu.toString();
}
} | repos\spring-boot-demo-master\demo-ldap\src\main\java\com\xkcoding\ldap\util\LdapUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getShippedDate()
{
return shippedDate;
}
public void setShippedDate(String shippedDate)
{
this.shippedDate = shippedDate;
}
public ShippingFulfillment shippingCarrierCode(String shippingCarrierCode)
{
this.shippingCarrierCode = shippingCarrierCode;
return this;
}
/**
* The eBay code identifying the shipping carrier for this fulfillment. This field is returned if available. Note: The Trading API's ShippingCarrierCodeType enumeration type contains the most current list of eBay shipping carrier codes and the countries served by each carrier. See ShippingCarrierCodeType.
*
* @return shippingCarrierCode
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The eBay code identifying the shipping carrier for this fulfillment. This field is returned if available. Note: The Trading API's ShippingCarrierCodeType enumeration type contains the most current list of eBay shipping carrier codes and the countries served by each carrier. See ShippingCarrierCodeType.")
public String getShippingCarrierCode()
{
return shippingCarrierCode;
}
public void setShippingCarrierCode(String shippingCarrierCode)
{
this.shippingCarrierCode = shippingCarrierCode;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
ShippingFulfillment shippingFulfillment = (ShippingFulfillment)o;
return Objects.equals(this.fulfillmentId, shippingFulfillment.fulfillmentId) &&
Objects.equals(this.lineItems, shippingFulfillment.lineItems) &&
Objects.equals(this.shipmentTrackingNumber, shippingFulfillment.shipmentTrackingNumber) &&
Objects.equals(this.shippedDate, shippingFulfillment.shippedDate) &&
Objects.equals(this.shippingCarrierCode, shippingFulfillment.shippingCarrierCode);
}
@Override
public int hashCode()
{
return Objects.hash(fulfillmentId, lineItems, shipmentTrackingNumber, shippedDate, shippingCarrierCode);
}
@Override | public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class ShippingFulfillment {\n");
sb.append(" fulfillmentId: ").append(toIndentedString(fulfillmentId)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" shipmentTrackingNumber: ").append(toIndentedString(shipmentTrackingNumber)).append("\n");
sb.append(" shippedDate: ").append(toIndentedString(shippedDate)).append("\n");
sb.append(" shippingCarrierCode: ").append(toIndentedString(shippingCarrierCode)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\ShippingFulfillment.java | 2 |
请完成以下Java代码 | public class AstParameters extends AstRightValue {
private final List<AstNode> nodes;
public AstParameters(List<AstNode> nodes) {
this.nodes = nodes;
}
@Override
public Object[] eval(Bindings bindings, ELContext context) {
Object[] result = new Object[nodes.size()];
for (int i = 0; i < nodes.size(); i++) {
result[i] = nodes.get(i).eval(bindings, context);
}
return result;
}
@Override
public String toString() {
return "(...)";
} | @Override
public void appendStructure(StringBuilder builder, Bindings bindings) {
builder.append("(");
for (int i = 0; i < nodes.size(); i++) {
if (i > 0) {
builder.append(", ");
}
nodes.get(i).appendStructure(builder, bindings);
}
builder.append(")");
}
public int getCardinality() {
return nodes.size();
}
public AstNode getChild(int i) {
return nodes.get(i);
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstParameters.java | 1 |
请完成以下Java代码 | public class JSONObjectIterator {
private Map<String, Object> keyValuePairs;
public JSONObjectIterator() {
keyValuePairs = new HashMap<>();
}
public void handleValue(String key, Object value) {
if (value instanceof JSONArray) {
handleJSONArray(key, (JSONArray) value);
} else if (value instanceof JSONObject) {
handleJSONObject((JSONObject) value);
}
keyValuePairs.put(key, value);
}
public void handleJSONObject(JSONObject jsonObject) {
Iterator<String> jsonObjectIterator = jsonObject.keys();
jsonObjectIterator.forEachRemaining(key -> {
Object value = jsonObject.get(key); | handleValue(key, value);
});
}
public void handleJSONArray(String key, JSONArray jsonArray) {
Iterator<Object> jsonArrayIterator = jsonArray.iterator();
jsonArrayIterator.forEachRemaining(element -> {
handleValue(key, element);
});
}
public Map<String, Object> getKeyValuePairs() {
return keyValuePairs;
}
public void setKeyValuePairs(Map<String, Object> keyValuePairs) {
this.keyValuePairs = keyValuePairs;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\iterate\JSONObjectIterator.java | 1 |
请完成以下Java代码 | public class ExecuteUpdateSQL extends JavaProcess
{
@Override
protected String doIt()
{
final String sqlParsed = StringExpressionCompiler.instance
.compile(getSql())
.evaluate(getEvalContext(), OnVariableNotFound.Fail);
final Stopwatch stopwatch = Stopwatch.createStarted();
final String msg;
final List<String> warningMessages;
addLog("Executing: " + sqlParsed);
if (!sqlParsed.trim().toUpperCase().startsWith("SELECT"))
{
final SQLUpdateResult sqlUpdateResult = DB.executeUpdateWithWarningEx(sqlParsed, ITrx.TRXNAME_ThreadInherited);
stopwatch.stop();
msg = "Result: " + sqlUpdateResult.getReturnedValue() + "; Runtime: " + stopwatch;
warningMessages = sqlUpdateResult.getWarningMessages();
}
else
{
// assuming that it is a select
final SQLValueStringResult sqlValueStringResult = DB.getSQLValueStringWithWarningEx(get_TrxName(), sqlParsed);
stopwatch.stop();
msg = "Runtime: " + stopwatch;
warningMessages = sqlValueStringResult.getWarningMessages();
}
final boolean isLogWarning = getProcessInfo().isLogWarning();
if (isLogWarning)
{
addLog(warningMessages, msg);
}
else
{
addLog(msg);
}
return "@Success@: " + msg;
}
private String getSql()
{
// the rawSql will be transformed into a one-liner, so it's important to make sure that it will work even without line breaks
final String rawSql = getProcessInfo()
.getSQLStatement()
.orElseThrow(() -> new AdempiereException("@FillMandatory@ @SQLStatement@"));
return rawSql
.replaceAll("--.*[\r\n\t]", "") // remove one-line-comments (comments within /* and */ are OK)
.replaceAll("[\r\n\t]", " "); // replace line-breaks with spaces
} | private Evaluatee getEvalContext()
{
final List<Evaluatee> contexts = new ArrayList<>();
//
// 1: Add process parameters
contexts.add(Evaluatees.ofRangeAwareParams(getParameterAsIParams()));
//
// 2: underlying record
final String recordTableName = getTableName();
final int recordId = getRecord_ID();
if (recordTableName != null && recordId > 0)
{
final TableRecordReference recordRef = TableRecordReference.of(recordTableName, recordId);
final Evaluatee evalCtx = Evaluatees.ofTableRecordReference(recordRef);
if (evalCtx != null)
{
contexts.add(evalCtx);
}
}
//
// 3: global context
contexts.add(Evaluatees.ofCtx(getCtx()));
return Evaluatees.compose(contexts);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ExecuteUpdateSQL.java | 1 |
请完成以下Java代码 | public boolean isAvailableForBPartnerAndLocation(
@NonNull final I_M_PickingSlot pickingSlot,
final BPartnerId bpartnerId,
@Nullable final BPartnerLocationId bpartnerLocationId)
{
return PickingSlotUtils.isAvailableForBPartnerAndLocation(pickingSlot, bpartnerId, bpartnerLocationId);
}
@Override
public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.getPickingSlotIdAndCaption(pickingSlotId);
}
@Override
public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final PickingSlotQuery query)
{
return pickingSlotDAO.retrievePickingSlotIdAndCaptions(query);
}
@Override
public QRCodePDFResource createQRCodesPDF(@NonNull final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions)
{
Check.assumeNotEmpty(pickingSlotIdAndCaptions, "pickingSlotIdAndCaptions is not empty");
final ImmutableList<PrintableQRCode> qrCodes = pickingSlotIdAndCaptions.stream()
.map(PickingSlotQRCode::ofPickingSlotIdAndCaption)
.map(PickingSlotQRCode::toPrintableQRCode)
.collect(ImmutableList.toImmutableList());
final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class);
return globalQRCodeService.createPDF(qrCodes);
}
@Override | public boolean isAvailableForAnyBPartner(@NonNull final PickingSlotId pickingSlotId)
{
return isAvailableForAnyBPartner(pickingSlotDAO.getById(pickingSlotId));
}
@NonNull
public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.getById(pickingSlotId);
}
@Override
public boolean isPickingRackSystem(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotDAO.isPickingRackSystem(pickingSlotId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotBL.java | 1 |
请完成以下Java代码 | public boolean save() {
return po.save(); // save
}
/**
* Update Value or create new record.
* To reload call load() - not updated
* @param trxName transaction
* @return true if saved
*/
public boolean save(String trxName) {
return po.save(trxName); // save
}
/**
* Is there a Change to be saved?
* @return true if record changed
*/
public boolean is_Changed() {
return po.is_Changed(); // is_Change
}
/**
* Create Single/Multi Key Where Clause
* @param withValues if true uses actual values otherwise ?
* @return where clause
*/
public String get_WhereClause(boolean withValues) {
return po.get_WhereClause(withValues); // getWhereClause
}
/**************************************************************************
* Delete Current Record
* @param force delete also processed records
* @return true if deleted
*/
public boolean delete(boolean force) {
return po.delete(force); // delete
}
/**
* Delete Current Record
* @param force delete also processed records
* @param trxName transaction
*/
public boolean delete(boolean force, String trxName) {
return po.delete(force, trxName); // delete
}
/**************************************************************************
* Lock it.
* @return true if locked
*/
public boolean lock() {
return po.lock(); // lock
} | /**
* UnLock it
* @return true if unlocked (false only if unlock fails)
*/
public boolean unlock(String trxName) {
return po.unlock(trxName); // unlock
}
/**
* Set Trx
* @param trxName transaction
*/
public void set_TrxName(String trxName) {
po.set_TrxName(trxName); // setTrx
}
/**
* Get Trx
* @return transaction
*/
public String get_TrxName() {
return po.get_TrxName(); // getTrx
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\wrapper\AbstractPOWrapper.java | 1 |
请完成以下Java代码 | public static MSV3ServerRequest requestAll()
{
return ALL;
}
public static MSV3ServerRequest requestConfig()
{
return CONFIG;
}
private static final MSV3ServerRequest ALL = MSV3ServerRequest.builder()
.requestAllUsers(true)
.requestAllStockAvailabilities(true)
.build();
private static final MSV3ServerRequest CONFIG = MSV3ServerRequest.builder()
.requestAllUsers(true)
.requestAllStockAvailabilities(false)
.build(); | boolean requestAllUsers;
boolean requestAllStockAvailabilities;
@JsonCreator
private MSV3ServerRequest(
@JsonProperty("requestAllUsers") final boolean requestAllUsers,
@JsonProperty("requestAllStockAvailabilities") final boolean requestAllStockAvailabilities)
{
this.requestAllUsers = requestAllUsers;
this.requestAllStockAvailabilities = requestAllStockAvailabilities;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\protocol\MSV3ServerRequest.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws InterruptedException {
String target = "localhost:8980";
if (args.length > 0) {
target = args[0];
}
ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
.usePlaintext()
.build();
try {
StockClient client = new StockClient(channel);
client.serverSideStreamingListOfStockPrices();
client.clientSideStreamingGetStatisticsOfStocks(); | client.bidirectionalStreamingGetListsStockQuotes();
} finally {
channel.shutdownNow()
.awaitTermination(5, TimeUnit.SECONDS);
}
}
private void initializeStocks() {
this.stocks = Arrays.asList(Stock.newBuilder().setTickerSymbol("AU").setCompanyName("Auburn Corp").setDescription("Aptitude Intel").build()
, Stock.newBuilder().setTickerSymbol("BAS").setCompanyName("Bassel Corp").setDescription("Business Intel").build()
, Stock.newBuilder().setTickerSymbol("COR").setCompanyName("Corvine Corp").setDescription("Corporate Intel").build()
, Stock.newBuilder().setTickerSymbol("DIA").setCompanyName("Dialogic Corp").setDescription("Development Intel").build()
, Stock.newBuilder().setTickerSymbol("EUS").setCompanyName("Euskaltel Corp").setDescription("English Intel").build());
}
} | repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\streaming\StockClient.java | 1 |
请完成以下Java代码 | public void onCreate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) {
if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_CREATE, variableInstance) && !variableInstance.isTransient()) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricVariableCreateEvt(variableInstance, sourceScope);
}
});
}
}
@Override
public void onDelete(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) {
if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_DELETE, variableInstance) && !variableInstance.isTransient()) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricVariableDeleteEvt(variableInstance, sourceScope);
} | });
}
}
@Override
public void onUpdate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) {
if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_UPDATE, variableInstance) && !variableInstance.isTransient()) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricVariableUpdateEvt(variableInstance, sourceScope);
}
});
}
}
protected HistoryLevel getHistoryLevel() {
return Context.getProcessEngineConfiguration().getHistoryLevel();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceHistoryListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Address {
@Id
@GeneratedValue
private Long id;
private String street;
private String city;
private String postCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
} | public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
} | repos\tutorials-master\persistence-modules\deltaspike\src\main\java\baeldung\model\Address.java | 2 |
请完成以下Java代码 | public String getErrorMessage() {
return typedValueField.getErrorMessage();
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id | + ", processDefinitionKey=" + processDefinitionKey
+ ", processDefinitionId=" + processDefinitionId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", executionId=" + executionId
+ ", tenantId=" + tenantId
+ ", activityInstanceId=" + activityInstanceId
+ ", caseDefinitionKey=" + caseDefinitionKey
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", caseExecutionId=" + caseExecutionId
+ ", name=" + name
+ ", createTime=" + createTime
+ ", revision=" + revision
+ ", serializerName=" + getSerializerName()
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", state=" + state
+ ", byteArrayId=" + getByteArrayId()
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricVariableInstanceEntity.java | 1 |
请完成以下Java代码 | public boolean hasActiveSessions()
{
return !activeSessions.isEmpty();
}
/* package */void addNotification(@NonNull final UserNotification notification)
{
final UserId adUserId = getUserId();
Check.assume(notification.getRecipientUserId() == adUserId.getRepoId(), "notification's recipient user ID shall be {}: {}", adUserId, notification);
final JSONNotification jsonNotification = JSONNotification.of(notification, jsonOptions);
fireEventOnWebsocket(JSONNotificationEvent.eventNew(jsonNotification, getUnreadCount()));
}
public void markAsRead(final String notificationId)
{
notificationsRepo.markAsReadById(Integer.parseInt(notificationId));
fireEventOnWebsocket(JSONNotificationEvent.eventRead(notificationId, getUnreadCount()));
}
public void markAllAsRead()
{
logger.trace("Marking all notifications as read (if any) for {}...", this);
notificationsRepo.markAllAsReadByUserId(getUserId());
fireEventOnWebsocket(JSONNotificationEvent.eventReadAll());
}
public int getUnreadCount()
{
return notificationsRepo.getUnreadCountByUserId(getUserId());
} | public void setLanguage(@NonNull final String adLanguage)
{
this.jsonOptions = jsonOptions.withAdLanguage(adLanguage);
}
public void delete(final String notificationId)
{
notificationsRepo.deleteById(Integer.parseInt(notificationId));
fireEventOnWebsocket(JSONNotificationEvent.eventDeleted(notificationId, getUnreadCount()));
}
public void deleteAll()
{
notificationsRepo.deleteAllByUserId(getUserId());
fireEventOnWebsocket(JSONNotificationEvent.eventDeletedAll());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\UserNotificationsQueue.java | 1 |
请完成以下Java代码 | public void updateDeliveryDayAllocFromModel(
final de.metas.tourplanning.model.I_M_DeliveryDay_Alloc deliveryDayAlloc,
final IDeliveryDayAllocable deliveryDayAllocable)
{
// Services
final IShipmentScheduleDeliveryDayBL shipmentScheduleDeliveryDayBL = Services.get(IShipmentScheduleDeliveryDayBL.class);
//
// Get underlying shipment schedule
final I_M_ShipmentSchedule huShipmentSchedule = shipmentScheduleDeliveryDayBL
.getShipmentScheduleOrNull(deliveryDayAllocable, I_M_ShipmentSchedule.class);
if (huShipmentSchedule == null)
{
// not applicable for our model
return;
}
//
// Get HU's version of delivery day allocation
final I_M_DeliveryDay_Alloc huDeliveryDayAlloc = InterfaceWrapperHelper.create(deliveryDayAlloc, I_M_DeliveryDay_Alloc.class);
//
// Copy current HU Quantities from shipment schedule to delivery day allocation
HUDeliveryQuantitiesHelper.copy(huDeliveryDayAlloc, huShipmentSchedule);
}
@Override
public void updateDeliveryDayWhenAllocationChanged(
final de.metas.tourplanning.model.I_M_DeliveryDay deliveryDay,
final de.metas.tourplanning.model.I_M_DeliveryDay_Alloc deliveryDayAlloc,
final de.metas.tourplanning.model.I_M_DeliveryDay_Alloc deliveryDayAllocOld)
{
final I_M_DeliveryDay huDeliveryDay = InterfaceWrapperHelper.create(deliveryDay, I_M_DeliveryDay.class);
//
// Get Old Qtys from M_DeliveryDay_Alloc
I_M_DeliveryDay_Alloc qtysToRemove = InterfaceWrapperHelper.create(deliveryDayAllocOld, I_M_DeliveryDay_Alloc.class);
if (qtysToRemove != null && !qtysToRemove.isActive())
{
qtysToRemove = null;
}
//
// Get New Qtys from M_DeliveryDay_Alloc
I_M_DeliveryDay_Alloc qtysToAdd = InterfaceWrapperHelper.create(deliveryDayAlloc, I_M_DeliveryDay_Alloc.class);
if (qtysToAdd != null && !qtysToAdd.isActive())
{
qtysToAdd = null;
}
// Adjust Delivery Day's quantities | HUDeliveryQuantitiesHelper.adjust(huDeliveryDay, qtysToRemove, qtysToAdd);
}
@Override
public void updateTourInstanceWhenDeliveryDayChanged(
final de.metas.tourplanning.model.I_M_Tour_Instance tourInstance,
final de.metas.tourplanning.model.I_M_DeliveryDay deliveryDay,
final de.metas.tourplanning.model.I_M_DeliveryDay deliveryDayOld)
{
final I_M_Tour_Instance huTourInstance = InterfaceWrapperHelper.create(tourInstance, I_M_Tour_Instance.class);
//
// Get Old Qtys from M_DeliveryDay
I_M_DeliveryDay qtysToRemove = InterfaceWrapperHelper.create(deliveryDayOld, I_M_DeliveryDay.class);
if (qtysToRemove != null && !qtysToRemove.isActive())
{
qtysToRemove = null;
}
//
// Get New Qtys from M_DeliveryDay_Alloc
I_M_DeliveryDay qtysToAdd = InterfaceWrapperHelper.create(deliveryDay, I_M_DeliveryDay.class);
if (qtysToAdd != null && !qtysToAdd.isActive())
{
qtysToAdd = null;
}
// Adjust Tour Instance's quantities
HUDeliveryQuantitiesHelper.adjust(huTourInstance, qtysToRemove, qtysToAdd);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\tourplanning\spi\impl\HUShipmentScheduleDeliveryDayHandler.java | 1 |
请完成以下Spring Boot application配置 | # DataSource Config
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.12.128:3306/world
username: root
password: 123456
mybatis- | plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl | repos\spring-boot-quick-master\quick-mybatis-druid\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ShipperMappingConfigRepository
{
@VisibleForTesting
public static ShipperMappingConfigRepository newInstanceForUnitTesting()
{
Adempiere.assertUnitTestMode();
return new ShipperMappingConfigRepository();
}
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, ShipperMappingConfigList> cache = CCache.<Integer, ShipperMappingConfigList>builder()
.tableName(I_M_Shipper_Mapping_Config.Table_Name)
.build();
public ShipperMappingConfigList getByShipperId(@NonNull final ShipperId shipperId)
{
return getList().subsetOf(shipperId);
}
private ShipperMappingConfigList getList()
{
//noinspection DataFlowIssue
return cache.getOrLoad(0, this::retrieveList);
}
private ShipperMappingConfigList retrieveList()
{
return ShipperMappingConfigList.ofCollection(queryBL.createQueryBuilder(I_M_Shipper_Mapping_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(ShipperMappingConfigRepository::fromRecord) | .collect(Collectors.toList()));
}
private static ShipperMappingConfig fromRecord(@NonNull final I_M_Shipper_Mapping_Config record)
{
return ShipperMappingConfig.builder()
.id(ShipperMappingConfigId.ofRepoId(record.getM_Shipper_Mapping_Config_ID()))
.shipperId(ShipperId.ofRepoId(record.getM_Shipper_ID()))
.seqNo(SeqNo.ofInt(record.getSeqNo()))
.carrierProductId(CarrierProductId.ofRepoIdOrNull(record.getCarrier_Product_ID()))
.attributeType(AttributeType.ofCode(record.getMappingAttributeType()))
.attributeKey(record.getMappingAttributeKey())
.attributeValue(AttributeValue.ofCode(record.getMappingAttributeValue()))
.groupKey(record.getMappingGroupKey())
.mappingRule(MappingRule.ofNullableCode(record.getMappingRule()))
.mappingRuleValue(record.getMappingRuleValue())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\mapping\ShipperMappingConfigRepository.java | 2 |
请完成以下Java代码 | public ItemControl getItemControl() {
return itemControlChild.getChild(this);
}
public void setItemControl(ItemControl itemControl) {
itemControlChild.setChild(this, itemControl);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItem.class, CMMN_ELEMENT_PLAN_ITEM)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<PlanItem>() {
public PlanItem newInstance(ModelTypeInstanceContext instanceContext) {
return new PlanItemImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
planItemDefinitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF)
.idAttributeReference(PlanItemDefinition.class)
.build();
entryCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ENTRY_CRITERIA_REFS)
.namespace(CMMN10_NS)
.idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class)
.build();
exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS)
.namespace(CMMN10_NS) | .idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
itemControlChild = sequenceBuilder.element(ItemControl.class)
.build();
entryCriterionCollection = sequenceBuilder.elementCollection(EntryCriterion.class)
.build();
exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemImpl.java | 1 |
请完成以下Java代码 | public ImmutableList<DhlCustomDeliveryDataDetail> getDetails()
{
return ImmutableList.copyOf(details);
}
@NonNull
public DhlCustomDeliveryDataDetail getDetailByPackageId(final PackageId packageId)
{
//noinspection OptionalGetWithoutIsPresent
return details.stream()
.filter(it -> Objects.equals(it.getPackageId(), packageId))
.findFirst()
.get();
}
@NonNull
public DhlCustomDeliveryDataDetail getDetailBySequenceNumber(@NonNull final DhlSequenceNumber sequenceNumber)
{
//noinspection OptionalGetWithoutIsPresent
return details.stream()
.filter(it -> it.getSequenceNumber().equals(sequenceNumber))
.findFirst()
.get(); | }
@NonNull
public DhlCustomDeliveryData withDhlCustomDeliveryDataDetails(@Nullable final ImmutableList<DhlCustomDeliveryDataDetail> details)
{
if (details == null)
{
return this;
}
return toBuilder()
.clearDetails()
.details(details)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\model\DhlCustomDeliveryData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ImmutableShipmentScheduleSegment implements IShipmentScheduleSegment
{
public static ImmutableShipmentScheduleSegment copyOf(@NonNull final IShipmentScheduleSegment from)
{
return from instanceof ImmutableShipmentScheduleSegment
? (ImmutableShipmentScheduleSegment)from
: new ImmutableShipmentScheduleSegment(from);
}
Set<Integer> productIds;
Set<Integer> bpartnerIds;
Set<Integer> billBPartnerIds;
Set<Integer> locatorIds;
Set<ShipmentScheduleAttributeSegment> attributes;
@Builder(toBuilder = true)
private ImmutableShipmentScheduleSegment(
@NonNull @Singular final Set<Integer> productIds,
@NonNull @Singular final Set<Integer> bpartnerIds,
@NonNull @Singular final Set<Integer> billBPartnerIds,
@NonNull @Singular final Set<Integer> locatorIds,
@NonNull @Singular final Set<ShipmentScheduleAttributeSegment> attributes)
{
this.productIds = Collections.unmodifiableSet(productIds);
this.bpartnerIds = Collections.unmodifiableSet(bpartnerIds);
this.billBPartnerIds = Collections.unmodifiableSet(billBPartnerIds);
this.locatorIds = Collections.unmodifiableSet(locatorIds);
this.attributes = Collections.unmodifiableSet(attributes);
}
private ImmutableShipmentScheduleSegment(final IShipmentScheduleSegment from)
{
this.productIds = Collections.unmodifiableSet(from.getProductIds());
this.bpartnerIds = Collections.unmodifiableSet(from.getBpartnerIds());
this.billBPartnerIds = Collections.unmodifiableSet(from.getBillBPartnerIds());
this.locatorIds = Collections.unmodifiableSet(from.getLocatorIds());
this.attributes = Collections.unmodifiableSet(from.getAttributes());
} | public static class ImmutableShipmentScheduleSegmentBuilder
{
public ImmutableShipmentScheduleSegmentBuilder anyBPartner()
{
if (bpartnerIds != null)
{
bpartnerIds.clear();
}
bpartnerId(ANY);
return this;
}
public ImmutableShipmentScheduleSegmentBuilder anyProduct()
{
if (productIds != null)
{
productIds.clear();
}
productId(ANY);
return this;
}
public ImmutableShipmentScheduleSegmentBuilder anyLocator()
{
if (locatorIds != null)
{
locatorIds.clear();
}
locatorId(ANY);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\segments\ImmutableShipmentScheduleSegment.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public UserDetailsService myUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
String[][] usersGroupsAndRoles = {
{ "bob", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "john", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "hannah", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam" },
{ "other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam" },
{ "system", "password", "ROLE_ACTIVITI_USER" },
{ "admin", "password", "ROLE_ACTIVITI_ADMIN" },
};
for (String[] user : usersGroupsAndRoles) {
List<String> authoritiesStrings = asList(Arrays.copyOfRange(user, 2, user.length));
logger.info(
"> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]"
);
inMemoryUserDetailsManager.createUser(
new User(
user[0],
passwordEncoder().encode(user[1]), | authoritiesStrings
.stream()
.map(s -> new SimpleGrantedAuthority(s))
.collect(Collectors.toList())
)
);
}
return inMemoryUserDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\Activiti-develop\activiti-examples\activiti-api-basic-full-example-bean\src\main\java\org\activiti\examples\DemoApplicationConfiguration.java | 2 |
请完成以下Java代码 | public class OrderDto {
private String customerName;
private String customerCity;
private String customerZipCode;
private String productName;
private double productPrice;
public String getCustomerZipCode() {
return customerZipCode;
}
public void setCustomerZipCode(String customerZipCode) {
this.customerZipCode = customerZipCode;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerCity() { | return customerCity;
}
public void setCustomerCity(String customerCity) {
this.customerCity = customerCity;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getProductPrice() {
return productPrice;
}
public void setProductPrice(double productPrice) {
this.productPrice = productPrice;
}
} | repos\tutorials-master\mapstruct-2\src\main\java\com\baeldung\nested\entity\OrderDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Pac4jConfig {
/**
* cas服务地址
*/
@Value("${cas.server.url}")
private String casServerUrl;
/**
* 客户端项目地址
*/
@Value("${cas.project.url}")
private String projectUrl;
/** 相当于一个标志,可以随意 */
@Value("${cas.client-name}")
private String clientName;
/**
* pac4j配置
* @param casClient
* @return
*/
@Bean
public Config config(CasClient casClient) {
return new Config(casClient);
}
/**
* cas 客户端配置
* @param casConfig
* @return
*/ | @Bean
public CasClient casClient(CasConfiguration casConfig){
CasClient casClient = new CasClient(casConfig);
//客户端回调地址
casClient.setCallbackUrl(projectUrl + "/callback?client_name=" + clientName);
casClient.setName(clientName);
return casClient;
}
/**
* 请求cas服务端配置
* @param casLogoutHandler
*/
@Bean
public CasConfiguration casConfig(){
final CasConfiguration configuration = new CasConfiguration();
//CAS server登录地址
configuration.setLoginUrl(casServerUrl + "/login");
configuration.setAcceptAnyProxy(true);
configuration.setPrefixUrl(casServerUrl + "/");
configuration.setLogoutHandler(new DefaultCasLogoutHandler<>());
return configuration;
}
} | repos\spring-boot-quick-master\quick-shiro-cas\src\main\java\com\shiro\config\Pac4jConfig.java | 2 |
请完成以下Java代码 | public de.metas.handlingunits.model.I_M_Picking_Job_Step getM_Picking_Job_Step()
{
return get_ValueAsPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class);
}
@Override
public void setM_Picking_Job_Step(final de.metas.handlingunits.model.I_M_Picking_Job_Step M_Picking_Job_Step)
{
set_ValueFromPO(COLUMNNAME_M_Picking_Job_Step_ID, de.metas.handlingunits.model.I_M_Picking_Job_Step.class, M_Picking_Job_Step);
}
@Override
public void setM_Picking_Job_Step_ID (final int M_Picking_Job_Step_ID)
{
if (M_Picking_Job_Step_ID < 1)
set_Value (COLUMNNAME_M_Picking_Job_Step_ID, null);
else
set_Value (COLUMNNAME_M_Picking_Job_Step_ID, M_Picking_Job_Step_ID);
}
@Override
public int getM_Picking_Job_Step_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_ID);
}
@Override
public void setQtyReserved (final BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public de.metas.handlingunits.model.I_M_HU getVHU()
{
return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); | }
@Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU)
{
set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU);
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_Value (COLUMNNAME_VHU_ID, null);
else
set_Value (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Reservation.java | 1 |
请完成以下Java代码 | public void setAD_PrinterHW_MediaTray_ID (int AD_PrinterHW_MediaTray_ID)
{
if (AD_PrinterHW_MediaTray_ID < 1)
set_Value (COLUMNNAME_AD_PrinterHW_MediaTray_ID, null);
else
set_Value (COLUMNNAME_AD_PrinterHW_MediaTray_ID, Integer.valueOf(AD_PrinterHW_MediaTray_ID));
}
@Override
public int getAD_PrinterHW_MediaTray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaTray_ID);
}
@Override
public void setCalX (int CalX)
{
set_Value (COLUMNNAME_CalX, Integer.valueOf(CalX));
}
@Override
public int getCalX()
{
return get_ValueAsInt(COLUMNNAME_CalX);
}
@Override
public void setCalY (int CalY)
{
set_Value (COLUMNNAME_CalY, Integer.valueOf(CalY));
}
@Override
public int getCalY()
{
return get_ValueAsInt(COLUMNNAME_CalY);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
throw new IllegalArgumentException ("HostKey is virtual column"); }
@Override
public java.lang.String getHostKey()
{ | return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
@Override
public void setIsManualCalibration (boolean IsManualCalibration)
{
set_Value (COLUMNNAME_IsManualCalibration, Boolean.valueOf(IsManualCalibration));
}
@Override
public boolean isManualCalibration()
{
return get_ValueAsBoolean(COLUMNNAME_IsManualCalibration);
}
@Override
public void setMeasurementX (java.math.BigDecimal MeasurementX)
{
set_Value (COLUMNNAME_MeasurementX, MeasurementX);
}
@Override
public java.math.BigDecimal getMeasurementX()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementX);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setMeasurementY (java.math.BigDecimal MeasurementY)
{
set_Value (COLUMNNAME_MeasurementY, MeasurementY);
}
@Override
public java.math.BigDecimal getMeasurementY()
{
BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MeasurementY);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_Calibration.java | 1 |
请完成以下Java代码 | public void setM_LU_HU_PI_Item_ID (final int M_LU_HU_PI_Item_ID)
{
if (M_LU_HU_PI_Item_ID < 1)
set_Value (COLUMNNAME_M_LU_HU_PI_Item_ID, null);
else
set_Value (COLUMNNAME_M_LU_HU_PI_Item_ID, M_LU_HU_PI_Item_ID);
}
@Override
public int getM_LU_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_LU_HU_PI_Item_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_PI getM_TU_HU_PI()
{
return get_ValueAsPO(COLUMNNAME_M_TU_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class);
}
@Override
public void setM_TU_HU_PI(final de.metas.handlingunits.model.I_M_HU_PI M_TU_HU_PI)
{
set_ValueFromPO(COLUMNNAME_M_TU_HU_PI_ID, de.metas.handlingunits.model.I_M_HU_PI.class, M_TU_HU_PI);
}
@Override
public void setM_TU_HU_PI_ID (final int M_TU_HU_PI_ID)
{
if (M_TU_HU_PI_ID < 1)
set_Value (COLUMNNAME_M_TU_HU_PI_ID, null);
else
set_Value (COLUMNNAME_M_TU_HU_PI_ID, M_TU_HU_PI_ID);
}
@Override
public int getM_TU_HU_PI_ID()
{
return get_ValueAsInt(COLUMNNAME_M_TU_HU_PI_ID);
}
@Override
public void setQtyCUsPerTU (final BigDecimal QtyCUsPerTU)
{
set_Value (COLUMNNAME_QtyCUsPerTU, QtyCUsPerTU); | }
@Override
public BigDecimal getQtyCUsPerTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCUsPerTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyLU (final BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_LUTU_Configuration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
@Autowired
private UserRepository userRepository;
@RequestMapping("/")
public String index() {
return "redirect:/list";
}
@RequestMapping("/list")
public String list(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
@RequestParam(value = "size", defaultValue = "6") Integer size) {
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = new PageRequest(page, size, sort);
Page<User> users=userRepository.findList(pageable);
model.addAttribute("users", users);
return "user/list";
}
@RequestMapping("/toAdd")
public String toAdd() {
return "user/userAdd";
}
@RequestMapping("/add")
public String add(@Valid UserParam userParam,BindingResult result, ModelMap model) {
String errorMsg="";
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
}
model.addAttribute("errorMsg",errorMsg);
return "user/userAdd";
}
User u= userRepository.findByUserName(userParam.getUserName());
if(u!=null){
model.addAttribute("errorMsg","用户已存在!");
return "user/userAdd";
}
User user=new User();
BeanUtils.copyProperties(userParam,user);
user.setRegTime(new Date());
userRepository.save(user);
return "redirect:/list"; | }
@RequestMapping("/toEdit")
public String toEdit(Model model,Long id) {
User user=userRepository.findById(id);
model.addAttribute("user", user);
return "user/userEdit";
}
@RequestMapping("/edit")
public String edit(@Valid UserParam userParam, BindingResult result,ModelMap model) {
String errorMsg="";
if(result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
errorMsg=errorMsg + error.getCode() + "-" + error.getDefaultMessage() +";";
}
model.addAttribute("errorMsg",errorMsg);
model.addAttribute("user", userParam);
return "user/userEdit";
}
User user=new User();
BeanUtils.copyProperties(userParam,user);
user.setRegTime(new Date());
userRepository.save(user);
return "redirect:/list";
}
@RequestMapping("/delete")
public String delete(Long id) {
userRepository.delete(id);
return "redirect:/list";
}
} | repos\spring-boot-leaning-master\1.x\第06课:Jpa 和 Thymeleaf 实践\spring-boot-jpa-thymeleaf\src\main\java\com\neo\web\UserController.java | 2 |
请完成以下Java代码 | public int hashCode()
{
if (hashcode == 0)
{
hashcode = new HashcodeBuilder()
.append(31) // seed
.append(AD_Table_ID)
.append(AD_Column_ID)
.toHashcode();
}
return hashcode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final TableColumnResource other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false; | }
return new EqualsBuilder()
.append(AD_Table_ID, other.AD_Table_ID)
.append(AD_Column_ID, other.AD_Column_ID)
.isEqual();
}
public int getAD_Table_ID()
{
return AD_Table_ID;
}
public int getAD_Column_ID()
{
return AD_Column_ID;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableColumnResource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<EntityLink> findEntityLinksWithSameRootScopeForScopeIdAndScopeType(String scopeId, String scopeType, String linkType) {
Map<String, String> parameters = new HashMap<>();
parameters.put("scopeId", scopeId);
parameters.put("scopeType", scopeType);
parameters.put("linkType", linkType);
return (List) getList("selectEntityLinksWithSameRootScopeByScopeIdAndType", parameters);
}
@Override
@SuppressWarnings("unchecked")
public List<EntityLinkEntity> findEntityLinksByQuery(InternalEntityLinkQuery<EntityLinkEntity> query) {
return getList("selectEntityLinksByQuery", query, (CachedEntityMatcher<EntityLinkEntity>) query, true);
}
@Override
@SuppressWarnings("unchecked")
public EntityLinkEntity findEntityLinkByQuery(InternalEntityLinkQuery<EntityLinkEntity> query) {
return getEntity("selectEntityLinksByQuery", query, (SingleCachedEntityMatcher<EntityLinkEntity>) query, true);
}
@Override
public void deleteEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
Map<String, String> parameters = new HashMap<>(); | parameters.put("scopeId", scopeId);
parameters.put("scopeType", scopeType);
bulkDelete("deleteEntityLinksByScopeIdAndScopeType", entityLinksByScopeIdAndTypeMatcher, parameters);
}
@Override
public void deleteEntityLinksByRootScopeIdAndType(String scopeId, String scopeType) {
Map<String, String> parameters = new HashMap<>();
parameters.put("rootScopeId", scopeId);
parameters.put("rootScopeType", scopeType);
bulkDelete("deleteEntityLinksByRootScopeIdAndRootScopeType", entityLinksByRootScopeIdAndScopeTypeMatcher, parameters);
}
@Override
protected IdGenerator getIdGenerator() {
return entityLinkServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\data\impl\MybatisEntityLinkDataManager.java | 2 |
请完成以下Spring Boot application配置 | #
# Exchange configuration.
cassandre.trading.bot.exchange.name=kucoin
cassandre.trading.bot.exchange.username=kucoin.cassandre.test@gmail.com
cassandre.trading.bot.exchange.passphrase=cassandre
cassandre.trading.bot.exchange.key=6054ad25365ac6000689a998
cassandre.trading.bot.exchange.secret=af080d55-afe3-47c9-8ec1-4b479fbcc5e7
#
# Modes
cassandre.trading.bot.exchange.modes.sandbox=true
cassandre.trading.bot.exchange.modes.dry=false
#
# Exchange API calls rates (ms or standard ISO 8601 duration like 'PT5S').
cassandre.trading.bot.exchange.rates.account=2000
cassandre.trading.bot.exchange.rates.ticker=2000
cassandre.trading.bot.exchange.rates.trade=2000
#
# Da | tabase configuration.
cassandre.trading.bot.database.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
cassandre.trading.bot.database.datasource.url=jdbc:hsqldb:mem:cassandre
cassandre.trading.bot.database.datasource.username=sa
cassandre.trading.bot.database.datasource.password= | repos\tutorials-master\spring-boot-modules\spring-boot-cassandre\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private @Nullable WebAuthnRegistrationRequest readRegistrationRequest(HttpServletRequest request) {
HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
try {
return (WebAuthnRegistrationRequest) this.converter.read(WebAuthnRegistrationRequest.class, inputMessage);
}
catch (Exception ex) {
logger.debug("Unable to parse WebAuthnRegistrationRequest", ex);
return null;
}
}
private void removeCredential(HttpServletRequest request, HttpServletResponse response, @Nullable String id)
throws IOException {
this.userCredentials.delete(Bytes.fromBase64(id));
response.setStatus(HttpStatus.NO_CONTENT.value());
}
static class WebAuthnRegistrationRequest {
private @Nullable RelyingPartyPublicKey publicKey;
@Nullable RelyingPartyPublicKey getPublicKey() {
return this.publicKey;
}
void setPublicKey(RelyingPartyPublicKey publicKey) {
this.publicKey = publicKey;
} | }
public static class SuccessfulUserRegistrationResponse {
private final CredentialRecord credentialRecord;
SuccessfulUserRegistrationResponse(CredentialRecord credentialRecord) {
this.credentialRecord = credentialRecord;
}
public boolean isSuccess() {
return true;
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\registration\WebAuthnRegistrationFilter.java | 1 |
请完成以下Java代码 | public void registerESRLineListener(IESRLineHandler l)
{
if (handlers.contains(l))
{
throw new IllegalStateException(l + " has already been added");
}
handlers.add(l);
}
@Override
public boolean applyESRMatchingBPartnerOfTheInvoice(final I_C_Invoice invoice, final I_ESR_ImportLine esrLine)
{
for (final IESRLineHandler h : handlers)
{
boolean match = h.matchBPartnerOfInvoice(invoice, esrLine);
if (!match)
{
return false;
}
}
return true;
}
@Override
public boolean applyESRMatchingBPartner( | @NonNull final I_C_BPartner bPartner,
@NonNull final I_ESR_ImportLine esrLine)
{
for (final IESRLineHandler l : handlers)
{
boolean match = l.matchBPartner(bPartner, esrLine);
if (!match)
{
return false;
}
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRLineHandlersService.java | 1 |
请完成以下Java代码 | private void buildSql()
{
if (sqlBuilt)
{
return;
}
final ArrayList<Object> sqlParams = new ArrayList<>();
final StringBuilder sql = new StringBuilder();
sql.append(columnName).append(" IS NOT NULL");
if (range.hasLowerBound())
{
final String operator;
final BoundType boundType = range.lowerBoundType();
switch (boundType)
{
case OPEN:
operator = ">";
break;
case CLOSED:
operator = ">=";
break;
default:
throw new AdempiereException("Unknown bound: " + boundType);
}
sql.append(" AND ").append(columnName).append(operator).append("?");
sqlParams.add(range.lowerEndpoint());
}
if (range.hasUpperBound())
{
final String operator;
final BoundType boundType = range.upperBoundType(); | switch (boundType)
{
case OPEN:
operator = "<";
break;
case CLOSED:
operator = "<=";
break;
default:
throw new AdempiereException("Unknown bound: " + boundType);
}
sql.append(" AND ").append(columnName).append(operator).append("?");
sqlParams.add(range.upperEndpoint());
}
//
this.sqlWhereClause = sql.toString();
this.sqlParams = !sqlParams.isEmpty() ? Collections.unmodifiableList(sqlParams) : ImmutableList.of();
this.sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InstantRangeQueryFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Locale getLocale()
{
return i18n.getCurrentLocale();
}
@Override
public String createPasswordHash(final String password)
{
return Hashing.sha256()
.hashString(password, StandardCharsets.UTF_8)
.toString();
}
@Override
public void sendPasswordResetKey(
@NonNull final String email,
@NonNull final String passwordResetToken)
{
try
{
final User user = getUserByMail(email);
if (user == null)
{
throw new PasswordResetFailedException(i18n.get("LoginService.error.emailNotRegistered"));
}
final LanguageKey language = user.getLanguageKeyOrDefault();
final URI passwordResetURI = new URI(passwordResetUrl + "?token=" + passwordResetToken);
final MimeMessage mail = emailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(mail, true); // multipart=true
if (emailFrom != null && !emailFrom.isBlank())
{
helper.setFrom(emailFrom.trim());
}
helper.setTo(email);
helper.setSubject(i18n.get(language, "PasswordReset.email.subject"));
helper.setText(i18n.get(language, "PasswordReset.email.content", passwordResetURI));
emailSender.send(mail);
}
catch (final MessagingException | URISyntaxException e)
{
e.printStackTrace();
}
}
@Override
@Transactional
public String generatePasswordResetKey(final String email)
{
final User user = getUserByMail(email);
if (user == null)
{
throw new PasswordResetFailedException(i18n.get("LoginService.error.emailNotRegistered"));
}
//
// Generate a password reset key and set it on user
final String passwordResetKey = UUID.randomUUID().toString().replace("-", "");
user.setPasswordResetKey(passwordResetKey);
userRepository.save(user);
return passwordResetKey; | }
@Override
@Transactional
public User resetPassword(final String passwordResetKey)
{
final User user = getUserByPasswordResetKey(passwordResetKey);
if (user == null)
{
throw new PasswordResetFailedException(i18n.get("LoginService.error.invalidPasswordResetKey"));
}
final String passwordNew = generatePassword();
user.setPassword(passwordNew);
user.setPasswordResetKey(null);
userRepository.save(user);
senderToMetasfreshService.syncAfterCommit().add(user);
return user;
}
private String generatePassword()
{
final StringBuilder password = new StringBuilder();
final SecureRandom random = new SecureRandom();
final int poolLength = PASSWORD_CHARS.length();
for (int i = 0; i < PASSWORD_Length; i++)
{
final int charIndex = random.nextInt(poolLength);
final char ch = PASSWORD_CHARS.charAt(charIndex);
password.append(ch);
}
return password.toString();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\LoginService.java | 2 |
请完成以下Java代码 | public Builder phoneNumberVerified(Boolean phoneNumberVerified) {
return this.claim(StandardClaimNames.PHONE_NUMBER_VERIFIED, phoneNumberVerified);
}
/**
* Use this preferred username in the resulting {@link OidcUserInfo}
* @param preferredUsername The preferred username to use
* @return the {@link Builder} for further configurations
*/
public Builder preferredUsername(String preferredUsername) {
return claim(StandardClaimNames.PREFERRED_USERNAME, preferredUsername);
}
/**
* Use this profile in the resulting {@link OidcUserInfo}
* @param profile The profile to use
* @return the {@link Builder} for further configurations
*/
public Builder profile(String profile) {
return claim(StandardClaimNames.PROFILE, profile);
}
/**
* Use this subject in the resulting {@link OidcUserInfo}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
return this.claim(StandardClaimNames.SUB, subject);
}
/**
* Use this updated-at {@link Instant} in the resulting {@link OidcUserInfo}
* @param updatedAt The updated-at {@link Instant} to use
* @return the {@link Builder} for further configurations
*/
public Builder updatedAt(String updatedAt) {
return this.claim(StandardClaimNames.UPDATED_AT, updatedAt);
}
/**
* Use this website in the resulting {@link OidcUserInfo}
* @param website The website to use
* @return the {@link Builder} for further configurations
*/
public Builder website(String website) {
return this.claim(StandardClaimNames.WEBSITE, website);
} | /**
* Use this zoneinfo in the resulting {@link OidcUserInfo}
* @param zoneinfo The zoneinfo to use
* @return the {@link Builder} for further configurations
*/
public Builder zoneinfo(String zoneinfo) {
return this.claim(StandardClaimNames.ZONEINFO, zoneinfo);
}
/**
* Build the {@link OidcUserInfo}
* @return The constructed {@link OidcUserInfo}
*/
public OidcUserInfo build() {
return new OidcUserInfo(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\OidcUserInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public UserDetailsService myUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
String[][] usersGroupsAndRoles = {
{ "system", "password", "ROLE_ACTIVITI_USER" },
{ "admin", "password", "ROLE_ACTIVITI_ADMIN" },
};
for (String[] user : usersGroupsAndRoles) {
List<String> authoritiesStrings = asList(Arrays.copyOfRange(user, 2, user.length));
logger.info(
"> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]"
);
inMemoryUserDetailsManager.createUser(
new User(
user[0], | passwordEncoder().encode(user[1]),
authoritiesStrings
.stream()
.map(s -> new SimpleGrantedAuthority(s))
.collect(Collectors.toList())
)
);
}
return inMemoryUserDetailsManager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\Activiti-develop\activiti-examples\activiti-api-spring-integration-example\src\main\java\org\activiti\examples\DemoApplicationConfiguration.java | 2 |
请完成以下Java代码 | public ViewQuery findByGradeInRange(int lower, int upper, boolean inclusiveEnd) {
return ViewQuery.from("studentGrades", "findByGrade")
.startKey(lower)
.endKey(upper)
.inclusiveEnd(inclusiveEnd);
}
public ViewQuery findByGradeLessThan(int upper) {
return ViewQuery.from("studentGrades", "findByGrade")
.endKey(upper)
.inclusiveEnd(false);
}
public ViewQuery findByGradeGreaterThan(int lower) {
return ViewQuery.from("studentGrades", "findByGrade")
.startKey(lower);
}
public ViewQuery findByCourseAndGradeInRange(String course, int minGrade, int maxGrade, boolean inclusiveEnd) {
return ViewQuery.from("studentGrades", "findByCourseAndGrade")
.startKey(JsonArray.from(course, minGrade))
.endKey(JsonArray.from(course, maxGrade))
.inclusiveEnd(inclusiveEnd);
}
public ViewQuery findTopGradesByCourse(String course, int limit) {
return ViewQuery.from("studentGrades", "findByCourseAndGrade")
.startKey(JsonArray.from(course, 100))
.endKey(JsonArray.from(course, 0))
.inclusiveEnd(true)
.descending() | .limit(limit);
}
public ViewQuery countStudentsByCourse() {
return ViewQuery.from("studentGrades", "countStudentsByCourse")
.reduce()
.groupLevel(1);
}
public ViewQuery sumCreditsByStudent() {
return ViewQuery.from("studentGrades", "sumCreditsByStudent")
.reduce()
.groupLevel(1);
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\mapreduce\StudentGradeQueryBuilder.java | 1 |
请完成以下Java代码 | private void performSwitch() {
//gc.transferFocus();
//panel.dispatchTabSwitch(gc);
}
public void addTabSwitchingSupport(JComponent c) {
if(c instanceof JTable) {
((JTable)c).getSelectionModel().addListSelectionListener(this);
return;
}
else if( //c instanceof org.compiere.grid.ed.VEditor ||
c instanceof JTextComponent ||
//c instanceof ItemSelectable ||
c instanceof org.compiere.grid.ed.VCheckBox ||
//c instanceof org.compiere.grid.ed.VLookup ||
//c instanceof org.compiere.swing.CLabel ||
c instanceof AbstractButton)
{
c.addFocusListener(this);
//c.addKeyListener(new MovementAdapter());
return;
}
else if(c instanceof org.compiere.grid.ed.VDate)
{
org.compiere.grid.ed.VDate d = ((org.compiere.grid.ed.VDate)c);
//d.addFocusListener(this);
d.addActionListener(this);
//d.addKeyListener(new MovementAdapter()); | return;
}
else if(c instanceof org.compiere.grid.ed.VLookup)
{
org.compiere.grid.ed.VLookup l = ((org.compiere.grid.ed.VLookup)c);
//l.addFocusListener(this);
l.addActionListener(this);
//l.addKeyListener(new MovementAdapter());
return;
}
}
class MovementAdapter extends KeyAdapter
{
public void keyPressed(KeyEvent event)
{
// look for tab keys
if(event.getKeyCode() == KeyEvent.VK_TAB
|| event.getKeyCode() == KeyEvent.VK_ENTER)
{
((JComponent)event.getSource()).transferFocus();
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\TabSwitcher.java | 1 |
请完成以下Java代码 | public class GLJournalLineGroup implements IGLJournalLineGroup
{
private final int groupNo;
private final BigDecimal amtDr;
private final BigDecimal amtCr;
public GLJournalLineGroup(int groupNo, BigDecimal amtDr, BigDecimal amtCr)
{
super();
Check.assume(groupNo > 0, "groupNo > 0");
this.groupNo = groupNo;
Check.assumeNotNull(amtDr, "amtDr not null");
this.amtDr = amtDr;
Check.assumeNotNull(amtCr, "amtCr not null");
this.amtCr = amtCr;
}
@Override
public String toString()
{
return "GLJournalLineGroup [groupNo=" + groupNo + ", amtDr=" + amtDr + ", amtCr=" + amtCr + "]";
}
@Override
public BigDecimal getBalance()
{
return getAmtDr().subtract(getAmtCr());
}
@Override | public BigDecimal getAmtDr()
{
return amtDr;
}
@Override
public BigDecimal getAmtCr()
{
return amtCr;
}
@Override
public int getGroupNo()
{
return groupNo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal\impl\GLJournalLineGroup.java | 1 |
请完成以下Java代码 | public static final <ModelType> Builder<ModelType> builder()
{
return new Builder<>();
}
private final List<IFacetCategory> facetCategories;
private final Set<IFacet<ModelType>> facets;
private FacetCollectorResult(final Builder<ModelType> builder)
{
super();
this.facetCategories = ImmutableList.copyOf(builder.facetCategories);
this.facets = ImmutableSet.copyOf(builder.facets);
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public List<IFacetCategory> getFacetCategories()
{
return facetCategories;
}
@Override
public Set<IFacet<ModelType>> getFacets()
{
return facets;
}
@Override
public Set<IFacet<ModelType>> getFacetsByCategory(IFacetCategory facetCategory)
{
Check.assumeNotNull(facetCategory, "facetCategory not null");
// TODO optimize
final ImmutableSet.Builder<IFacet<ModelType>> facetsForCategory = ImmutableSet.builder();
for (final IFacet<ModelType> facet : facets)
{
if (!facetCategory.equals(facet.getFacetCategory()))
{
continue;
}
facetsForCategory.add(facet);
}
return facetsForCategory.build();
}
public static class Builder<ModelType>
{
private final Set<IFacetCategory> facetCategories = new LinkedHashSet<>();
private final LinkedHashSet<IFacet<ModelType>> facets = new LinkedHashSet<>();
private Builder()
{
super();
}
public IFacetCollectorResult<ModelType> build()
{
// If there was nothing added to this builder, return the empty instance (optimization)
if (isEmpty())
{
return EmptyFacetCollectorResult.getInstance();
}
return new FacetCollectorResult<>(this);
}
/** @return true if this builder is empty */
private final boolean isEmpty()
{ | return facets.isEmpty() && facetCategories.isEmpty();
}
public Builder<ModelType> addFacetCategory(final IFacetCategory facetCategory)
{
Check.assumeNotNull(facetCategory, "facetCategory not null");
facetCategories.add(facetCategory);
return this;
}
public Builder<ModelType> addFacet(final IFacet<ModelType> facet)
{
Check.assumeNotNull(facet, "facet not null");
facets.add(facet);
facetCategories.add(facet.getFacetCategory());
return this;
}
public Builder<ModelType> addFacets(final Iterable<IFacet<ModelType>> facets)
{
Check.assumeNotNull(facets, "facet not null");
for (final IFacet<ModelType> facet : facets)
{
addFacet(facet);
}
return this;
}
/** @return true if there was added at least one facet */
public boolean hasFacets()
{
return !facets.isEmpty();
}
public Builder<ModelType> addFacetCollectorResult(final IFacetCollectorResult<ModelType> facetCollectorResult)
{
// NOTE: we need to add the categories first, to make sure we preserve the order of categories
this.facetCategories.addAll(facetCollectorResult.getFacetCategories());
this.facets.addAll(facetCollectorResult.getFacets());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCollectorResult.java | 1 |
请完成以下Java代码 | private static Optional<Integer> extractNumberPrecision(final int displayType)
{
if (displayType == DisplayType.Integer)
{
return Optional.of(0);
}
else if (displayType == DisplayType.Amount
|| displayType == DisplayType.CostPrice
|| displayType == DisplayType.Quantity)
{
return Optional.of(2);
}
else
{
return Optional.empty();
}
}
private static class KPIsMap
{
private final ImmutableMap<KPIId, KPI> byId;
KPIsMap(final Collection<KPI> kpis)
{
byId = Maps.uniqueIndex(kpis, KPI::getId);
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("size", byId.size())
.toString();
}
public Collection<KPI> toCollection()
{
return byId.values();
} | @Nullable
public KPI getByIdOrNull(@NonNull final KPIId kpiId)
{
return byId.get(kpiId);
}
}
@Builder
@ToString
private static class KPILoadingContext
{
@NonNull private final ImmutableListMultimap<KPIId, I_WEBUI_KPI_Field> kpiFieldDefsMap;
@NonNull private final HashMap<Integer, I_AD_Element> adElementsById = new HashMap<>();
public ImmutableList<I_WEBUI_KPI_Field> getFields(@NonNull final KPIId kpiId)
{
return kpiFieldDefsMap.get(kpiId);
}
public I_AD_Element getAdElementById(final int adElementId, @NonNull final IADElementDAO adElementDAO)
{
return adElementsById.computeIfAbsent(adElementId, adElementDAO::getById);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPIRepository.java | 1 |
请完成以下Java代码 | public class WFActivityType
{
@JsonCreator
public static WFActivityType ofString(@NonNull final String value)
{
//noinspection UnstableApiUsage
return interner.intern(new WFActivityType(value));
}
@SuppressWarnings("UnstableApiUsage")
private static final Interner<WFActivityType> interner = Interners.newStrongInterner();
private final String value;
private WFActivityType(@NonNull final String value)
{
this.value = value;
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return value;
}
public void assertExpected(@NonNull final WFActivityType expected)
{
assertExpected(expected, this);
} | public void assertActual(@NonNull final WFActivityType actual)
{
assertExpected(this, actual);
}
private static void assertExpected(
@NonNull final WFActivityType expected,
@NonNull final WFActivityType actual)
{
if (!actual.equals(expected))
{
throw new AdempiereException("WFActivityType expected to be `" + expected + "` but it was `" + actual + "`");
}
}
public static boolean equals(@Nullable WFActivityType o1, @Nullable WFActivityType o2) {return Objects.equals(o1, o2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFActivityType.java | 1 |
请完成以下Java代码 | public Quantity computeQtyRequired(@NonNull final Quantity qtyOfFinishedGood)
{
final Quantity qtyOfFinishedGoodInRightUOM = uomConversionService.convertQuantityTo(qtyOfFinishedGood, UOMConversionContext.of(bomProductId), UomId.ofRepoId(bomProductUOM.getC_UOM_ID()));
final Quantity qtyRequiredForOneFinishedGood = getQtyRequiredForOneFinishedGood();
final Quantity qtyRequired;
if (componentType.isTools())
{
qtyRequired = qtyRequiredForOneFinishedGood;
}
else
{
qtyRequired = qtyRequiredForOneFinishedGood
.multiply(qtyOfFinishedGoodInRightUOM.toBigDecimal())
.setScale(UOMPrecision.ofInt(8), RoundingMode.UP);
}
//
// Adjust the qtyRequired by adding the scrap percentage to it.
return ProductBOMQtys.computeQtyWithScrap(qtyRequired, scrap);
}
@VisibleForTesting
public Quantity getQtyRequiredForOneFinishedGood()
{
if (qtyPercentage)
{
//
// We also need to multiply by BOM UOM to BOM Line UOM multiplier
// see http://dewiki908/mediawiki/index.php/06973_Fix_percentual_BOM_line_quantities_calculation_%28108941319640%29
final UOMConversionRate bomToLineRate = uomConversionService.getRate(bomProductId,
UomId.ofRepoId(bomProductUOM.getC_UOM_ID()),
UomId.ofRepoId(uom.getC_UOM_ID()));
final BigDecimal bomToLineUOMMultiplier = bomToLineRate.getFromToMultiplier();
return Quantity.of(
percentOfFinishedGood.computePercentageOf(bomToLineUOMMultiplier, 12),
uom);
}
else
{
return qtyForOneFinishedGood;
} | }
@Deprecated
public Quantity computeQtyOfFinishedGoodsForComponentQty(@NonNull final BigDecimal componentsQty)
{
return computeQtyOfFinishedGoodsForComponentQty(Quantity.of(componentsQty, uom));
}
public Quantity computeQtyOfFinishedGoodsForComponentQty(@NonNull final Quantity componentsQty)
{
final Quantity qtyRequiredForOneFinishedGood = getQtyRequiredForOneFinishedGood();
final Quantity componentsQtyConverted = uomConversionService.convertQuantityTo(componentsQty,
UOMConversionContext.of(productId),
uom);
final BigDecimal qtyOfFinishedGoodsBD = componentsQtyConverted
.toBigDecimal()
.divide(
qtyRequiredForOneFinishedGood.toBigDecimal(),
bomProductUOM.getStdPrecision(),
RoundingMode.DOWN); // IMPORTANT to round DOWN because we need complete products.
return Quantity.of(qtyOfFinishedGoodsBD, bomProductUOM);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\QtyCalculationsBOMLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreController {
private final SimpleFilterProvider filterProvider;
private final BookstoreService bookstoreService;
public BookstoreController(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
filterProvider = new SimpleFilterProvider().addFilter("AuthorId",
SimpleBeanPropertyFilter.filterOutAllExcept("id", "name", "age", "genre"));
filterProvider.setFailOnUnknownId(false);
}
@GetMapping("/author/avatar/{id}")
public String fetchAuthorAvatarViaId(@PathVariable long id) {
return Base64.getEncoder().encodeToString(bookstoreService.fetchAuthorAvatarViaId(id));
} | @GetMapping("/authors/{age}")
public MappingJacksonValue fetchAuthorsByAgeGreaterThanEqual(@PathVariable int age)
throws JsonProcessingException {
List<Author> authors = bookstoreService.fetchAuthorsByAgeGreaterThanEqual(age);
MappingJacksonValue wrapper = new MappingJacksonValue(authors);
wrapper.setFilters(filterProvider);
return wrapper;
}
@GetMapping("/authors/details/{age}")
public List<Author> fetchAuthorsDetailsByAgeGreaterThanEqual(@PathVariable int age)
throws JsonProcessingException {
return bookstoreService.fetchAuthorsDetailsByAgeGreaterThanEqual(age);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAttributeLazyLoadingJacksonSerialization\src\main\java\com\bookstore\controller\BookstoreController.java | 2 |
请完成以下Java代码 | public int getM_Picking_Job_Step_PickedHU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Job_Step_PickedHU_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU getPicked_HU()
{
return get_ValueAsPO(COLUMNNAME_Picked_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setPicked_HU(final de.metas.handlingunits.model.I_M_HU Picked_HU)
{
set_ValueFromPO(COLUMNNAME_Picked_HU_ID, de.metas.handlingunits.model.I_M_HU.class, Picked_HU);
}
@Override
public void setPicked_HU_ID (final int Picked_HU_ID)
{
if (Picked_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_Picked_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Picked_HU_ID, Picked_HU_ID);
}
@Override
public int getPicked_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_Picked_HU_ID);
}
@Override
public void setPicked_RenderedQRCode (final @Nullable java.lang.String Picked_RenderedQRCode)
{
set_Value (COLUMNNAME_Picked_RenderedQRCode, Picked_RenderedQRCode);
}
@Override
public java.lang.String getPicked_RenderedQRCode()
{
return get_ValueAsString(COLUMNNAME_Picked_RenderedQRCode);
}
@Override
public de.metas.handlingunits.model.I_M_HU getPickFrom_HU()
{
return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU)
{
set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU);
}
@Override
public void setPickFrom_HU_ID (final int PickFrom_HU_ID) | {
if (PickFrom_HU_ID < 1)
set_Value (COLUMNNAME_PickFrom_HU_ID, null);
else
set_Value (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_PickedHU.java | 1 |
请完成以下Java代码 | public void startupMinimal()
{
startupMinimal(RunMode.BACKEND);
}
/**
* Minimal adempiere system startup.
*/
public void startupMinimal(RunMode runMode)
{
// Disable distributed events because we don't want to broadcast events to network.
EventBusConfig.disableDistributedEvents();
AddonStarter.warnIfPropertiesFileMissing = false; // don't warn because it we know it's missing.
//
// Adempiere system shall be started with a minimal set of entity types.
// In particular, we don't want async, btw, because it doesn't stop when this process is already finished
ModelValidationEngine.setInitEntityTypes(ModelValidationEngine.INITENTITYTYPE_Minimal);
ModelValidationEngine.setFailOnMissingModelInteceptors(false); | //
// Initialize logging
LogManager.initialize(true); // running it here to make sure we get the client side config
//
// Start Adempiere system
Env.getSingleAdempiereInstance(null).startup(runMode);
System.out.println("ADempiere system started in tools minimal mode.");
}
private AdempiereToolsHelper()
{
super();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\tools\AdempiereToolsHelper.java | 1 |
请完成以下Java代码 | public CaseDefinitionEntity getCaseDefinitionById(String caseDefinitionId) {
checkInvalidDefinitionId(caseDefinitionId);
CaseDefinitionEntity caseDefinition = getDefinition(caseDefinitionId);
if (caseDefinition == null) {
caseDefinition = findDeployedDefinitionById(caseDefinitionId);
}
return caseDefinition;
}
@Override
protected AbstractResourceDefinitionManager<CaseDefinitionEntity> getManager() {
return Context.getCommandContext().getCaseDefinitionManager();
}
@Override
protected void checkInvalidDefinitionId(String definitionId) {
ensureNotNull("Invalid case definition id", "caseDefinitionId", definitionId);
}
@Override
protected void checkDefinitionFound(String definitionId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no deployed case definition found with id '" + definitionId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKey(String definitionKey, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key '" + definitionKey + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyAndTenantId(String definitionKey, String tenantId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key '" + definitionKey + "' and tenant-id '" + tenantId + "'", "caseDefinition", definition); | }
@Override
protected void checkInvalidDefinitionByKeyVersionAndTenantId(String definitionKey, Integer definitionVersion, String tenantId, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key = '" + definitionKey + "', version = '" + definitionVersion + "'"
+ " and tenant-id = '" + tenantId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionByKeyVersionTagAndTenantId(String definitionKey, String definitionVersionTag, String tenantId, CaseDefinitionEntity definition) {
throw new UnsupportedOperationException("Version tag is not implemented in case definition."); }
@Override
protected void checkInvalidDefinitionByDeploymentAndKey(String deploymentId, String definitionKey, CaseDefinitionEntity definition) {
ensureNotNull(CaseDefinitionNotFoundException.class, "no case definition deployed with key = '" + definitionKey + "' in deployment = '" + deploymentId + "'", "caseDefinition", definition);
}
@Override
protected void checkInvalidDefinitionWasCached(String deploymentId, String definitionId, CaseDefinitionEntity definition) {
ensureNotNull("deployment '" + deploymentId + "' didn't put case definition '" + definitionId + "' in the cache", "cachedCaseDefinition", definition);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CaseDefinitionCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeRepository {
@PersistenceContext
private EntityManager em;
@Transactional
public void save(Employee employee) {
em.persist(employee);
}
@Transactional
public void remove(int id) {
Employee employee = findById(id);
em.remove(employee);
}
public Employee findById(int id) {
return em.find(Employee.class, id); | }
public Employee findByJPQL(int id) {
return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class)
.setParameter("id", id).getSingleResult();
}
public Employee findByEntityGraph(int id) {
EntityGraph<Employee> entityGraph = em.createEntityGraph(Employee.class);
entityGraph.addAttributeNodes("name", "phones");
Map<String, Object> properties = new HashMap<>();
properties.put("javax.persistence.fetchgraph", entityGraph);
return em.find(Employee.class, id, properties);
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise-2\src\main\java\com\baeldung\elementcollection\repository\EmployeeRepository.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.