instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | default boolean isKey() { return getDescriptor().isKey(); }
default boolean isCalculated() { return getDescriptor().isCalculated(); }
default boolean isReadonlyVirtualField() { return getDescriptor().isReadonlyVirtualField(); }
default boolean isParentLink() { return getDescriptor().isParentLink(); }
/** Checks if this field was changed until it was saved. i.e. compares {@link #getValue()} with {@link #getInitialValue()}. */
boolean hasChangesToSave();
//@formatter:on
//@formatter:off
LogicExpressionResult getReadonly();
default boolean isAlwaysUpdateable() { return getDescriptor().isAlwaysUpdateable(); }
//
LogicExpressionResult getMandatory();
default boolean isMandatory() { return getMandatory().isTrue(); }
//
LogicExpressionResult getDisplayed();
//
boolean isLookupValuesStale();
/** @return true if this field is public and will be published to API clients */
default boolean isPublicField() { return getDescriptor().hasCharacteristic(Characteristic.PublicField); }
default boolean isAdvancedField() { return getDescriptor().hasCharacteristic(Characteristic.AdvancedField); }
//@formatter:on
//@formatter:off
default Class<?> getValueClass() { return getDescriptor().getValueClass(); }
/** @return field's current value */
@Nullable
Object getValue();
@Nullable
Object getValueAsJsonObject(JSONOptions jsonOpts);
boolean getValueAsBoolean();
int getValueAsInt(final int defaultValueWhenNull);
DocumentZoomIntoInfo getZoomIntoInfo();
@Nullable
<T> T getValueAs(@NonNull final Class<T> returnType);
default Optional<BigDecimal> getValueAsBigDecimal() { return Optional.ofNullable(getValueAs(BigDecimal.class));} | default <T extends RepoIdAware> Optional<T> getValueAsId(Class<T> idType) { return Optional.ofNullable(getValueAs(idType));}
/** @return initial value / last saved value */
@Nullable
Object getInitialValue();
/** @return old value (i.e. the value as it was when the document was checked out from repository/documents collection) */
@Nullable
Object getOldValue();
//@formatter:on
/**
* @return field's valid state; never return null
*/
DocumentValidStatus getValidStatus();
/**
* @return optional WindowId to be used when zooming into
*/
Optional<WindowId> getZoomIntoWindowId();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\IDocumentFieldView.java | 1 |
请完成以下Java代码 | public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
public I_C_ElementValue getUser1() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser1_ID(), get_TrxName()); }
/** Set User List 1.
@param User1_ID
User defined list element #1
*/
public void setUser1_ID (int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID));
}
/** Get User List 1.
@return User defined list element #1
*/
public int getUser1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ElementValue getUser2() throws RuntimeException
{
return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); }
/** Set User List 2.
@param User2_ID
User defined list element #2
*/
public void setUser2_ID (int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID));
}
/** Get User List 2.
@return User defined list element #2
*/
public int getUser2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Movement.java | 1 |
请完成以下Java代码 | final class GracefulShutdown {
private static final Log logger = LogFactory.getLog(GracefulShutdown.class);
private final Server server;
private final Supplier<Integer> activeRequests;
private volatile boolean aborted;
GracefulShutdown(Server server, Supplier<Integer> activeRequests) {
this.server = server;
this.activeRequests = activeRequests;
}
void shutDownGracefully(GracefulShutdownCallback callback) {
logger.info("Commencing graceful shutdown. Waiting for active requests to complete");
new Thread(() -> awaitShutdown(callback), "jetty-shutdown").start();
boolean jetty10 = isJetty10();
for (Connector connector : this.server.getConnectors()) {
shutdown(connector, !jetty10);
}
}
@SuppressWarnings("unchecked")
private void shutdown(Connector connector, boolean getResult) {
Future<Void> result;
try {
result = connector.shutdown();
}
catch (NoSuchMethodError ex) {
Method shutdown = ReflectionUtils.findMethod(connector.getClass(), "shutdown");
Assert.state(shutdown != null, "'shutdown' must not be null");
result = (Future<Void>) ReflectionUtils.invokeMethod(shutdown, connector);
}
if (getResult) {
try {
Assert.state(result != null, "'result' must not be null");
result.get();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
catch (ExecutionException ex) { | // Continue
}
}
}
private boolean isJetty10() {
try {
return CompletableFuture.class.equals(Connector.class.getMethod("shutdown").getReturnType());
}
catch (Exception ex) {
return false;
}
}
private void awaitShutdown(GracefulShutdownCallback callback) {
while (!this.aborted && this.activeRequests.get() > 0) {
sleep(100);
}
if (this.aborted) {
logger.info("Graceful shutdown aborted with one or more requests still active");
callback.shutdownComplete(GracefulShutdownResult.REQUESTS_ACTIVE);
}
else {
logger.info("Graceful shutdown complete");
callback.shutdownComplete(GracefulShutdownResult.IDLE);
}
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
void abort() {
this.aborted = true;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\GracefulShutdown.java | 1 |
请完成以下Java代码 | public String getTopicNamePrefix()
{
return WebsocketTopicNames.TOPIC_Dashboard;
}
@Override
public UserDashboardWebsocketProducer createProducer(final WebsocketTopicName topicName)
{
final WebuiSessionId sessionId = extractSessionId(topicName);
if (sessionId == null)
{
throw new AdempiereException("Invalid websocket topic name: " + topicName);
}
final KPIDataContext kpiDataContext = contextHolder.getSessionContext(sessionId);
return UserDashboardWebsocketProducer.builder()
.dashboardDataService(dashboardDataService)
.websocketTopicName(topicName)
.kpiDataContext(kpiDataContext)
.build();
}
@Nullable
public static WebuiSessionId extractSessionId(@NonNull final WebsocketTopicName topicName)
{
final String topicNameString = topicName.getAsString();
if (topicNameString.startsWith(WebsocketTopicNames.TOPIC_Dashboard)) | {
final String sessionId = topicNameString.substring(WebsocketTopicNames.TOPIC_Dashboard.length() + 1).trim();
return WebuiSessionId.ofNullableString(sessionId);
}
else
{
return null;
}
}
public static WebsocketTopicName createWebsocketTopicName(@NonNull final WebuiSessionId sessionId)
{
return WebsocketTopicName.ofString(WebsocketTopicNames.TOPIC_Dashboard + "/" + sessionId.getAsString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketProducerFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AdoptionService {
private final OwnerRepository ownersRepo;
private final PetRepository petsRepo;
private final SpeciesRepository speciesRepo;
/**
* Register a new pet for adoption. Initially, this pet will have no name or owner.
* @param speciesName
* @return The assigned UUID for this pet
*/
public UUID registerForAdoption( String speciesName) {
var species = speciesRepo.findByName(speciesName)
.orElseThrow(() -> new IllegalArgumentException("Unknown Species: " + speciesName));
var pet = new Pet();
pet.setSpecies(species);
pet.setUuid(UUID.randomUUID());
petsRepo.save(pet);
return pet.getUuid();
}
public List<Pet> findPetsForAdoption(String speciesName) {
var species = speciesRepo.findByName(speciesName)
.orElseThrow(() -> new IllegalArgumentException("Unknown Species: " + speciesName));
return petsRepo.findPetsByOwnerNullAndSpecies(species);
}
public Pet adoptPet(UUID petUuid, String ownerName, String petName) {
var newOwner = ownersRepo.findByName(ownerName)
.orElseThrow(() -> new IllegalArgumentException("Unknown owner"));
var pet = petsRepo.findPetByUuid(petUuid)
.orElseThrow(() -> new IllegalArgumentException("Unknown pet"));
if ( pet.getOwner() != null) {
throw new IllegalArgumentException("Pet already adopted");
}
pet.setOwner(newOwner);
pet.setName(petName);
petsRepo.save(pet);
return pet;
}
public Pet returnPet(UUID petUuid) { | var pet = petsRepo.findPetByUuid(petUuid)
.orElseThrow(() -> new IllegalArgumentException("Unknown pet"));
pet.setOwner(null);
petsRepo.save(pet);
return pet;
}
public List<PetHistoryEntry> listPetHistory(UUID petUuid) {
var pet = petsRepo.findPetByUuid(petUuid)
.orElseThrow(() -> new IllegalArgumentException("No pet with UUID '" + petUuid + "' found"));
return petsRepo.findRevisions(pet.getId()).stream()
.map(r -> {
CustomRevisionEntity rev = r.getMetadata().getDelegate();
return new PetHistoryEntry(r.getRequiredRevisionInstant(),
r.getMetadata().getRevisionType(),
r.getEntity().getUuid(),
r.getEntity().getSpecies().getName(),
r.getEntity().getName(),
r.getEntity().getOwner() != null ? r.getEntity().getOwner().getName() : null,
rev.getRemoteHost(),
rev.getRemoteUser());
})
.toList();
}
} | repos\tutorials-master\persistence-modules\spring-data-envers\src\main\java\com\baeldung\envers\customrevision\service\AdoptionService.java | 2 |
请完成以下Java代码 | static Object normalizeValue(@Nullable final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof RepoIdAware)
{
return ((RepoIdAware)value).getRepoId();
}
else if (value instanceof ReferenceListAwareEnum)
{
return ((ReferenceListAwareEnum)value).getCode();
}
else if (TimeUtil.isDateOrTimeObject(value))
{
return TimeUtil.asZonedDateTime(value);
}
else
{
assertValueIsSQLConvertibleIfJUnitMode(value);
return value;
}
}
private static void assertValueIsSQLConvertibleIfJUnitMode(@Nullable final Object value)
{
if (Adempiere.isUnitTestMode())
{
DB.TO_SQL(value); // expect to throw exception if not convertible
}
}
@Override
public final String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public final List<Object> getSqlParams(final Properties ctx)
{
buildSql();
return sqlParams;
}
private boolean sqlBuilt = false;
private String sqlWhereClause = null;
private List<Object> sqlParams = null;
private void buildSql()
{ | if (sqlBuilt)
{
return;
}
final Operator operator = getOperator();
final String operand1ColumnName = operand1.getColumnName();
final String operand1ColumnSql = operand1Modifier.getColumnSql(operand1ColumnName);
final String operatorSql = operator.getSql();
sqlParams = new ArrayList<>();
final String operand2Sql = operand2 == null ? null : operand2Modifier.getValueSql(operand2, sqlParams);
if (operand2 == null && Operator.EQUAL == operator)
{
sqlWhereClause = operand1ColumnName + " IS NULL";
sqlParams = Collections.emptyList();
}
else if (operand2 == null && Operator.NOT_EQUAL == operator)
{
sqlWhereClause = operand1ColumnName + " IS NOT NULL";
sqlParams = Collections.emptyList();
}
else
{
sqlWhereClause = operand1ColumnSql + " " + operatorSql + " " + operand2Sql;
}
// Corner case: we are asked for Operand1 <> SomeValue
// => we need to create an SQL which is also taking care about the NULL value
// i.e. (Operand1 <> SomeValue OR Operand1 IS NULL)
if (operand2 != null && Operator.NOT_EQUAL == operator)
{
sqlWhereClause = "(" + sqlWhereClause
+ " OR " + operand1ColumnSql + " IS NULL"
+ ")";
}
sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompareQueryFilter.java | 1 |
请完成以下Java代码 | public LookupValue findById(final Object idObj)
{
if (idObj == null)
{
return null;
}
//
// Normalize the ID to Integer/String
final Object idNormalized = LookupValue.normalizeId(idObj, fetcher.isNumericKey());
if (idNormalized == null)
{
return null;
}
//
// Build the validation context
final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingById(idNormalized)
.putFilterById(IdsToFilter.ofSingleValue(idNormalized))
.putShowInactive(true)
.build();
//
// Get the lookup value
final LookupValue lookupValue = fetcher.retrieveLookupValueById(evalCtx);
if (lookupValue == LookupDataSourceFetcher.LOOKUPVALUE_NULL)
{
return null;
}
return lookupValue;
} | @Override
public @NonNull LookupValuesList findByIdsOrdered(final @NonNull Collection<?> ids)
{
final LookupDataSourceContext evalCtx = fetcher.newContextForFetchingByIds(ids)
.putShowInactive(true)
.build();
return fetcher.retrieveLookupValueByIdsInOrder(evalCtx);
}
@Override
public List<CCacheStats> getCacheStats()
{
return fetcher.getCacheStats();
}
@Override
public void cacheInvalidate()
{
fetcher.cacheInvalidate();
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return fetcher.getZoomIntoWindowId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static ResultBody error(BaseErrorInfoInterface errorInfo) {
ResultBody rb = new ResultBody();
rb.setCode(errorInfo.getResultCode());
rb.setMessage(errorInfo.getResultMsg());
rb.setResult(null);
return rb;
}
public static ResultBody error(String code, String message) {
ResultBody rb = new ResultBody();
rb.setCode(code);
rb.setMessage(message);
rb.setResult(null);
return rb;
} | public static ResultBody error( String message) {
ResultBody rb = new ResultBody();
rb.setCode("-1");
rb.setMessage(message);
rb.setResult(null);
return rb;
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
} | repos\springboot-demo-master\Exception\src\main\java\com\et\exception\config\ResultBody.java | 2 |
请完成以下Java代码 | public Map<String, Object> getCaseVariables() {
Map<String, Object> caseVariables = new HashMap<>();
if (this.queryVariables != null) {
for (VariableInstanceEntity queryVariable : queryVariables) {
if (queryVariable.getId() != null && queryVariable.getTaskId() == null) {
caseVariables.put(queryVariable.getName(), queryVariable.getValue());
}
}
}
// The variables from the cache have precedence
if (variableInstances != null) {
for (String variableName : variableInstances.keySet()) {
caseVariables.put(variableName, variableInstances.get(variableName).getValue());
}
}
return caseVariables;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public List<VariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new VariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
@Override
public void setCaseDefinitionKey(String caseDefinitionKey) {
this.caseDefinitionKey = caseDefinitionKey;
}
@Override
public String getCaseDefinitionName() {
return caseDefinitionName;
}
@Override
public void setCaseDefinitionName(String caseDefinitionName) {
this.caseDefinitionName = caseDefinitionName;
}
@Override
public Integer getCaseDefinitionVersion() {
return caseDefinitionVersion; | }
@Override
public void setCaseDefinitionVersion(Integer caseDefinitionVersion) {
this.caseDefinitionVersion = caseDefinitionVersion;
}
@Override
public String getCaseDefinitionDeploymentId() {
return caseDefinitionDeploymentId;
}
@Override
public void setCaseDefinitionDeploymentId(String caseDefinitionDeploymentId) {
this.caseDefinitionDeploymentId = caseDefinitionDeploymentId;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CaseInstance[id=").append(id)
.append(", caseDefinitionId=").append(caseDefinitionId)
.append(", caseDefinitionKey=").append(caseDefinitionKey)
.append(", parentId=").append(parentId)
.append(", name=").append(name);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CaseInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public abstract class EnumItemDictionary<E extends Enum<E>> extends CommonDictionary<EnumItem<E>>
{
@Override
protected EnumItem<E> createValue(String[] params)
{
Map.Entry<String, Map.Entry<String, Integer>[]> args = EnumItem.create(params);
EnumItem<E> nrEnumItem = new EnumItem<E>();
for (Map.Entry<String, Integer> e : args.getValue())
{
nrEnumItem.labelMap.put(valueOf(e.getKey()), e.getValue());
}
return nrEnumItem;
}
/**
* 代理E.valueOf
*
* @param name
* @return
*/
protected abstract E valueOf(String name);
/**
* 代理E.values
*
* @return
*/
protected abstract E[] values();
/**
* 代理new EnumItem<E>
*
* @return
*/
protected abstract EnumItem<E> newItem();
@Override
final protected EnumItem<E>[] loadValueArray(ByteArray byteArray)
{
if (byteArray == null)
{
return null;
}
E[] nrArray = values();
int size = byteArray.nextInt();
EnumItem<E>[] valueArray = new EnumItem[size]; | for (int i = 0; i < size; ++i)
{
int currentSize = byteArray.nextInt();
EnumItem<E> item = newItem();
for (int j = 0; j < currentSize; ++j)
{
E nr = nrArray[byteArray.nextInt()];
int frequency = byteArray.nextInt();
item.labelMap.put(nr, frequency);
}
valueArray[i] = item;
}
return valueArray;
}
@Override
protected void saveValue(EnumItem<E> item, DataOutputStream out) throws IOException
{
out.writeInt(item.labelMap.size());
for (Map.Entry<E, Integer> entry : item.labelMap.entrySet())
{
out.writeInt(entry.getKey().ordinal());
out.writeInt(entry.getValue());
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\common\EnumItemDictionary.java | 1 |
请完成以下Java代码 | public static boolean equals(@Nullable final LocatorId id1, @Nullable final LocatorId id2)
{
return Objects.equals(id1, id2);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean equalsByRepoId(final int repoId1, final int repoId2)
{
final int repoId1Norm = repoId1 > 0 ? repoId1 : -1;
final int repoId2Norm = repoId2 > 0 ? repoId2 : -1;
return repoId1Norm == repoId2Norm;
}
private LocatorId(final int repoId, @NonNull final WarehouseId warehouseId)
{
Check.assumeGreaterThanZero(repoId, "M_Locator_ID");
this.repoId = repoId;
this.warehouseId = warehouseId;
}
@JsonValue
public String toJson()
{
return warehouseId.getRepoId() + "_" + repoId;
}
@JsonCreator | public static LocatorId fromJson(final String json)
{
final String[] parts = json.split("_");
if (parts.length != 2)
{
throw new IllegalArgumentException("Invalid json: " + json);
}
final int warehouseId = Integer.parseInt(parts[0]);
final int locatorId = Integer.parseInt(parts[1]);
return ofRepoId(warehouseId, locatorId);
}
public void assetWarehouseId(@NonNull final WarehouseId expectedWarehouseId)
{
if (!WarehouseId.equals(this.warehouseId, expectedWarehouseId))
{
throw new AdempiereException("Expected " + expectedWarehouseId + " for " + this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\LocatorId.java | 1 |
请完成以下Java代码 | public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceCreateTime() {
orderBy(HistoricCaseActivityInstanceQueryProperty.CREATE);
return this;
}
public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceEndTime() {
orderBy(HistoricCaseActivityInstanceQueryProperty.END);
return this;
}
public HistoricCaseActivityInstanceQuery orderByHistoricCaseActivityInstanceDuration() {
orderBy(HistoricCaseActivityInstanceQueryProperty.DURATION);
return this;
}
public HistoricCaseActivityInstanceQuery orderByCaseDefinitionId() {
orderBy(HistoricCaseActivityInstanceQueryProperty.CASE_DEFINITION_ID);
return this;
}
public HistoricCaseActivityInstanceQuery orderByTenantId() {
return orderBy(HistoricCaseActivityInstanceQueryProperty.TENANT_ID);
}
// getter
public String[] getCaseActivityInstanceIds() {
return caseActivityInstanceIds;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String[] getCaseActivityIds() {
return caseActivityIds;
}
public String getCaseActivityName() {
return caseActivityName;
}
public String getCaseActivityType() {
return caseActivityType;
}
public Date getCreatedBefore() { | return createdBefore;
}
public Date getCreatedAfter() {
return createdAfter;
}
public Date getEndedBefore() {
return endedBefore;
}
public Date getEndedAfter() {
return endedAfter;
}
public Boolean getEnded() {
return ended;
}
public Integer getCaseActivityInstanceState() {
return caseActivityInstanceState;
}
public Boolean isRequired() {
return required;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseActivityInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
@ApiModelProperty(example = "null")
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
@ApiModelProperty(example = "2023-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
@ApiModelProperty(example = "cmmn")
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@ApiModelProperty(example = "async-history")
public String getJobHandlerType() {
return jobHandlerType;
}
public void setJobHandlerType(String jobHandlerType) {
this.jobHandlerType = jobHandlerType;
}
@ApiModelProperty(example = "myCfg")
public String getJobHandlerConfiguration() {
return jobHandlerConfiguration;
}
public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
} | @ApiModelProperty(example = "myAdvancedCfg")
public String getAdvancedJobHandlerConfiguration() {
return advancedJobHandlerConfiguration;
}
public void setAdvancedJobHandlerConfiguration(String advancedJobHandlerConfiguration) {
this.advancedJobHandlerConfiguration = advancedJobHandlerConfiguration;
}
@ApiModelProperty(example = "custom value")
public String getCustomValues() {
return customValues;
}
public void setCustomValues(String customValues) {
this.customValues = customValues;
}
@ApiModelProperty(example = "node1")
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
@ApiModelProperty(example = "2023-06-03T22:05:05.474+0000")
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\HistoryJobResponse.java | 2 |
请完成以下Java代码 | public void setScriptIdentifier (final String ScriptIdentifier)
{
set_Value (COLUMNNAME_ScriptIdentifier, ScriptIdentifier);
}
@Override
public String getScriptIdentifier()
{
return get_ValueAsString(COLUMNNAME_ScriptIdentifier);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override | public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setWhereClause (final String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
@Override
public String getWhereClause()
{
return get_ValueAsString(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_ScriptedExportConversion.java | 1 |
请完成以下Java代码 | public void addActivity(final PPRoutingActivity activity)
{
if (!activity.getYield().isZero())
{
yield = yield.multiply(activity.getYield(), 0);
}
queuingTime = queuingTime.plus(activity.getQueuingTime());
setupTime = setupTime.plus(activity.getSetupTime());
waitingTime = waitingTime.plus(activity.getWaitingTime());
movingTime = movingTime.plus(activity.getMovingTime());
// We use node.getDuration() instead of m_routingService.estimateWorkingTime(node) because
// this will be the minimum duration of this node. So even if the node have defined units/cycle
// we consider entire duration of the node.
durationPerOneUnit = durationPerOneUnit.plus(activity.getDurationPerOneUnit());
}
}
@lombok.Value(staticConstructor = "of")
private static class RoutingActivitySegmentCost
{
public static Collector<RoutingActivitySegmentCost, ?, Map<CostElementId, BigDecimal>> groupByCostElementId()
{
return Collectors.groupingBy(RoutingActivitySegmentCost::getCostElementId, sumCostsAsBigDecimal());
}
private static Collector<RoutingActivitySegmentCost, ?, BigDecimal> sumCostsAsBigDecimal()
{ | return Collectors.reducing(BigDecimal.ZERO, RoutingActivitySegmentCost::getCostAsBigDecimal, BigDecimal::add);
}
@NonNull
CostAmount cost;
@NonNull
PPRoutingActivityId routingActivityId;
@NonNull
CostElementId costElementId;
public BigDecimal getCostAsBigDecimal()
{
return cost.toBigDecimal();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\RollupWorkflow.java | 1 |
请完成以下Java代码 | public class MessageFlow extends BaseElement {
protected String name;
protected String sourceRef;
protected String targetRef;
protected String messageRef;
public MessageFlow() {}
public MessageFlow(String sourceRef, String targetRef) {
this.sourceRef = sourceRef;
this.targetRef = targetRef;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceRef() {
return sourceRef;
}
public void setSourceRef(String sourceRef) {
this.sourceRef = sourceRef;
}
public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
} | public String getMessageRef() {
return messageRef;
}
public void setMessageRef(String messageRef) {
this.messageRef = messageRef;
}
public String toString() {
return sourceRef + " --> " + targetRef;
}
public MessageFlow clone() {
MessageFlow clone = new MessageFlow();
clone.setValues(this);
return clone;
}
public void setValues(MessageFlow otherFlow) {
super.setValues(otherFlow);
setName(otherFlow.getName());
setSourceRef(otherFlow.getSourceRef());
setTargetRef(otherFlow.getTargetRef());
setMessageRef(otherFlow.getMessageRef());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\MessageFlow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HistoricVariableInstanceDataResource extends HistoricVariableInstanceBaseResource {
@Autowired
protected CmmnRestResponseFactory restResponseFactory;
@Autowired
protected CmmnHistoryService historyService;
@GetMapping(value = "/cmmn-history/historic-variable-instances/{varInstanceId}/data")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the variable instance was found and the requested variable data is returned."),
@ApiResponse(code = 404, message = "Indicates the requested variable instance was not found or the variable instance does not have a variable with the given name or the variable does not have a binary stream available. Status message provides additional information.") })
@ApiOperation(value = "Get the binary data for a historic task instance variable", tags = {
"History" }, nickname = "getHistoricInstanceVariableData", notes = "The response body contains the binary value of the variable. When the variable is of type binary, the content-type of the response is set to application/octet-stream, regardless of the content of the variable or the request accept-type header. In case of serializable, application/x-java-serialized-object is used as content-type.")
@ResponseBody
public byte[] getVariableData(@ApiParam(name = "varInstanceId") @PathVariable("varInstanceId") String varInstanceId, HttpServletResponse response) {
try {
byte[] result = null;
RestVariable variable = getVariableFromRequest(true, varInstanceId);
if (CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
result = (byte[]) variable.getValue();
response.setContentType("application/octet-stream");
} else if (CmmnRestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) { | ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(buffer);
outputStream.writeObject(variable.getValue());
outputStream.close();
result = buffer.toByteArray();
response.setContentType("application/x-java-serialized-object");
} else {
throw new FlowableObjectNotFoundException("The variable does not have a binary data stream.", null);
}
return result;
} catch (IOException ioe) {
// Re-throw IOException
throw new FlowableException("Unexpected exception getting variable data", ioe);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceDataResource.java | 2 |
请完成以下Java代码 | final HttpSession applySessionFixation(HttpServletRequest request) {
HttpSession session = request.getSession();
String originalSessionId = session.getId();
this.logger.debug(LogMessage.of(() -> "Invalidating session with Id '" + originalSessionId + "' "
+ (this.migrateSessionAttributes ? "and" : "without") + " migrating attributes."));
Map<String, Object> attributesToMigrate = extractAttributes(session);
int maxInactiveIntervalToMigrate = session.getMaxInactiveInterval();
session.invalidate();
session = request.getSession(true); // we now have a new session
this.logger.debug(LogMessage.format("Started new session: %s", session.getId()));
transferAttributes(attributesToMigrate, session);
if (this.migrateSessionAttributes) {
session.setMaxInactiveInterval(maxInactiveIntervalToMigrate);
}
return session;
}
/**
* @param attributes the attributes which were extracted from the original session by
* {@code extractAttributes}
* @param newSession the newly created session
*/
void transferAttributes(Map<String, Object> attributes, HttpSession newSession) {
if (attributes != null) {
attributes.forEach(newSession::setAttribute);
}
}
@SuppressWarnings("unchecked")
private HashMap<String, Object> createMigratedAttributeMap(HttpSession session) {
HashMap<String, Object> attributesToMigrate = new HashMap<>();
Enumeration<String> enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement(); | if (!this.migrateSessionAttributes && !key.startsWith("SPRING_SECURITY_")) {
// Only retain Spring Security attributes
continue;
}
attributesToMigrate.put(key, session.getAttribute(key));
}
return attributesToMigrate;
}
/**
* Defines whether attributes should be migrated to a new session or not. Has no
* effect if you override the {@code extractAttributes} method.
* <p>
* Attributes used by Spring Security (to store cached requests, for example) will
* still be retained by default, even if you set this value to {@code false}.
* @param migrateSessionAttributes whether the attributes from the session should be
* transferred to the new, authenticated session.
*/
public void setMigrateSessionAttributes(boolean migrateSessionAttributes) {
this.migrateSessionAttributes = migrateSessionAttributes;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\session\SessionFixationProtectionStrategy.java | 1 |
请完成以下Java代码 | public boolean isDraft(final I_C_RfQResponse rfqResponse)
{
final String docStatus = rfqResponse.getDocStatus();
return X_C_RfQResponse.DOCSTATUS_Drafted.equals(docStatus)
|| X_C_RfQResponse.DOCSTATUS_InProgress.equals(docStatus);
}
@Override
public boolean isDraft(final I_C_RfQResponseLine rfqResponseLine)
{
final String docStatus = rfqResponseLine.getDocStatus();
return X_C_RfQResponseLine.DOCSTATUS_Drafted.equals(docStatus)
|| X_C_RfQResponseLine.DOCSTATUS_InProgress.equals(docStatus);
}
@Override
public boolean isCompleted(final I_C_RfQResponse rfqResponse)
{
return X_C_RfQResponse.DOCSTATUS_Completed.equals(rfqResponse.getDocStatus());
}
@Override
public boolean isCompleted(final I_C_RfQResponseLine rfqResponseLine)
{
return X_C_RfQResponseLine.DOCSTATUS_Completed.equals(rfqResponseLine.getDocStatus());
}
@Override
public boolean isClosed(final I_C_RfQResponse rfqResponse)
{
return X_C_RfQResponse.DOCSTATUS_Closed.equals(rfqResponse.getDocStatus());
}
@Override
public boolean isClosed(final I_C_RfQResponseLine rfqResponseLine)
{
return X_C_RfQResponseLine.DOCSTATUS_Closed.equals(rfqResponseLine.getDocStatus());
}
@Override
public String getSummary(final I_C_RfQ rfq)
{
// NOTE: nulls shall be tolerated because the method is used for building exception error messages
if (rfq == null)
{
return "@C_RfQ_ID@ ?";
}
return "@C_RfQ_ID@ #" + rfq.getDocumentNo();
}
@Override
public String getSummary(final I_C_RfQResponse rfqResponse)
{
// NOTE: nulls shall be tolerated because the method is used for building exception error messages
if (rfqResponse == null)
{
return "@C_RfQResponse_ID@ ?";
}
return "@C_RfQResponse_ID@ #" + rfqResponse.getName(); | }
@Override
public void updateQtyPromisedAndSave(final I_C_RfQResponseLine rfqResponseLine)
{
final BigDecimal qtyPromised = Services.get(IRfqDAO.class).calculateQtyPromised(rfqResponseLine);
rfqResponseLine.setQtyPromised(qtyPromised);
InterfaceWrapperHelper.save(rfqResponseLine);
}
// @Override
// public void uncloseInTrx(final I_C_RfQResponse rfqResponse)
// {
// if (!isClosed(rfqResponse))
// {
// throw new RfQDocumentNotClosedException(getSummary(rfqResponse));
// }
//
// //
// final IRfQEventDispacher rfQEventDispacher = getRfQEventDispacher();
// rfQEventDispacher.fireBeforeUnClose(rfqResponse);
//
// //
// // Mark as NOT closed
// rfqResponse.setDocStatus(X_C_RfQResponse.DOCSTATUS_Completed);
// InterfaceWrapperHelper.save(rfqResponse);
// updateRfQResponseLinesStatus(rfqResponse);
//
// //
// rfQEventDispacher.fireAfterUnClose(rfqResponse);
//
// // Make sure it's saved
// InterfaceWrapperHelper.save(rfqResponse);
// }
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfqBL.java | 1 |
请完成以下Java代码 | public SpinRuntimeException unableToReadFromReader(Exception e) {
return new SpinRuntimeException(exceptionMessage("003", "Unable to read from reader"), e);
}
public SpinDataFormatException unrecognizableDataFormatException() {
return new SpinDataFormatException(exceptionMessage("004", "No matching data format detected"));
}
public SpinScriptException noScriptEnvFoundForLanguage(String scriptLanguage, String path) {
return new SpinScriptException(exceptionMessage("006", "No script script env found for script language '{}' at path '{}'", scriptLanguage, path));
}
public IOException unableToRewindReader() {
return new IOException(exceptionMessage("007", "Unable to rewind input stream: rewind buffering limit exceeded"));
}
public SpinDataFormatException multipleProvidersForDataformat(String dataFormatName) {
return new SpinDataFormatException(exceptionMessage("008", "Multiple providers found for dataformat '{}'", dataFormatName));
}
public void logDataFormats(Collection<DataFormat<?>> formats) {
if (isInfoEnabled()) {
for (DataFormat<?> format : formats) {
logDataFormat(format);
}
}
}
protected void logDataFormat(DataFormat<?> dataFormat) {
logInfo("009", "Discovered Spin data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName());
}
public void logDataFormatProvider(DataFormatProvider provider) {
if (isInfoEnabled()) {
logInfo("010", "Discovered Spin data format provider: {}[name = {}]",
provider.getClass().getName(), provider.getDataFormatName());
}
} | @SuppressWarnings("rawtypes")
public void logDataFormatConfigurator(DataFormatConfigurator configurator) {
if (isInfoEnabled()) {
logInfo("011", "Discovered Spin data format configurator: {}[dataformat = {}]",
configurator.getClass(), configurator.getDataFormatClass().getName());
}
}
public SpinDataFormatException classNotFound(String classname, ClassNotFoundException cause) {
return new SpinDataFormatException(exceptionMessage("012", "Class {} not found ", classname), cause);
}
public void tryLoadingClass(String classname, ClassLoader cl) {
logDebug("013", "Try loading class '{}' using classloader '{}'.", classname, cl);
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\logging\SpinCoreLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public KeyPair keyPair() {
try {
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Bean
public RSAKey rsaKey(KeyPair keyPair) {
return new RSAKey
.Builder((RSAPublicKey)keyPair.getPublic())
.privateKey(keyPair.getPrivate())
.keyID(UUID.randomUUID().toString())
.build();
}
@Bean | public JWKSource<SecurityContext> jwkSource(RSAKey rsaKey) {
var jwkSet = new JWKSet(rsaKey);
return (jwkSelector, context) -> jwkSelector.select(jwkSet);
}
@Bean
public JwtDecoder jwtDecoder(RSAKey rsaKey) throws JOSEException {
return NimbusJwtDecoder
.withPublicKey(rsaKey.toRSAPublicKey())
.build();
}
@Bean
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
} | repos\master-spring-and-spring-boot-main\71-spring-security\src\main\java\com\in28minutes\learnspringsecurity\jwt\JwtSecurityConfiguration.java | 2 |
请完成以下Java代码 | public class CompositeSessionAuthenticationStrategy implements SessionAuthenticationStrategy {
private final Log logger = LogFactory.getLog(getClass());
private final List<SessionAuthenticationStrategy> delegateStrategies;
public CompositeSessionAuthenticationStrategy(List<SessionAuthenticationStrategy> delegateStrategies) {
Assert.notEmpty(delegateStrategies, "delegateStrategies cannot be null or empty");
for (SessionAuthenticationStrategy strategy : delegateStrategies) {
Assert.notNull(strategy, () -> "delegateStrategies cannot contain null entires. Got " + delegateStrategies);
}
this.delegateStrategies = delegateStrategies;
}
@Override
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) throws SessionAuthenticationException {
int currentPosition = 0;
int size = this.delegateStrategies.size(); | for (SessionAuthenticationStrategy delegate : this.delegateStrategies) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Preparing session with %s (%d/%d)",
delegate.getClass().getSimpleName(), ++currentPosition, size));
}
delegate.onAuthentication(authentication, request, response);
}
}
@Override
public String toString() {
return getClass().getName() + " [delegateStrategies = " + this.delegateStrategies + "]";
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\session\CompositeSessionAuthenticationStrategy.java | 1 |
请完成以下Java代码 | public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Time Type. | @param S_TimeType_ID
Type of time recorded
*/
public void setS_TimeType_ID (int S_TimeType_ID)
{
if (S_TimeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_TimeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_TimeType_ID, Integer.valueOf(S_TimeType_ID));
}
/** Get Time Type.
@return Type of time recorded
*/
public int getS_TimeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_TimeType_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_S_TimeType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class HealthContributorRegistryAutoConfiguration {
HealthContributorRegistryAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean(HealthContributorRegistry.class)
DefaultHealthContributorRegistry healthContributorRegistry(Map<String, HealthContributor> contributorBeans,
ObjectProvider<HealthContributorNameGenerator> nameGeneratorProvider,
List<HealthContributorNameValidator> nameValidators) {
HealthContributorNameGenerator nameGenerator = nameGeneratorProvider
.getIfAvailable(HealthContributorNameGenerator::withoutStandardSuffixes);
return new DefaultHealthContributorRegistry(nameValidators, nameGenerator.registrar(contributorBeans));
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(Flux.class) | static class ReactiveHealthContributorRegistryConfiguration {
@Bean
@ConditionalOnMissingBean(ReactiveHealthContributorRegistry.class)
DefaultReactiveHealthContributorRegistry reactiveHealthContributorRegistry(
Map<String, ReactiveHealthContributor> contributorBeans,
ObjectProvider<HealthContributorNameGenerator> nameGeneratorProvider,
List<HealthContributorNameValidator> nameValidators) {
HealthContributorNameGenerator nameGenerator = nameGeneratorProvider
.getIfAvailable(HealthContributorNameGenerator::withoutStandardSuffixes);
return new DefaultReactiveHealthContributorRegistry(nameValidators,
nameGenerator.registrar(contributorBeans));
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\registry\HealthContributorRegistryAutoConfiguration.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
if (context.isMoreThanAllowedSelected(MAX_SELECTION_SIZE))
{
return ProcessPreconditionsResolution.rejectBecauseTooManyRecordsSelected(MAX_SELECTION_SIZE);
}
final IQueryFilter<I_C_Order> queryFilter = context.getQueryFilter(I_C_Order.class);
final List<I_C_Order> selectedOrders = orderBL.getByQueryFilter(queryFilter);
if (selectedOrders.stream().anyMatch(orderBL::isRequisition))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("is purchase requisition");
}
if (selectedOrders.stream().anyMatch(o -> !orderBL.isCompleted(o)))
{
return ProcessPreconditionsResolution.reject(MSG_DOCUMENT_NOT_COMPLETE);
} | return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final Set<OrderId> orderIds = orderBL.getByQueryFilter(getProcessInfo().getQueryFilterOrElseFalse())
.stream()
.map(o -> OrderId.ofRepoId(o.getC_Order_ID()))
.collect(Collectors.toSet());
if (shipperTransportationBL.isAnyOrderAssignedToDifferentTransportationOrder(p_M_ShipperTransportation_ID, orderIds))
{
throw new AdempiereException(MSG_ORDER_ASSIGNED_TO_DIFFERENT_TRANSPORTATION_ORDER);
}
orderToShipperTransportationService.addPurchaseOrdersToShipperTransportation(p_M_ShipperTransportation_ID, orderIds);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\process\C_Order_AddTo_M_ShipperTransportation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DeviceProfileImportService extends BaseEntityImportService<DeviceProfileId, DeviceProfile, EntityExportData<DeviceProfile>> {
private final DeviceProfileService deviceProfileService;
@Override
protected void setOwner(TenantId tenantId, DeviceProfile deviceProfile, IdProvider idProvider) {
deviceProfile.setTenantId(tenantId);
}
@Override
protected DeviceProfile prepare(EntitiesImportCtx ctx, DeviceProfile deviceProfile, DeviceProfile old, EntityExportData<DeviceProfile> exportData, IdProvider idProvider) {
deviceProfile.setDefaultRuleChainId(idProvider.getInternalId(deviceProfile.getDefaultRuleChainId()));
deviceProfile.setDefaultEdgeRuleChainId(idProvider.getInternalId(deviceProfile.getDefaultEdgeRuleChainId()));
deviceProfile.setDefaultDashboardId(idProvider.getInternalId(deviceProfile.getDefaultDashboardId()));
deviceProfile.setFirmwareId(idProvider.getInternalId(deviceProfile.getFirmwareId(), false));
deviceProfile.setSoftwareId(idProvider.getInternalId(deviceProfile.getSoftwareId(), false));
return deviceProfile;
}
@Override
protected DeviceProfile saveOrUpdate(EntitiesImportCtx ctx, DeviceProfile deviceProfile, EntityExportData<DeviceProfile> exportData, IdProvider idProvider, CompareResult compareResult) {
boolean toUpdate = ctx.isFinalImportAttempt() || ctx.getCurrentImportResult().isUpdatedAllExternalIds();
if (toUpdate) {
deviceProfile.setFirmwareId(idProvider.getInternalId(deviceProfile.getFirmwareId()));
deviceProfile.setSoftwareId(idProvider.getInternalId(deviceProfile.getSoftwareId()));
}
DeviceProfile saved = deviceProfileService.saveDeviceProfile(deviceProfile);
if (toUpdate) {
importCalculatedFields(ctx, saved, exportData, idProvider);
}
return saved;
}
@Override
protected void onEntitySaved(User user, DeviceProfile savedDeviceProfile, DeviceProfile oldDeviceProfile) {
logEntityActionService.logEntityAction(savedDeviceProfile.getTenantId(), savedDeviceProfile.getId(), savedDeviceProfile,
null, oldDeviceProfile == null ? ActionType.ADDED : ActionType.UPDATED, user);
} | @Override
protected DeviceProfile deepCopy(DeviceProfile deviceProfile) {
return new DeviceProfile(deviceProfile);
}
@Override
protected void cleanupForComparison(DeviceProfile deviceProfile) {
super.cleanupForComparison(deviceProfile);
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE_PROFILE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\DeviceProfileImportService.java | 2 |
请完成以下Java代码 | public byte[] getModelEditorSourceExtra(String modelId) {
return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
}
@Override
public void addCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override
public void addCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterUser(String processDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null));
}
@Override | public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId));
}
@Override
public List<ValidationError> validateProcess(BpmnModel bpmnModel) {
return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel));
}
@Override
public List<DmnDecision> getDecisionsForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetDecisionsForProcessDefinitionCmd(processDefinitionId));
}
@Override
public List<FormDefinition> getFormDefinitionsForProcessDefinition(String processDefinitionId) {
return commandExecutor.execute(new GetFormDefinitionsForProcessDefinitionCmd(processDefinitionId));
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\RepositoryServiceImpl.java | 1 |
请完成以下Java代码 | public class Employee {
protected String firstName;
protected int id;
/**
* Gets the value of the firstName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFirstName() {
return firstName;
}
/**
* Sets the value of the firstName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFirstName(String value) {
this.firstName = value;
}
/** | * Gets the value of the id property.
*
*/
public int getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(int value) {
this.id = value;
}
} | repos\tutorials-master\web-modules\jee-7\src\main\java\com\baeldung\jaxws\client\Employee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ImportConfigRepository
{
private final IBPGroupDAO groupDAO = Services.get(IBPGroupDAO.class);
public ImportConfig getForQueryOrNull(@NonNull final BPartnerQuery query)
{
final I_HC_Forum_Datenaustausch_Config configRecord = ConfigRepositoryUtil.retrieveRecordForQueryOrNull(query);
return ofRecordOrNull(configRecord);
}
private ImportConfig ofRecordOrNull(@Nullable final I_HC_Forum_Datenaustausch_Config configRecord)
{
if (configRecord == null)
{
return null;
}
final ImportConfig.ImportConfigBuilder builder = ImportConfig.builder();
final BPGroupId patientBPGroupId = BPGroupId.ofRepoIdOrNull(configRecord.getImportedPartientBP_Group_ID());
if (patientBPGroupId != null)
{
final I_C_BP_Group patientBPartnerGroup = Check.assumeNotNull(
groupDAO.getById(patientBPGroupId),
"Unable to load BP_Group referenced by HC_Forum_Datenaustausch_Config.ImportedPartientBP_Group_ID={}. HC_Forum_Datenaustausch_Config={}",
patientBPGroupId.getRepoId(), configRecord);
builder.partientBPartnerGroupName(patientBPartnerGroup.getName());
}
final BPGroupId municipalityBPGroupId = BPGroupId.ofRepoIdOrNull(configRecord.getImportedMunicipalityBP_Group_ID()); | if (municipalityBPGroupId != null)
{
final I_C_BP_Group municipalityBPartnerGroup = Check.assumeNotNull(
groupDAO.getById(municipalityBPGroupId),
"Unable to load BP_Group referenced by HC_Forum_Datenaustausch_Config.ImportedMunicipalityBP_Group_ID={}. HC_Forum_Datenaustausch_Config={}",
municipalityBPGroupId.getRepoId(), configRecord);
builder.municipalityBPartnerGroupName(municipalityBPartnerGroup.getName());
}
if (Check.isNotBlank(configRecord.getImportedBPartnerLanguage()))
{
builder.languageCode(configRecord.getImportedBPartnerLanguage());
}
return builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\config\ImportConfigRepository.java | 2 |
请完成以下Java代码 | public class MigrationExecutorException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = 5403917143953357678L;
private final boolean fatal;
/**
* Wrap an {@link Throwable} exception with a {@link MigrationExecutorException}
*
* @param e
*/
public MigrationExecutorException(Throwable e)
{
super(e);
fatal = true;
}
/**
* Create a new {@link MigrationExecutorException}. The fatal flag should be set to true when the execution must be ended on error.
*
* @param message
* @param fatal
*/
public MigrationExecutorException(String message, boolean fatal)
{
super(message);
this.fatal = fatal;
}
/**
* Get the exception's fatal flag.
*
* @return boolean | */
public boolean isFatal()
{
return fatal;
}
/**
* Checks if a {@link MigrationExecutorException} is fatal for an instance of {@link Throwable}.
*
* @param e
* @return boolean
*/
public static boolean isFatal(Throwable e)
{
if (e instanceof MigrationExecutorException)
{
final MigrationExecutorException mee = (MigrationExecutorException)e;
return mee.isFatal();
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\MigrationExecutorException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getM_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID);
}
@Override
public void setOpenAmt (final BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
@Override
public BigDecimal getOpenAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_OpenAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPaidAmt (final BigDecimal PaidAmt)
{
set_Value (COLUMNNAME_PaidAmt, PaidAmt);
}
@Override
public BigDecimal getPaidAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PaidAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
} | /**
* Status AD_Reference_ID=541890
* Reference name: C_POS_Order_Status
*/
public static final int STATUS_AD_Reference_ID=541890;
/** Drafted = DR */
public static final String STATUS_Drafted = "DR";
/** WaitingPayment = WP */
public static final String STATUS_WaitingPayment = "WP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
/** Voided = VO */
public static final String STATUS_Voided = "VO";
/** Closed = CL */
public static final String STATUS_Closed = "CL";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
@Override
public void setTaxAmt (final BigDecimal TaxAmt)
{
set_Value (COLUMNNAME_TaxAmt, TaxAmt);
}
@Override
public BigDecimal getTaxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Order.java | 2 |
请完成以下Java代码 | public String getSubScopeId() {
throw new UnsupportedOperationException("Not supported to get sub scope id");
}
@Override
public String getScopeType() {
throw new UnsupportedOperationException("Not supported to scope type");
}
@Override
public String getTaskId() {
throw new UnsupportedOperationException("Not supported to get task id");
}
@Override
public String getTextValue() {
return node.path("textValue").stringValue(null);
}
@Override
public void setTextValue(String textValue) {
throw new UnsupportedOperationException("Not supported to set text value");
}
@Override
public String getTextValue2() {
return node.path("textValues").stringValue(null);
}
@Override
public void setTextValue2(String textValue2) {
throw new UnsupportedOperationException("Not supported to set text value2");
}
@Override
public Long getLongValue() {
JsonNode longNode = node.path("longValue");
if (longNode.isNumber()) {
return longNode.longValue();
}
return null;
}
@Override
public void setLongValue(Long longValue) {
throw new UnsupportedOperationException("Not supported to set long value");
}
@Override
public Double getDoubleValue() {
JsonNode doubleNode = node.path("doubleValue");
if (doubleNode.isNumber()) {
return doubleNode.doubleValue(); | }
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
throw new UnsupportedOperationException("Not supported to set double value");
}
@Override
public byte[] getBytes() {
throw new UnsupportedOperationException("Not supported to get bytes");
}
@Override
public void setBytes(byte[] bytes) {
throw new UnsupportedOperationException("Not supported to set bytes");
}
@Override
public Object getCachedValue() {
throw new UnsupportedOperationException("Not supported to set get cached value");
}
@Override
public void setCachedValue(Object cachedValue) {
throw new UnsupportedOperationException("Not supported to set cached value");
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delete\BatchDeleteCaseConfig.java | 1 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_S_ResourceUnAvailable[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Date From.
@param DateFrom
Starting date for a range
*/
public void setDateFrom (Timestamp DateFrom)
{
set_Value (COLUMNNAME_DateFrom, DateFrom);
}
/** Get Date From.
@return Starting date for a range
*/
public Timestamp getDateFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Date To.
@param DateTo
End date of a date range
*/
public void setDateTo (Timestamp DateTo)
{
set_Value (COLUMNNAME_DateTo, DateTo);
}
/** Get Date To.
@return End date of a date range
*/
public Timestamp getDateTo ()
{
return (Timestamp)get_Value(COLUMNNAME_DateTo);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public I_S_Resource getS_Resource() throws RuntimeException
{
return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name)
.getPO(getS_Resource_ID(), get_TrxName()); }
/** Set Resource.
@param S_Resource_ID
Resource
*/
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
} | /** Get Resource.
@return Resource
*/
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID()));
}
/** Set Resource Unavailability.
@param S_ResourceUnAvailable_ID Resource Unavailability */
public void setS_ResourceUnAvailable_ID (int S_ResourceUnAvailable_ID)
{
if (S_ResourceUnAvailable_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, Integer.valueOf(S_ResourceUnAvailable_ID));
}
/** Get Resource Unavailability.
@return Resource Unavailability */
public int getS_ResourceUnAvailable_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceUnAvailable_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_S_ResourceUnAvailable.java | 1 |
请完成以下Java代码 | public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Gelieferte Menge.
@param QtyDelivered
Delivered Quantity
*/
@Override
public void setQtyDelivered (java.math.BigDecimal QtyDelivered)
{
set_Value (COLUMNNAME_QtyDelivered, QtyDelivered);
}
/** Get Gelieferte Menge.
@return Delivered Quantity
*/
@Override
public java.math.BigDecimal getQtyDelivered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Berechn. Menge.
@param QtyInvoiced
Menge, die bereits in Rechnung gestellt wurde
*/
@Override
public void setQtyInvoiced (java.math.BigDecimal QtyInvoiced)
{
set_Value (COLUMNNAME_QtyInvoiced, QtyInvoiced);
}
/** Get Berechn. Menge.
@return Menge, die bereits in Rechnung gestellt wurde
*/
@Override
public java.math.BigDecimal getQtyInvoiced ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced);
if (bd == null)
return Env.ZERO;
return bd;
} | @Override
public org.compiere.model.I_M_RMALine getRef_RMALine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Ref_RMALine_ID, org.compiere.model.I_M_RMALine.class);
}
@Override
public void setRef_RMALine(org.compiere.model.I_M_RMALine Ref_RMALine)
{
set_ValueFromPO(COLUMNNAME_Ref_RMALine_ID, org.compiere.model.I_M_RMALine.class, Ref_RMALine);
}
/** Set Referenced RMA Line.
@param Ref_RMALine_ID Referenced RMA Line */
@Override
public void setRef_RMALine_ID (int Ref_RMALine_ID)
{
if (Ref_RMALine_ID < 1)
set_Value (COLUMNNAME_Ref_RMALine_ID, null);
else
set_Value (COLUMNNAME_Ref_RMALine_ID, Integer.valueOf(Ref_RMALine_ID));
}
/** Get Referenced RMA Line.
@return Referenced RMA Line */
@Override
public int getRef_RMALine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_RMALine_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_M_RMALine.java | 1 |
请完成以下Java代码 | public class MigrationApply extends JavaProcess
{
private int p_AD_Migration_ID = -1;
private static final String PARAM_FailOnError = "FailOnError";
private boolean p_FailOnError = true;
private static final String PARAM_AD_Migration_Operation = "AD_Migration_Operation";
private MigrationOperation p_MigrationOperation = MigrationOperation.BOTH;
@Override
protected void prepare()
{
p_AD_Migration_ID = getRecord_ID();
for (ProcessInfoParameter p : getParametersAsArray())
{
final String name = p.getParameterName();
if (PARAM_FailOnError.equals(name))
{
p_FailOnError = p.getParameterAsBoolean();
}
else if (PARAM_AD_Migration_Operation.equals(name))
{
p_MigrationOperation = MigrationOperation.valueOf(p.getParameterAsString());
}
}
}
@Override
protected String doIt() throws Exception
{ | final IMigrationExecutorProvider executorProvider = Services.get(IMigrationExecutorProvider.class);
final IMigrationExecutorContext context = executorProvider.createInitialContext(getCtx());
context.setFailOnFirstError(p_FailOnError);
context.setMigrationOperation(p_MigrationOperation);
final IMigrationExecutor executor = executorProvider.newMigrationExecutor(context, p_AD_Migration_ID);
executor.execute();
final List<Exception> errors = executor.getExecutionErrors();
for (final Exception error : errors)
{
addLog("Error: " + error.getLocalizedMessage());
}
return executor.getStatusDescription();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\MigrationApply.java | 1 |
请完成以下Java代码 | private static Instant extractAllocationDate(final I_C_AllocationHdr ah, final @NonNull InvoiceOpenRequest.DateColumn dateColumn)
{
switch (dateColumn)
{
case DateAcct:
return ah.getDateAcct().toInstant();
case DateTrx:
default:
return ah.getDateTrx().toInstant();
}
}
private static Instant extractInvoiceDate(final I_C_Invoice invoice, final @NonNull InvoiceOpenRequest.DateColumn dateColumn)
{
switch (dateColumn)
{
case DateAcct:
return invoice.getDateAcct().toInstant();
case DateTrx:
default:
return invoice.getDateInvoiced().toInstant();
}
}
@Override
public BigDecimal retrieveWriteoffAmt(final org.compiere.model.I_C_Invoice invoice)
{
return retrieveWriteoffAmt(invoice, o -> {
final I_C_AllocationLine line = (I_C_AllocationLine)o;
return line.getWriteOffAmt();
});
}
private BigDecimal retrieveWriteoffAmt(final org.compiere.model.I_C_Invoice invoice, final TypedAccessor<BigDecimal> amountAccessor)
{
BigDecimal sum = BigDecimal.ZERO;
for (final I_C_AllocationLine line : retrieveAllocationLines(invoice)) | {
final I_C_AllocationHdr ah = line.getC_AllocationHdr();
final BigDecimal lineWriteOff = amountAccessor.getValue(line);
if (null != ah && ah.getC_Currency_ID() != invoice.getC_Currency_ID())
{
final BigDecimal lineWriteOffConv = Services.get(ICurrencyBL.class).convert(
lineWriteOff, // Amt
CurrencyId.ofRepoId(ah.getC_Currency_ID()), // CurFrom_ID
CurrencyId.ofRepoId(invoice.getC_Currency_ID()), // CurTo_ID
ah.getDateTrx().toInstant(), // ConvDate
CurrencyConversionTypeId.ofRepoIdOrNull(invoice.getC_ConversionType_ID()),
ClientId.ofRepoId(line.getAD_Client_ID()),
OrgId.ofRepoId(line.getAD_Org_ID()));
sum = sum.add(lineWriteOffConv);
}
else
{
sum = sum.add(lineWriteOff);
}
}
return sum;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\impl\PlainAllocationDAO.java | 1 |
请完成以下Java代码 | public String getType() {
if (type == null) {
return "esrQR";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the iban property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIban() {
return iban;
}
/**
* Sets the value of the iban property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIban(String value) {
this.iban = value;
}
/**
* Gets the value of the referenceNumber property.
* | * @return
* possible object is
* {@link String }
*
*/
public String getReferenceNumber() {
return referenceNumber;
}
/**
* Sets the value of the referenceNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenceNumber(String value) {
this.referenceNumber = value;
}
/**
* Gets the value of the customerNote property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCustomerNote() {
return customerNote;
}
/**
* Sets the value of the customerNote property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCustomerNote(String value) {
this.customerNote = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\EsrQRType.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8080
logging:
level:
cn.javastack.springboot.ai: DEBUG
spring:
ai:
deepseek:
api-key: ${DEEPSEEK_API_KEY} # 安全起见,从系统环境变量读取
base-url: https://api.deepseek.com
chat:
options:
model: deepseek-chat
temperature: 0.5
mcp:
clie | nt:
stdio:
servers-configuration: classpath:mcp-servers-config.json
toolcallback:
enabled: true | repos\spring-boot-best-practice-master\spring-boot-ai\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setClientInfo(String name, String value) throws SQLClientInfoException
{
delegate.setClientInfo(name, value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException
{
delegate.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException
{
return delegate.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException
{
return delegate.getClientInfo();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException
{
return delegate.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException
{
return delegate.createStruct(typeName, attributes);
}
@Override
public void setSchema(String schema) throws SQLException
{
delegate.setSchema(schema);
}
@Override
public String getSchema() throws SQLException | {
return delegate.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException
{
delegate.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException
{
delegate.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException
{
return delegate.getNetworkTimeout();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperJdbcConnection.java | 2 |
请完成以下Java代码 | private JsonToPdxConverter newJsonToPdxConverter() {
return new JSONFormatterJsonToPdxConverter();
}
// TODO configure via an SPI
private ObjectMapper newObjectMapper() {
return new ObjectMapper();
}
/**
* Returns a reference to the configured {@link JsonToPdxConverter} used to convert from a single object,
* {@literal JSON} {@link String} to PDX (i.e. as a {@link PdxInstance}.
*
* @return a reference to the configured {@link JsonToPdxConverter}; never {@literal null}.
* @see org.springframework.geode.data.json.converter.JsonToPdxConverter
*/
protected @NonNull JsonToPdxConverter getJsonToPdxConverter() {
return this.converter;
}
/**
* Returns a reference to the configured Jackson {@link ObjectMapper}.
*
* @return a reference to the configured Jackson {@link ObjectMapper}; never {@literal null}.
* @see com.fasterxml.jackson.databind.ObjectMapper
*/
protected @NonNull ObjectMapper getObjectMapper() {
return this.objectMapper;
}
/**
* Converts the given {@link String JSON} containing multiple objects into an array of {@link PdxInstance} objects.
*
* @param json {@link String JSON} data to convert.
* @return an array of {@link PdxInstance} objects from the given {@link String JSON}.
* @throws IllegalStateException if the {@link String JSON} does not start with
* either a JSON array or a JSON object.
* @see org.apache.geode.pdx.PdxInstance
*/
@Nullable @Override
public PdxInstance[] convert(String json) {
try {
JsonNode jsonNode = getObjectMapper().readTree(json);
List<PdxInstance> pdxList = new ArrayList<>();
if (isArray(jsonNode)) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
JsonToPdxConverter converter = getJsonToPdxConverter(); | for (JsonNode object : asIterable(CollectionUtils.nullSafeIterator(arrayNode.elements()))) {
pdxList.add(converter.convert(object.toString()));
}
}
else if (isObject(jsonNode)) {
ObjectNode objectNode = (ObjectNode) jsonNode;
pdxList.add(getJsonToPdxConverter().convert(objectNode.toString()));
}
else {
String message = String.format("Unable to process JSON node of type [%s];"
+ " expected either an [%s] or an [%s]", jsonNode.getNodeType(),
JsonNodeType.OBJECT, JsonNodeType.ARRAY);
throw new IllegalStateException(message);
}
return pdxList.toArray(new PdxInstance[0]);
}
catch (JsonProcessingException cause) {
throw new DataRetrievalFailureException("Failed to read JSON content", cause);
}
}
private boolean isArray(@Nullable JsonNode node) {
return node != null && (node.isArray() || JsonNodeType.ARRAY.equals(node.getNodeType()));
}
private boolean isObject(@Nullable JsonNode node) {
return node != null && (node.isObject() || JsonNodeType.OBJECT.equals(node.getNodeType()));
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToPdxConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
/**
* 角色名称
*
* @return
*/
public String getRoleName() {
return roleName; | }
/**
* 角色名称
*
* @return
*/
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public PmsRole() {
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\entity\PmsRole.java | 2 |
请完成以下Java代码 | public void intervalRemoved(final ListDataEvent e)
{
final int index0 = e.getIndex0();
for (int i = index0; i <= e.getIndex1(); i++)
{
final SideActionsGroupPanel groupComp = (SideActionsGroupPanel)contentPanel.getComponent(index0);
contentPanel.remove(index0);
destroyGroupComponent(groupComp);
}
refreshUI();
}
@Override
public void contentsChanged(final ListDataEvent e)
{
logger.warn("Changing the content is not synchronized: " + e);
}
};
private final PropertyChangeListener groupPanelChangedListener = new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
refreshUI();
}
};
public SideActionsGroupsListPanel()
{
super();
contentPanel = new JXTaskPaneContainer();
contentPanel.setScrollableWidthHint(ScrollableSizeHint.FIT);
contentPanel.setOpaque(false);
final JScrollPane contentPaneScroll = new JScrollPane();
contentPaneScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
contentPaneScroll.getViewport().add(contentPanel);
contentPaneScroll.setOpaque(false);
setLayout(new BorderLayout());
this.add(contentPaneScroll, BorderLayout.CENTER);
this.setOpaque(false);
refreshUI();
}
public void setModel(final ISideActionsGroupsListModel model)
{
if (this.model == model)
{
return;
}
if (this.model != null)
{
model.getGroups().removeListDataListener(groupsListModelListener);
}
this.model = model;
renderAll();
if (this.model != null) | {
model.getGroups().addListDataListener(groupsListModelListener);
}
}
private void renderAll()
{
final ListModel<ISideActionsGroupModel> groups = model.getGroups();
for (int i = 0; i < groups.getSize(); i++)
{
final ISideActionsGroupModel group = groups.getElementAt(i);
final SideActionsGroupPanel groupComp = createGroupComponent(group);
contentPanel.add(groupComp);
}
refreshUI();
}
private final SideActionsGroupPanel createGroupComponent(final ISideActionsGroupModel group)
{
final SideActionsGroupPanel groupComp = new SideActionsGroupPanel();
groupComp.setModel(group);
groupComp.addPropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener);
return groupComp;
}
private void destroyGroupComponent(final SideActionsGroupPanel groupComp)
{
groupComp.removePropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener);
}
protected void refreshUI()
{
autoHideIfNeeded();
contentPanel.revalidate();
}
/**
* Auto-hide if no groups or groups are not visible
*/
private final void autoHideIfNeeded()
{
boolean haveVisibleGroups = false;
for (Component groupComp : contentPanel.getComponents())
{
if (groupComp.isVisible())
{
haveVisibleGroups = true;
break;
}
}
setVisible(haveVisibleGroups);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupsListPanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable ConfigDataResource getLocation() {
return this.location;
}
/**
* Return the name of the property.
* @return the property name
*/
public String getPropertyName() {
return this.propertyName;
}
/**
* Return the origin or the property or {@code null}.
* @return the property origin
*/
public @Nullable Origin getOrigin() {
return this.origin;
}
/**
* Throw an {@link InactiveConfigDataAccessException} if the given
* {@link ConfigDataEnvironmentContributor} contains the property. | * @param contributor the contributor to check
* @param name the name to check
*/
static void throwIfPropertyFound(ConfigDataEnvironmentContributor contributor, ConfigurationPropertyName name) {
ConfigurationPropertySource source = contributor.getConfigurationPropertySource();
ConfigurationProperty property = (source != null) ? source.getConfigurationProperty(name) : null;
if (property != null) {
PropertySource<?> propertySource = contributor.getPropertySource();
ConfigDataResource location = contributor.getResource();
Assert.state(propertySource != null, "'propertySource' must not be null");
throw new InactiveConfigDataAccessException(propertySource, location, name.toString(),
property.getOrigin());
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\InactiveConfigDataAccessException.java | 2 |
请完成以下Java代码 | public TrustManagerFactory getTrustManagerFactory() {
return trustManagerFactory;
}
};
}
/**
* Factory method to create a new {@link SslManagerBundle} backed by the given
* {@link SslBundle} and {@link SslBundleKey}.
* @param storeBundle the SSL store bundle
* @param key the key reference
* @return a new {@link SslManagerBundle} instance
*/
static SslManagerBundle from(@Nullable SslStoreBundle storeBundle, @Nullable SslBundleKey key) {
return new DefaultSslManagerBundle(storeBundle, key);
}
/**
* Factory method to create a new {@link SslManagerBundle} using the given
* {@link TrustManagerFactory} and the default {@link KeyManagerFactory}.
* @param trustManagerFactory the trust manager factory
* @return a new {@link SslManagerBundle} instance
* @since 3.5.0
*/
static SslManagerBundle from(TrustManagerFactory trustManagerFactory) {
Assert.notNull(trustManagerFactory, "'trustManagerFactory' must not be null");
KeyManagerFactory defaultKeyManagerFactory = createDefaultKeyManagerFactory();
return of(defaultKeyManagerFactory, trustManagerFactory);
}
/**
* Factory method to create a new {@link SslManagerBundle} using the given
* {@link TrustManager TrustManagers} and the default {@link KeyManagerFactory}.
* @param trustManagers the trust managers to use
* @return a new {@link SslManagerBundle} instance
* @since 3.5.0
*/ | static SslManagerBundle from(TrustManager... trustManagers) {
Assert.notNull(trustManagers, "'trustManagers' must not be null");
KeyManagerFactory defaultKeyManagerFactory = createDefaultKeyManagerFactory();
TrustManagerFactory defaultTrustManagerFactory = createDefaultTrustManagerFactory();
return of(defaultKeyManagerFactory, FixedTrustManagerFactory.of(defaultTrustManagerFactory, trustManagers));
}
private static TrustManagerFactory createDefaultTrustManagerFactory() {
String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory;
try {
trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm);
trustManagerFactory.init((KeyStore) null);
}
catch (NoSuchAlgorithmException | KeyStoreException ex) {
throw new IllegalStateException(
"Unable to create TrustManagerFactory for default '%s' algorithm".formatted(defaultAlgorithm), ex);
}
return trustManagerFactory;
}
private static KeyManagerFactory createDefaultKeyManagerFactory() {
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory;
try {
keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
keyManagerFactory.init(null, null);
}
catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException ex) {
throw new IllegalStateException(
"Unable to create KeyManagerFactory for default '%s' algorithm".formatted(defaultAlgorithm), ex);
}
return keyManagerFactory;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\SslManagerBundle.java | 1 |
请完成以下Java代码 | public List<NotificationRequest> findNotificationRequestsByRuleIdAndOriginatorEntityIdAndStatus(TenantId tenantId, NotificationRuleId ruleId, EntityId originatorEntityId, NotificationRequestStatus status) {
return notificationRequestDao.findByRuleIdAndOriginatorEntityIdAndStatus(tenantId, ruleId, originatorEntityId, status);
}
@Override
public void deleteNotificationRequest(TenantId tenantId, NotificationRequest request) {
notificationRequestDao.removeById(tenantId, request.getUuidId());
notificationDao.deleteByRequestId(tenantId, request.getId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entity(request).entityId(request.getId()).build());
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
if (force) {
notificationRequestDao.removeById(tenantId, id.getId());
} else {
NotificationRequest notificationRequest = findNotificationRequestById(tenantId, (NotificationRequestId) id);
deleteNotificationRequest(tenantId, notificationRequest);
}
}
@Override
public PageData<NotificationRequest> findScheduledNotificationRequests(PageLink pageLink) {
return notificationRequestDao.findAllByStatus(NotificationRequestStatus.SCHEDULED, pageLink);
}
@Override
public void updateNotificationRequest(TenantId tenantId, NotificationRequestId requestId, NotificationRequestStatus requestStatus, NotificationRequestStats stats) {
notificationRequestDao.updateById(tenantId, requestId, requestStatus, stats);
}
// notifications themselves are left in the database until removed by ttl
@Override
public void deleteNotificationRequestsByTenantId(TenantId tenantId) {
notificationRequestDao.removeByTenantId(tenantId);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteNotificationRequestsByTenantId(tenantId);
} | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findNotificationRequestById(tenantId, new NotificationRequestId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(notificationRequestDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_REQUEST;
}
private static class NotificationRequestValidator extends DataValidator<NotificationRequest> {}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationRequestService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SignalRestServiceImpl extends AbstractRestProcessEngineAware implements SignalRestService {
public SignalRestServiceImpl(String engineName, ObjectMapper objectMapper) {
super(engineName, objectMapper);
}
@Override
public void throwSignal(SignalDto dto) {
String name = dto.getName();
if (name == null) {
throw new InvalidRequestException(Status.BAD_REQUEST, "No signal name given");
}
SignalEventReceivedBuilder signalEvent = createSignalEventReceivedBuilder(dto);
try {
signalEvent.send();
} catch (NotFoundException e) {
// keeping compatibility with older versions where ProcessEngineException (=> 500) was
// thrown; NotFoundException translates to 400 by default
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, e.getMessage());
}
}
protected SignalEventReceivedBuilder createSignalEventReceivedBuilder(SignalDto dto) {
RuntimeService runtimeService = getProcessEngine().getRuntimeService();
String name = dto.getName();
SignalEventReceivedBuilder signalEvent = runtimeService.createSignalEvent(name);
String executionId = dto.getExecutionId(); | if (executionId != null) {
signalEvent.executionId(executionId);
}
Map<String, VariableValueDto> variablesDto = dto.getVariables();
if (variablesDto != null) {
Map<String, Object> variables = VariableValueDto.toMap(variablesDto, getProcessEngine(), objectMapper);
signalEvent.setVariables(variables);
}
String tenantId = dto.getTenantId();
if (tenantId != null) {
signalEvent.tenantId(tenantId);
}
boolean isWithoutTenantId = dto.isWithoutTenantId();
if (isWithoutTenantId) {
signalEvent.withoutTenantId();
}
return signalEvent;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\SignalRestServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MybatisConfigurer {
@Bean
public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setTypeAliasesPackage(MODEL_PACKAGE);
//配置分页插件,详情请查阅官方文档
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页
properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页
properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数
pageHelper.setProperties(properties);
//添加插件
factory.setPlugins(new Interceptor[]{pageHelper});
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); | factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return factory.getObject();
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
mapperScannerConfigurer.setBasePackage(MAPPER_PACKAGE);
//配置通用Mapper,详情请查阅官方文档
Properties properties = new Properties();
properties.setProperty("mappers", MAPPER_INTERFACE_REFERENCE);
properties.setProperty("notEmpty", "false");//insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != ''
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
} | repos\spring-boot-api-project-seed-master\src\main\java\com\company\project\configurer\MybatisConfigurer.java | 2 |
请完成以下Java代码 | public void reset (String groupColumnName, String functionColumnName)
{
String key = groupColumnName + DELIMITER + functionColumnName;
PrintDataFunction pdf = (PrintDataFunction)m_groupFunction.get(key);
if (pdf != null)
pdf.reset();
} // reset
/**************************************************************************
* String Representation
* @return info
*/
public String toString ()
{
return toString(false);
} // toString
/**
* String Representation
* @param withData with data
* @return info
*/
public String toString (boolean withData)
{
StringBuffer sb = new StringBuffer("PrintDataGroup[");
sb.append("Groups=");
for (int i = 0; i < m_groups.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_groups.get(i));
}
if (withData)
{
Iterator it = m_groupMap.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupMap.get(key);
sb.append(":").append(key).append("=").append(value);
} | }
sb.append(";Functions=");
for (int i = 0; i < m_functions.size(); i++)
{
if (i != 0)
sb.append(",");
sb.append(m_functions.get(i));
}
if (withData)
{
Iterator it = m_groupFunction.keySet().iterator();
while(it.hasNext())
{
Object key = it.next();
Object value = m_groupFunction.get(key);
sb.append(":").append(key).append("=").append(value);
}
}
sb.append("]");
return sb.toString();
} // toString
} // PrintDataGroup | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | void setClientSettings(@Nullable HttpClientSettings clientSettings) {
this.clientSettings = clientSettings;
}
void setHttpMessageConvertersCustomizers(
@Nullable List<ClientHttpMessageConvertersCustomizer> httpMessageConvertersCustomizers) {
this.httpMessageConvertersCustomizers = httpMessageConvertersCustomizers;
}
void setRestTemplateCustomizers(@Nullable List<RestTemplateCustomizer> restTemplateCustomizers) {
this.restTemplateCustomizers = restTemplateCustomizers;
}
void setRestTemplateRequestCustomizers(
@Nullable List<RestTemplateRequestCustomizer<?>> restTemplateRequestCustomizers) {
this.restTemplateRequestCustomizers = restTemplateRequestCustomizers;
}
/**
* Configure the specified {@link RestTemplateBuilder}. The builder can be further
* tuned and default settings can be overridden.
* @param builder the {@link RestTemplateBuilder} instance to configure
* @return the configured builder
*/
public RestTemplateBuilder configure(RestTemplateBuilder builder) {
if (this.requestFactoryBuilder != null) {
builder = builder.requestFactoryBuilder(this.requestFactoryBuilder);
}
if (this.clientSettings != null) { | builder = builder.clientSettings(this.clientSettings);
}
if (this.httpMessageConvertersCustomizers != null) {
ClientBuilder clientBuilder = HttpMessageConverters.forClient();
this.httpMessageConvertersCustomizers.forEach((customizer) -> customizer.customize(clientBuilder));
builder = builder.messageConverters(clientBuilder.build());
}
builder = addCustomizers(builder, this.restTemplateCustomizers, RestTemplateBuilder::customizers);
builder = addCustomizers(builder, this.restTemplateRequestCustomizers, RestTemplateBuilder::requestCustomizers);
return builder;
}
private <T> RestTemplateBuilder addCustomizers(RestTemplateBuilder builder, @Nullable List<T> customizers,
BiFunction<RestTemplateBuilder, Collection<T>, RestTemplateBuilder> method) {
if (!ObjectUtils.isEmpty(customizers)) {
return method.apply(builder, customizers);
}
return builder;
}
} | repos\spring-boot-4.0.1\module\spring-boot-restclient\src\main\java\org\springframework\boot\restclient\autoconfigure\RestTemplateBuilderConfigurer.java | 2 |
请完成以下Java代码 | public ArrayList<Integer> arrayListItemsSetting() {
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
return list;
}
@Benchmark
public void arrayItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 1000000; i++) {
int item = array[i];
blackhole.consume(item);
}
}
@Benchmark
public void arrayListItemsRetrieval(Blackhole blackhole) {
for (int i = 0; i < 1000000; i++) { | int item = list.get(i);
blackhole.consume(item);
}
}
@Benchmark
public void arrayCloning(Blackhole blackhole) {
Integer[] newArray = array.clone();
blackhole.consume(newArray);
}
@Benchmark
public void arrayListCloning(Blackhole blackhole) {
ArrayList<Integer> newList = new ArrayList<>(list);
blackhole.consume(newList);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-5\src\main\java\com\baeldung\arrayandlistperformance\ArrayAndArrayListPerformance.java | 1 |
请完成以下Java代码 | public class TaxCategoryNotFoundException extends AdempiereException
{
public TaxCategoryNotFoundException(final Object documentLine, final String additionalReason)
{
super(buildMsg(documentLine, additionalReason));
}
public TaxCategoryNotFoundException(final Object documentLine)
{
super(buildMsg(documentLine, (String)null));
}
private static String buildMsg(final Object documentLine, final String additionalReason)
{
final StringBuilder msg = new StringBuilder(); | msg.append("@NotFound@ @C_TaxCategory_ID@");
if (!Check.isEmpty(additionalReason, true))
{
msg.append(": ").append(additionalReason);
}
if (documentLine != null)
{
msg.append("\nDocument: ").append(documentLine);
}
return msg.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\TaxCategoryNotFoundException.java | 1 |
请完成以下Java代码 | public class MigratingTransitionInstanceValidationReportImpl implements MigratingTransitionInstanceValidationReport {
protected String transitionInstanceId;
protected String sourceScopeId;
protected MigrationInstruction migrationInstruction;
protected List<String> failures = new ArrayList<String>();
public MigratingTransitionInstanceValidationReportImpl(MigratingTransitionInstance migratingTransitionInstance) {
this.transitionInstanceId = migratingTransitionInstance.getTransitionInstance().getId();
this.sourceScopeId = migratingTransitionInstance.getSourceScope().getId();
this.migrationInstruction = migratingTransitionInstance.getMigrationInstruction();
}
public String getSourceScopeId() {
return sourceScopeId;
}
public String getTransitionInstanceId() {
return transitionInstanceId; | }
public MigrationInstruction getMigrationInstruction() {
return migrationInstruction;
}
public void addFailure(String failure) {
failures.add(failure);
}
public boolean hasFailures() {
return !failures.isEmpty();
}
public List<String> getFailures() {
return failures;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\MigratingTransitionInstanceValidationReportImpl.java | 1 |
请完成以下Java代码 | public boolean isValueChanged(final Object model, final String columnName)
{
return getHelperThatCanHandle(model)
.isValueChanged(model, columnName);
}
@Override
public boolean isValueChanged(final Object model, final Set<String> columnNames)
{
return getHelperThatCanHandle(model)
.isValueChanged(model, columnNames);
}
@Override
public boolean isNull(final Object model, final String columnName)
{
if (model == null)
{
return true;
}
return getHelperThatCanHandle(model)
.isNull(model, columnName);
}
@Nullable
@Override
public <T> T getDynAttribute(@NonNull final Object model, @NonNull final String attributeName)
{
return getHelperThatCanHandle(model)
.getDynAttribute(model, attributeName);
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return getHelperThatCanHandle(model)
.setDynAttribute(model, attributeName, value);
}
@Nullable
@Override
public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier)
{
return getHelperThatCanHandle(model).computeDynAttributeIfAbsent(model, attributeName, supplier);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
if (model == null)
{
return null;
}
// Short-circuit: model is already a PO instance
if (model instanceof PO)
{
@SuppressWarnings("unchecked") final T po = (T)model;
return po;
}
return getHelperThatCanHandle(model)
.getPO(model, strict);
} | @Override
public Evaluatee getEvaluatee(final Object model)
{
if (model == null)
{
return null;
}
else if (model instanceof Evaluatee)
{
final Evaluatee evaluatee = (Evaluatee)model;
return evaluatee;
}
return getHelperThatCanHandle(model)
.getEvaluatee(model);
}
@Override
public boolean isCopy(@NonNull final Object model)
{
return getHelperThatCanHandle(model).isCopy(model);
}
@Override
public boolean isCopying(@NonNull final Object model)
{
return getHelperThatCanHandle(model).isCopying(model);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\CompositeInterfaceWrapperHelper.java | 1 |
请完成以下Java代码 | public String getServerInfo()
{
return "#" + getRunCount() + " - Last=" + m_summary.toString();
}
/**
* @return the isProcessRunning
*/
@Override
public boolean isProcessRunning()
{
return importProcessorRunning;
}
/**
* @param isProcessRunning the isProcessRunning to set | */
@Override
public void setProcessRunning(boolean isProcessRunning)
{
this.importProcessorRunning = isProcessRunning;
}
/**
* @return the mImportProcessor
*/
@Override
public I_IMP_Processor getMImportProcessor()
{
return mImportProcessor;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\ReplicationProcessor.java | 1 |
请完成以下Java代码 | private List<String> getDimensionColumnNames(final I_PA_ReportCube paReportCube)
{
final List<String> values = new ArrayList<String>();
if (paReportCube.isProductDim())
values.add("M_Product_ID");
if (paReportCube.isBPartnerDim())
values.add("C_BPartner_ID");
if (paReportCube.isProjectDim())
values.add("C_Project_ID");
if (paReportCube.isOrgTrxDim())
values.add("AD_OrgTrx_ID");
if (paReportCube.isSalesRegionDim())
values.add("C_SalesRegion_ID");
if (paReportCube.isActivityDim())
values.add("C_Activity_ID");
if (paReportCube.isCampaignDim())
values.add("C_Campaign_ID");
if (paReportCube.isLocToDim())
values.add("C_LocTo_ID");
if (paReportCube.isLocFromDim())
values.add("C_LocFrom_ID");
if (paReportCube.isUser1Dim())
values.add("User1_ID");
if (paReportCube.isUser2Dim())
values.add("User2_ID"); | if (paReportCube.isUserElement1Dim())
values.add("UserElement1_ID");
if (paReportCube.isUserElement2Dim())
values.add("UserElement2_ID");
if (paReportCube.isSubAcctDim())
values.add("C_SubAcct_ID");
if (paReportCube.isProjectPhaseDim())
values.add("C_ProjectPhase_ID");
if (paReportCube.isProjectTaskDim())
values.add("C_ProjectTask_ID");
// --(CASE v.IsGL_Category_ID WHEN 'Y' THEN f."GL_Category_ID END) GL_Category_ID
return values;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\cube\impl\FactAcctCubeUpdater.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setApiKey (final java.lang.String ApiKey)
{
set_Value (COLUMNNAME_ApiKey, ApiKey);
}
@Override
public java.lang.String getApiKey()
{
return get_ValueAsString(COLUMNNAME_ApiKey);
}
@Override
public de.metas.payment.sumup.repository.model.I_SUMUP_CardReader getSUMUP_CardReader()
{
return get_ValueAsPO(COLUMNNAME_SUMUP_CardReader_ID, de.metas.payment.sumup.repository.model.I_SUMUP_CardReader.class);
}
@Override
public void setSUMUP_CardReader(final de.metas.payment.sumup.repository.model.I_SUMUP_CardReader SUMUP_CardReader)
{
set_ValueFromPO(COLUMNNAME_SUMUP_CardReader_ID, de.metas.payment.sumup.repository.model.I_SUMUP_CardReader.class, SUMUP_CardReader);
}
@Override
public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID)
{
if (SUMUP_CardReader_ID < 1)
set_Value (COLUMNNAME_SUMUP_CardReader_ID, null);
else
set_Value (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID);
}
@Override | public int getSUMUP_CardReader_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID);
}
@Override
public void setSUMUP_Config_ID (final int SUMUP_Config_ID)
{
if (SUMUP_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
}
@Override
public int getSUMUP_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID);
}
@Override
public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code)
{
set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code);
}
@Override
public java.lang.String getSUMUP_merchant_code()
{
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Config.java | 2 |
请完成以下Java代码 | public Map<String, EventResourceEntity> getResources() {
return resources;
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("category", this.category);
persistentState.put("tenantId", tenantId);
persistentState.put("parentDeploymentId", parentDeploymentId);
return persistentState;
}
// Deployed artifacts manipulation ////////////////////////////////////////////
@Override
public void addDeployedArtifact(Object deployedArtifact) {
if (deployedArtifacts == null) {
deployedArtifacts = new HashMap<>();
}
Class<?> clazz = deployedArtifact.getClass();
List<Object> artifacts = deployedArtifacts.get(clazz);
if (artifacts == null) {
artifacts = new ArrayList<>();
deployedArtifacts.put(clazz, artifacts);
}
artifacts.add(deployedArtifact);
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getDeployedArtifacts(Class<T> clazz) {
for (Class<?> deployedArtifactsClass : deployedArtifacts.keySet()) {
if (clazz.isAssignableFrom(deployedArtifactsClass)) {
return (List<T>) deployedArtifacts.get(deployedArtifactsClass);
}
}
return null;
}
// getters and setters ////////////////////////////////////////////////////////
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override | public String getParentDeploymentId() {
return parentDeploymentId;
}
@Override
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
@Override
public void setResources(Map<String, EventResourceEntity> resources) {
this.resources = resources;
}
@Override
public Date getDeploymentTime() {
return deploymentTime;
}
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "EventDeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDeploymentEntityImpl.java | 1 |
请完成以下Java代码 | public HelloWorld lookup() throws NamingException {
// The app name is the EAR name of the deployed EJB without .ear suffix.
// Since we haven't deployed the application as a .ear, the app name for
// us will be an empty string
final String appName = "";
final String moduleName = "spring-ejb-remote";
final String distinctName = "";
final String beanName = "HelloWorld";
final String viewClassName = HelloWorld.class.getName();
final String toLookup = String.format("ejb:%s/%s/%s/%s!%s", appName, moduleName, distinctName, beanName, viewClassName);
return (HelloWorld) context.lookup(toLookup);
}
public void createInitialContext() throws NamingException {
Properties prop = new Properties();
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); | prop.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
prop.put(Context.PROVIDER_URL, "http-remoting://127.0.0.1:8080");
prop.put(Context.SECURITY_PRINCIPAL, "testUser");
prop.put(Context.SECURITY_CREDENTIALS, "admin1234!");
prop.put("jboss.naming.client.ejb.context", false);
context = new InitialContext(prop);
}
public void closeContext() throws NamingException {
if (context != null) {
context.close();
}
}
} | repos\tutorials-master\spring-ejb-modules\spring-ejb-client\src\main\java\com\baeldung\ejb\client\EJBClient.java | 1 |
请完成以下Java代码 | protected void initJpa() {
super.initJpa();
if (jpaEntityManagerFactory != null) {
sessionFactories.put(EntityManagerSession.class, new SpringEntityManagerSessionFactory(jpaEntityManagerFactory, jpaHandleTransaction, jpaCloseEntityManager));
}
}
protected void autoDeployResources(ProcessEngine processEngine) {
if (deploymentResources != null && deploymentResources.length > 0) {
final AutoDeploymentStrategy strategy = getAutoDeploymentStrategy(deploymentMode);
strategy.deployResources(deploymentName, deploymentResources, processEngine.getRepositoryService());
}
}
@Override
public ProcessEngineConfiguration setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
return super.setDataSource(dataSource);
} else {
// Wrap datasource in Transaction-aware proxy
DataSource proxiedDataSource = new TransactionAwareDataSourceProxy(dataSource);
return super.setDataSource(proxiedDataSource);
}
}
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public String getDeploymentName() {
return deploymentName;
}
public void setDeploymentName(String deploymentName) {
this.deploymentName = deploymentName;
}
public Resource[] getDeploymentResources() {
return deploymentResources;
} | public void setDeploymentResources(Resource[] deploymentResources) {
this.deploymentResources = deploymentResources;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public String getDeploymentMode() {
return deploymentMode;
}
public void setDeploymentMode(String deploymentMode) {
this.deploymentMode = deploymentMode;
}
/**
* Gets the {@link AutoDeploymentStrategy} for the provided mode. This method may be overridden to implement custom deployment strategies if required, but implementors should take care not to
* return <code>null</code>.
*
* @param mode the mode to get the strategy for
* @return the deployment strategy to use for the mode. Never <code>null</code>
*/
protected AutoDeploymentStrategy getAutoDeploymentStrategy(final String mode) {
AutoDeploymentStrategy result = new DefaultAutoDeploymentStrategy();
for (final AutoDeploymentStrategy strategy : deploymentStrategies) {
if (strategy.handlesMode(mode)) {
result = strategy;
break;
}
}
return result;
}
} | repos\flowable-engine-main\modules\flowable5-spring\src\main\java\org\activiti\spring\SpringProcessEngineConfiguration.java | 1 |
请完成以下Java代码 | public void execute()
{
// Add Line
if (m_node != null && nodeToId != null)
{
final I_AD_WF_NodeNext newLine = InterfaceWrapperHelper.newInstance(I_AD_WF_NodeNext.class);
newLine.setAD_Org_ID(OrgId.ANY.getRepoId());
newLine.setAD_WF_Node_ID(m_node.getId().getRepoId());
newLine.setAD_WF_Next_ID(nodeToId.getRepoId());
InterfaceWrapperHelper.save(newLine);
log.info("Add Line to " + m_node + " -> " + newLine);
m_parent.load(m_wf.getId(), true);
}
// Delete Node
else if (m_node != null && nodeToId == null)
{
log.info("Delete Node: " + m_node); | Services.get(IADWorkflowDAO.class).deleteNodeById(m_node.getId());
m_parent.load(m_wf.getId(), true);
}
// Delete Line
else if (m_line != null)
{
log.info("Delete Line: " + m_line);
Services.get(IADWorkflowDAO.class).deleteNodeTransitionById(m_line.getId());
m_parent.load(m_wf.getId(), true);
}
else
log.error("No Action??");
} // execute
} // WFPopupItem
} // WFContentPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFContentPanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HistoricDetailBaseResource {
private static Map<String, QueryProperty> allowedSortProperties = new HashMap<>();
static {
allowedSortProperties.put("processInstanceId", HistoricDetailQueryProperty.PROCESS_INSTANCE_ID);
allowedSortProperties.put("time", HistoricDetailQueryProperty.TIME);
allowedSortProperties.put("name", HistoricDetailQueryProperty.VARIABLE_NAME);
allowedSortProperties.put("revision", HistoricDetailQueryProperty.VARIABLE_REVISION);
allowedSortProperties.put("variableType", HistoricDetailQueryProperty.VARIABLE_TYPE);
}
@Autowired
protected RestResponseFactory restResponseFactory;
@Autowired
protected HistoryService historyService;
@Autowired(required=false)
protected BpmnRestApiInterceptor restApiInterceptor;
protected DataResponse<HistoricDetailResponse> getQueryResponse(HistoricDetailQueryRequest queryRequest, Map<String, String> allRequestParams) {
HistoricDetailQuery query = historyService.createHistoricDetailQuery();
// Populate query based on request
if (queryRequest.getProcessInstanceId() != null) {
query.processInstanceId(queryRequest.getProcessInstanceId());
}
if (queryRequest.getExecutionId() != null) { | query.executionId(queryRequest.getExecutionId());
}
if (queryRequest.getActivityInstanceId() != null) {
query.activityInstanceId(queryRequest.getActivityInstanceId());
}
if (queryRequest.getTaskId() != null) {
query.taskId(queryRequest.getTaskId());
}
if (queryRequest.getSelectOnlyFormProperties() != null) {
if (queryRequest.getSelectOnlyFormProperties()) {
query.formProperties();
}
}
if (queryRequest.getSelectOnlyVariableUpdates() != null) {
if (queryRequest.getSelectOnlyVariableUpdates()) {
query.variableUpdates();
}
}
if (restApiInterceptor != null) {
restApiInterceptor.accessHistoryDetailInfoWithQuery(query, queryRequest);
}
return paginateList(allRequestParams, queryRequest, query, "processInstanceId", allowedSortProperties,
restResponseFactory::createHistoricDetailResponse);
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailBaseResource.java | 2 |
请完成以下Java代码 | public Advice getAdvice() {
synchronized (this.adviceMonitor) {
if (this.interceptor == null) {
Assert.notNull(this.adviceBeanName, "'adviceBeanName' must be set for use with bean factory lookup.");
Assert.state(this.beanFactory != null, "BeanFactory must be set to resolve 'adviceBeanName'");
this.interceptor = this.beanFactory.getBean(this.adviceBeanName, MethodInterceptor.class);
}
return this.interceptor;
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject(); | this.adviceMonitor = new Object();
this.attributeSource = this.beanFactory.getBean(this.metadataSourceBeanName,
MethodSecurityMetadataSource.class);
}
class MethodSecurityMetadataSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
@Override
public boolean matches(Method m, Class<?> targetClass) {
MethodSecurityMetadataSource source = MethodSecurityMetadataSourceAdvisor.this.attributeSource;
return !CollectionUtils.isEmpty(source.getAttributes(m, targetClass));
}
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\aopalliance\MethodSecurityMetadataSourceAdvisor.java | 1 |
请完成以下Java代码 | public class MultipleSQLExecution {
private Connection connection;
public MultipleSQLExecution(Connection connection) {
this.connection = connection;
}
public boolean executeMultipleStatements() throws SQLException {
String sql = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');" +
"INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');";
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
return true;
}
}
public int[] executeBatchProcessing() throws SQLException {
try (Statement statement = connection.createStatement()) {
connection.setAutoCommit(false);
statement.addBatch("INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com')");
statement.addBatch("INSERT INTO users (name, email) VALUES ('Diana', 'diana@example.com')");
int[] updateCounts = statement.executeBatch();
connection.commit();
return updateCounts;
}
}
public boolean callStoredProcedure() throws SQLException {
try (CallableStatement callableStatement = connection.prepareCall("{CALL InsertMultipleUsers()}")) {
callableStatement.execute();
return true;
} | }
public List<User> executeMultipleSelectStatements() throws SQLException {
String sql = "SELECT * FROM users WHERE email = 'alice@example.com';" +
"SELECT * FROM users WHERE email = 'bob@example.com';";
List<User> users = new ArrayList<>();
try (Statement statement = connection.createStatement()) {
statement.execute(sql); // Here we execute the multiple queries
do {
try (ResultSet resultSet = statement.getResultSet()) {
while (resultSet != null && resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
users.add(new User(id, name, email));
}
}
} while (statement.getMoreResults());
}
return users;
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\sql\MultipleSQLExecution.java | 1 |
请完成以下Java代码 | public void setDeviceData(DeviceData data) {
this.deviceData = data;
try {
this.deviceDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize device data: ", e);
}
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getFirmwareId() {
return firmwareId;
}
public void setFirmwareId(OtaPackageId firmwareId) {
this.firmwareId = firmwareId;
}
@Schema(description = "JSON object with Ota Package Id.") | public OtaPackageId getSoftwareId() {
return softwareId;
}
public void setSoftwareId(OtaPackageId softwareId) {
this.softwareId = softwareId;
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Device.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_M_PricingSystem[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Beschreibung.
@param Description
Optionale kurze Beschreibung fuer den Eintrag
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optionale kurze Beschreibung fuer den Eintrag
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Preise.
@param M_PricingSystem_ID Preise */
public void setM_PricingSystem_ID (int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PricingSystem_ID, Integer.valueOf(M_PricingSystem_ID));
}
/** Get Preise.
@return Preise */
public int getM_PricingSystem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PricingSystem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag | */
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PricingSystem.java | 1 |
请完成以下Java代码 | public final int getResultSetHoldability() throws SQLException
{
return getStatementImpl().getResultSetHoldability();
}
@Override
public final boolean isClosed() throws SQLException
{
return closed;
}
@Override
public final void setPoolable(final boolean poolable) throws SQLException
{
getStatementImpl().setPoolable(poolable);
}
@Override
public final boolean isPoolable() throws SQLException
{
return getStatementImpl().isPoolable();
}
@Override
public final void closeOnCompletion() throws SQLException
{
getStatementImpl().closeOnCompletion();
}
@Override
public final boolean isCloseOnCompletion() throws SQLException
{
return getStatementImpl().isCloseOnCompletion();
}
@Override
public final String getSql()
{
return this.vo.getSql();
}
protected final String convertSqlAndSet(final String sql)
{
final String sqlConverted = DB.getDatabase().convertStatement(sql);
vo.setSql(sqlConverted); | MigrationScriptFileLoggerHolder.logMigrationScript(sql);
return sqlConverted;
}
@Override
public final void commit() throws SQLException
{
if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit())
{
this.ownedConnection.commit();
}
}
@Nullable
private static Trx getTrx(@NonNull final CStatementVO vo)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final String trxName = vo.getTrxName();
if (trxManager.isNull(trxName))
{
return (Trx)ITrx.TRX_None;
}
else
{
final ITrx trx = trxManager.get(trxName, false); // createNew=false
// NOTE: we assume trx if of type Trx because we need to invoke getConnection()
return (Trx)trx;
}
}
@Override
public String toString()
{
return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java | 1 |
请完成以下Java代码 | private ExceptionMatcher buildExceptionMatcher() {
if (this.exceptionEntriesConfigurer == null) {
return ExceptionMatcher.forAllowList().add(Throwable.class).build();
}
ExceptionMatcher.Builder builder = (this.exceptionEntriesConfigurer.matchIfFound)
? ExceptionMatcher.forAllowList() : ExceptionMatcher.forDenyList();
builder.addAll(this.exceptionEntriesConfigurer.entries);
if (this.traversingCauses != null) {
builder.traverseCauses(this.traversingCauses);
}
return builder.build();
}
/**
* Create a new instance of the builder.
* @return the new instance.
*/
public static RetryTopicConfigurationBuilder newInstance() {
return new RetryTopicConfigurationBuilder(); | }
private static final class ExceptionEntriesConfigurer {
private final boolean matchIfFound;
private final Set<Class<? extends Throwable>> entries = new LinkedHashSet<>();
private ExceptionEntriesConfigurer(boolean matchIfFound) {
this.matchIfFound = matchIfFound;
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfigurationBuilder.java | 1 |
请完成以下Java代码 | public void setPromotionCode (String PromotionCode)
{
set_Value (COLUMNNAME_PromotionCode, PromotionCode);
}
/** Get Promotion Code.
@return User entered promotion code at sales time
*/
public String getPromotionCode ()
{
return (String)get_Value(COLUMNNAME_PromotionCode);
}
/** Set Usage Counter.
@param PromotionCounter
Usage counter
*/
public void setPromotionCounter (int PromotionCounter)
{
set_ValueNoCheck (COLUMNNAME_PromotionCounter, Integer.valueOf(PromotionCounter));
}
/** Get Usage Counter.
@return Usage counter
*/
public int getPromotionCounter ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionCounter);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usage Limit.
@param PromotionUsageLimit
Maximum usage limit
*/
public void setPromotionUsageLimit (int PromotionUsageLimit)
{
set_Value (COLUMNNAME_PromotionUsageLimit, Integer.valueOf(PromotionUsageLimit));
}
/** Get Usage Limit.
@return Maximum usage limit
*/
public int getPromotionUsageLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PromotionUsageLimit);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionPreCondition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class ReactiveSessionConfiguration {
@Bean
SessionTimeout embeddedWebServerSessionTimeout(SessionProperties sessionProperties,
ServerProperties serverProperties) {
return () -> determineTimeout(sessionProperties, serverProperties.getReactive().getSession()::getTimeout);
}
}
/**
* Condition to trigger the creation of a {@link DefaultCookieSerializer}. This kicks
* in if either no {@link HttpSessionIdResolver} and {@link CookieSerializer} beans
* are registered, or if {@link CookieHttpSessionIdResolver} is registered but
* {@link CookieSerializer} is not.
*/
static class DefaultCookieSerializerCondition extends AnyNestedCondition { | DefaultCookieSerializerCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingBean({ HttpSessionIdResolver.class, CookieSerializer.class })
static class NoComponentsAvailable {
}
@ConditionalOnBean(CookieHttpSessionIdResolver.class)
@ConditionalOnMissingBean(CookieSerializer.class)
static class CookieHttpSessionIdResolverAvailable {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Account getTaxAccount(
@NonNull final TaxId taxId,
@NonNull final AcctSchemaId acctSchemaId,
@NonNull final PostingSign postingSign)
{
final TaxAcctType taxAcctType = postingSign.isDebit()
? TaxAcctType.TaxCredit
: TaxAcctType.TaxDue;
return taxAccountsRepository.getAccounts(taxId, acctSchemaId)
.getAccount(taxAcctType)
.orElseThrow(() -> new AdempiereException("No account found for " + taxId + ", " + acctSchemaId + ", " + taxAcctType));
}
public Money calculateTaxAmt( | @NonNull final Money lineAmt,
@NonNull final TaxId taxId,
final boolean isTaxIncluded)
{
//
final CurrencyId currencyId = lineAmt.getCurrencyId();
final CurrencyPrecision precision = moneyService.getStdPrecision(currencyId);
final Tax tax = taxBL.getTaxById(taxId);
final CalculateTaxResult taxResult = tax.calculateTax(lineAmt.toBigDecimal(), isTaxIncluded, precision.toInt());
return tax.isReverseCharge()
? Money.of(taxResult.getReverseChargeAmt(), currencyId)
: Money.of(taxResult.getTaxAmount(), currencyId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalTaxProvider.java | 2 |
请完成以下Java代码 | public final void setValueAt(final Object value, final int rowModelIndex, final int columnModelIndex)
{
final TableColumnInfo columnInfo = getTableColumnInfo(columnModelIndex);
final ModelType row = getRow(rowModelIndex);
try
{
columnInfo.getWriteMethod().invoke(row, value);
}
catch (final IllegalAccessException e)
{
throw new AdempiereException("Cannot set value for " + columnInfo, e);
}
catch (final InvocationTargetException e)
{
final Throwable cause = e.getTargetException() == null ? e : e.getTargetException();
throw new AdempiereException("Cannot set value for " + columnInfo, cause);
}
fireTableCellUpdated(rowModelIndex, columnModelIndex);
}
/**
* Notifies all listeners that all values of given column where changed.
*
* @param columnName
* @see TableModelEvent
*/
protected final void fireTableColumnChanged(final String columnName)
{
final int rowCount = getRowCount();
if (rowCount <= 0)
{
// no rows => no point to fire the event
return;
}
final int columnIndex = getColumnIndexByColumnName(columnName);
final int firstRow = 0;
final int lastRow = rowCount - 1;
final TableModelEvent event = new TableModelEvent(this, firstRow, lastRow, columnIndex, TableModelEvent.UPDATE);
fireTableChanged(event);
}
public final void fireTableRowsUpdated(final Collection<ModelType> rows)
{
if (rows == null || rows.isEmpty())
{
return;
}
// NOTE: because we are working with small amounts of rows,
// it's pointless to figure out which are the row indexes of those rows
// so it's better to fire a full data change event.
// In future we can optimize this.
fireTableDataChanged();
}
/**
* @return foreground color to be used when rendering the given cell or <code>null</code> if no suggestion
*/
protected Color getCellForegroundColor(final int modelRowIndex, final int modelColumnIndex) | {
return null;
}
public List<ModelType> getSelectedRows(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel)
{
final int rowMinView = selectionModel.getMinSelectionIndex();
final int rowMaxView = selectionModel.getMaxSelectionIndex();
if (rowMinView < 0 || rowMaxView < 0)
{
return ImmutableList.of();
}
final ImmutableList.Builder<ModelType> selection = ImmutableList.builder();
for (int rowView = rowMinView; rowView <= rowMaxView; rowView++)
{
if (selectionModel.isSelectedIndex(rowView))
{
final int rowModel = convertRowIndexToModel.apply(rowView);
selection.add(getRow(rowModel));
}
}
return selection.build();
}
public ModelType getSelectedRow(final ListSelectionModel selectionModel, final Function<Integer, Integer> convertRowIndexToModel)
{
final int rowIndexView = selectionModel.getMinSelectionIndex();
if (rowIndexView < 0)
{
return null;
}
final int rowIndexModel = convertRowIndexToModel.apply(rowIndexView);
return getRow(rowIndexModel);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\AnnotatedTableModel.java | 1 |
请完成以下Java代码 | public Collection<OnPart> getOnParts() {
return onPartCollection.get(this);
}
public IfPart getIfPart() {
return ifPartChild.getChild(this);
}
public void setIfPart(IfPart ifPart) {
ifPartChild.setChild(this, ifPart);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Sentry.class, CMMN_ELEMENT_SENTRY)
.extendsType(CmmnElement.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<Sentry>() {
public Sentry newInstance(ModelTypeInstanceContext instanceContext) {
return new SentryImpl(instanceContext); | }
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
onPartCollection = sequenceBuilder.elementCollection(OnPart.class)
.build();
ifPartChild = sequenceBuilder.element(IfPart.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\SentryImpl.java | 1 |
请完成以下Java代码 | public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override
public Long getWorkTimeInMillis() {
if (endTime == null || claimTime == null) {
return null;
}
return endTime.getTime() - claimTime.getTime();
}
@Override
public Map<String, Object> getTaskLocalVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() != null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
} | }
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricTaskInstanceEntity[");
sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntity.java | 1 |
请完成以下Java代码 | public List<JsonHU> listByQRCode(@RequestBody @NonNull final JsonGetByQRCodeRequest request)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return handlingUnitsService.getHUsByQrCode(request, adLanguage);
}
private static @NonNull ResponseEntity<JsonGetSingleHUResponse> toBadRequestResponseEntity(final Exception e)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return ResponseEntity.badRequest().body(JsonGetSingleHUResponse.ofError(JsonErrors.ofThrowable(e, adLanguage)));
}
private JsonHUAttribute toJsonHUAttribute(final HUQRCodeAttribute huQRCodeAttribute)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
final AttributeCode attributeCode = huQRCodeAttribute.getCode();
return JsonHUAttribute.builder()
.code(attributeCode.getCode())
.caption(attributeDAO.getAttributeByCode(attributeCode).getDisplayName().translate(adLanguage))
.value(huQRCodeAttribute.getValueRendered())
.build();
} | private static JsonHUType toJsonHUType(@NonNull final HUQRCodeUnitType huUnitType)
{
switch (huUnitType)
{
case LU:
return JsonHUType.LU;
case TU:
return JsonHUType.TU;
case VHU:
return JsonHUType.CU;
default:
throw new AdempiereException("Unknown HU Unit Type: " + huUnitType);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HandlingUnitsRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static void updateRecord(
@NonNull final I_M_Picking_Job_Step record,
@Nullable final PickingJobStepPickedTo pickedTo)
{
final BigDecimal qtyRejectedBD;
final String rejectReason;
if (pickedTo != null)
{
qtyRejectedBD = pickedTo.getQtyRejected() != null ? pickedTo.getQtyRejected().toBigDecimal() : BigDecimal.ZERO;
rejectReason = pickedTo.getQtyRejected() != null ? pickedTo.getQtyRejected().getReasonCode().getCode() : null;
}
else
{
qtyRejectedBD = BigDecimal.ZERO;
rejectReason = null;
}
record.setQtyRejectedToPick(qtyRejectedBD);
record.setRejectReason(rejectReason);
}
private static void updateRecord(final I_M_Picking_Job_Step_HUAlternative existingRecord, final PickingJobStepPickFrom pickFrom)
{
existingRecord.setPickFrom_HU_ID(pickFrom.getPickFromHUId().getRepoId());
updateRecord(existingRecord, pickFrom.getPickedTo()); | }
private static void updateRecord(final I_M_Picking_Job_Step_HUAlternative existingRecord, final PickingJobStepPickedTo pickedTo)
{
final UomId uomId;
final BigDecimal qtyRejectedBD;
final String rejectReason;
if (pickedTo != null && pickedTo.getQtyRejected() != null)
{
final QtyRejectedWithReason qtyRejected = pickedTo.getQtyRejected();
uomId = qtyRejected.toQuantity().getUomId();
qtyRejectedBD = qtyRejected.toBigDecimal();
rejectReason = qtyRejected.getReasonCode().getCode();
}
else
{
uomId = null;
qtyRejectedBD = BigDecimal.ZERO;
rejectReason = null;
}
existingRecord.setC_UOM_ID(UomId.toRepoId(uomId));
existingRecord.setQtyRejectedToPick(qtyRejectedBD);
existingRecord.setRejectReason(rejectReason);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\PickingJobSaver.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isExplicitNulls() {
return this.explicitNulls;
}
public void setExplicitNulls(boolean explicitNulls) {
this.explicitNulls = explicitNulls;
}
public boolean isCoerceInputValues() {
return this.coerceInputValues;
}
public void setCoerceInputValues(boolean coerceInputValues) {
this.coerceInputValues = coerceInputValues;
}
public boolean isAllowStructuredMapKeys() {
return this.allowStructuredMapKeys;
}
public void setAllowStructuredMapKeys(boolean allowStructuredMapKeys) {
this.allowStructuredMapKeys = allowStructuredMapKeys;
}
public boolean isAllowSpecialFloatingPointValues() {
return this.allowSpecialFloatingPointValues;
}
public void setAllowSpecialFloatingPointValues(boolean allowSpecialFloatingPointValues) {
this.allowSpecialFloatingPointValues = allowSpecialFloatingPointValues;
}
public String getClassDiscriminator() {
return this.classDiscriminator;
}
public void setClassDiscriminator(String classDiscriminator) {
this.classDiscriminator = classDiscriminator;
}
public ClassDiscriminatorMode getClassDiscriminatorMode() {
return this.classDiscriminatorMode;
}
public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) {
this.classDiscriminatorMode = classDiscriminatorMode;
}
public boolean isDecodeEnumsCaseInsensitive() {
return this.decodeEnumsCaseInsensitive;
}
public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) {
this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive;
}
public boolean isUseAlternativeNames() {
return this.useAlternativeNames;
}
public void setUseAlternativeNames(boolean useAlternativeNames) {
this.useAlternativeNames = useAlternativeNames;
}
public boolean isAllowTrailingComma() {
return this.allowTrailingComma;
}
public void setAllowTrailingComma(boolean allowTrailingComma) { | this.allowTrailingComma = allowTrailingComma;
}
public boolean isAllowComments() {
return this.allowComments;
}
public void setAllowComments(boolean allowComments) {
this.allowComments = allowComments;
}
/**
* Enum representing strategies for JSON property naming. The values correspond to
* {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot
* be directly referenced.
*/
public enum JsonNamingStrategy {
/**
* Snake case strategy.
*/
SNAKE_CASE,
/**
* Kebab case strategy.
*/
KEBAB_CASE
}
} | repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java | 2 |
请完成以下Java代码 | public PageData<EntityView> findByTenantId(UUID tenantId, PageLink pageLink) {
return findEntityViewsByTenantId(tenantId, pageLink);
}
@Override
public EntityViewId getExternalIdByInternal(EntityViewId internalId) {
return Optional.ofNullable(entityViewRepository.getExternalIdById(internalId.getId()))
.map(EntityViewId::new).orElse(null);
}
@Override
public EntityView findByTenantIdAndName(UUID tenantId, String name) {
return findEntityViewByTenantIdAndName(tenantId, name).orElse(null);
}
@Override
public PageData<EntityView> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
} | @Override
public List<EntityViewFields> findNextBatch(UUID id, int batchSize) {
return entityViewRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) {
return entityViewRepository.findEntityInfosByNamePrefix(tenantId.getId(), name);
}
@Override
public EntityType getEntityType() {
return EntityType.ENTITY_VIEW;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\entityview\JpaEntityViewDao.java | 1 |
请完成以下Java代码 | public Dimension getFromRecord(@NonNull final I_M_InOutLine record)
{
return Dimension.builder()
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.campaignId(record.getC_Campaign_ID())
.activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID()))
.userElementString1(record.getUserElementString1())
.userElementString2(record.getUserElementString2())
.userElementString3(record.getUserElementString3())
.userElementString4(record.getUserElementString4())
.userElementString5(record.getUserElementString5())
.userElementString6(record.getUserElementString6())
.userElementString7(record.getUserElementString7())
.user1_ID(record.getUser1_ID())
.user2_ID(record.getUser2_ID())
.build();
}
@Override
public void updateRecord(final I_M_InOutLine record, final Dimension from) | {
record.setC_Project_ID(ProjectId.toRepoId(from.getProjectId()));
record.setC_Campaign_ID(from.getCampaignId());
record.setC_Activity_ID(ActivityId.toRepoId(from.getActivityId()));
record.setC_OrderSO_ID(OrderId.toRepoId(from.getSalesOrderId()));
record.setUserElementString1(from.getUserElementString1());
record.setUserElementString2(from.getUserElementString2());
record.setUserElementString3(from.getUserElementString3());
record.setUserElementString4(from.getUserElementString4());
record.setUserElementString5(from.getUserElementString5());
record.setUserElementString6(from.getUserElementString6());
record.setUserElementString7(from.getUserElementString7());
record.setUser1_ID(from.getUser1_ID());
record.setUser2_ID(from.getUser2_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\dimension\InOutLineDimensionFactory.java | 1 |
请完成以下Java代码 | public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:baeldung.Foo)
}
static {
defaultInstance = new Foo(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:baeldung.Foo)
}
private static final com.google.protobuf.Descriptors.Descriptor internal_static_baeldung_Foo_descriptor;
private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_baeldung_Foo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
} | private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = { "\n\017FooProtos.proto\022\010baeldung\"\037\n\003Foo\022\n\n\002id" + "\030\001 \002(\003\022\014\n\004name\030\002 \002(\tB!\n\024com.baeldung.web" + ".dtoB\tFooProtos" };
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner);
internal_static_baeldung_Foo_descriptor = getDescriptor().getMessageTypes().get(0);
internal_static_baeldung_Foo_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable(internal_static_baeldung_Foo_descriptor, new java.lang.String[] { "Id", "Name", });
}
// @@protoc_insertion_point(outer_class_scope)
} | repos\tutorials-master\spring-web-modules\spring-rest-simple\src\main\java\com\baeldung\web\dto\FooProtos.java | 1 |
请完成以下Java代码 | public void destroy() throws Exception {
// stop-schedule
JobScheduleHelper.getInstance().toStop();
// admin log report stop
JobLogReportHelper.getInstance().toStop();
// admin lose-monitor stop
JobCompleteHelper.getInstance().toStop();
// admin fail-monitor stop
JobFailMonitorHelper.getInstance().toStop();
// admin registry stop
JobRegistryHelper.getInstance().toStop();
// admin trigger pool stop
JobTriggerPoolHelper.toStop();
}
// ---------------------- I18n ----------------------
private void initI18n(){
for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) {
item.setTitle(I18nUtil.getString("jobconf_block_".concat(item.name())));
}
}
// ---------------------- executor-client ---------------------- | private static ConcurrentMap<String, ExecutorBiz> executorBizRepository = new ConcurrentHashMap<String, ExecutorBiz>();
public static ExecutorBiz getExecutorBiz(String address) throws Exception {
// valid
if (address==null || address.trim().length()==0) {
return null;
}
// load-cache
address = address.trim();
ExecutorBiz executorBiz = executorBizRepository.get(address);
if (executorBiz != null) {
return executorBiz;
}
// set-cache
executorBiz = new ExecutorBizClient(address, XxlJobAdminConfig.getAdminConfig().getAccessToken());
executorBizRepository.put(address, executorBiz);
return executorBiz;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\scheduler\XxlJobScheduler.java | 1 |
请完成以下Java代码 | public BigDecimal getPrice() {
return price;
}
public Store getStore() {
return store;
}
public void setColor(String color) {
this.color = color;
}
public void setGrade(String grade) {
this.grade = grade;
}
public void setId(Long id) {
this.id = id; | }
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public void setStore(Store store) {
this.store = store;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-2\src\main\java\com\baeldung\boot\domain\Item.java | 1 |
请完成以下Java代码 | public abstract class AbstractTemplateFilter implements Filter {
private FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void destroy() {
filterConfig = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
applyFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
}
/**
* Apply the filter to the given request/response.
*
* This method must be provided by subclasses to perform actual work.
*
* @param request
* @param response
* @param chain
*
* @throws IOException
* @throws ServletException
*/
protected abstract void applyFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;
/**
* Returns true if the given web resource exists.
*
* @param name
* @return
*/
protected boolean hasWebResource(String name) {
try {
URL resource = filterConfig.getServletContext().getResource(name);
return resource != null; | } catch (MalformedURLException e) {
return false;
}
}
/**
* Returns the string contents of a web resource with the given name.
*
* The resource must be static and text based.
*
* @param name the name of the resource
*
* @return the resource contents
*
* @throws IOException
*/
protected String getWebResourceContents(String name) throws IOException {
InputStream is = null;
try {
is = filterConfig.getServletContext().getResourceAsStream(name);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringWriter writer = new StringWriter();
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.append("\n");
}
return writer.toString();
} finally {
if (is != null) {
try { is.close(); } catch (IOException e) { }
}
}
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\filter\AbstractTemplateFilter.java | 1 |
请完成以下Java代码 | public class SuffixingRetryTopicNamesProviderFactory implements RetryTopicNamesProviderFactory {
@Override
public RetryTopicNamesProvider createRetryTopicNamesProvider(DestinationTopic.Properties properties) {
return new SuffixingRetryTopicNamesProvider(properties);
}
public static class SuffixingRetryTopicNamesProvider implements RetryTopicNamesProvider {
private final Suffixer suffixer;
public SuffixingRetryTopicNamesProvider(DestinationTopic.Properties properties) {
this.suffixer = new Suffixer(properties.suffix());
}
@Override
public @Nullable String getEndpointId(KafkaListenerEndpoint endpoint) {
return this.suffixer.maybeAddTo(endpoint.getId());
}
@Override
public @Nullable String getGroupId(KafkaListenerEndpoint endpoint) {
return this.suffixer.maybeAddTo(endpoint.getGroupId());
}
@Override | public @Nullable String getClientIdPrefix(KafkaListenerEndpoint endpoint) {
return this.suffixer.maybeAddTo(endpoint.getClientIdPrefix());
}
@Override
public @Nullable String getGroup(KafkaListenerEndpoint endpoint) {
return this.suffixer.maybeAddTo(endpoint.getGroup());
}
@Override
public @Nullable String getTopicName(String topic) {
return this.suffixer.maybeAddTo(topic);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\SuffixingRetryTopicNamesProviderFactory.java | 1 |
请完成以下Java代码 | public RefundMode extractRefundMode()
{
return RefundConfigs.extractRefundMode(refundConfigs);
}
public Optional<RefundConfig> getRefundConfigToUseProfitCalculation()
{
return getRefundConfigs()
.stream()
.filter(RefundConfig::isUseInProfitCalculation)
.findFirst();
}
/**
* With this instance's {@code StartDate} as basis, the method returns the first date that is
* after or at the given {@code currentDate} and that is aligned with this instance's invoice schedule.
*/
public NextInvoiceDate computeNextInvoiceDate(@NonNull final LocalDate currentDate)
{
final InvoiceSchedule invoiceSchedule = extractSingleElement(refundConfigs, RefundConfig::getInvoiceSchedule);
LocalDate date = invoiceSchedule.calculateNextDateToInvoice(startDate);
while (date.isBefore(currentDate))
{
final LocalDate nextDate = invoiceSchedule.calculateNextDateToInvoice(date); | Check.assume(nextDate.isAfter(date), // make sure not to get stuck in an endless loop
"For the given date={}, invoiceSchedule.calculateNextDateToInvoice needs to return a nextDate that is later; nextDate={}",
date, nextDate);
date = nextDate;
}
return new NextInvoiceDate(invoiceSchedule, date);
}
@Value
public static class NextInvoiceDate
{
InvoiceSchedule invoiceSchedule;
LocalDate dateToInvoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\RefundContract.java | 1 |
请完成以下Java代码 | public static class Builder {
private final boolean matchIfFound;
private final Set<Class<? extends Throwable>> exceptionClasses = new LinkedHashSet<>();
private boolean traverseCauses = false;
protected Builder(boolean matchIfFound) {
this.matchIfFound = matchIfFound;
}
/**
* Add an exception type.
* @param exceptionType the exception type to add
* @return {@code this}
*/
public Builder add(Class<? extends Throwable> exceptionType) {
Assert.notNull(exceptionType, "Exception class can not be null");
this.exceptionClasses.add(exceptionType);
return this;
}
/**
* Add all exception types from the given collection.
* @param exceptionTypes the exception types to add
* @return {@code this}
*/
public Builder addAll(Collection<Class<? extends Throwable>> exceptionTypes) {
this.exceptionClasses.addAll(exceptionTypes);
return this;
} | /**
* Specify if the matcher should traverse nested causes to check for the presence
* of a matching exception.
* @param traverseCauses whether to traverse causes
* @return {@code this}
*/
public Builder traverseCauses(boolean traverseCauses) {
this.traverseCauses = traverseCauses;
return this;
}
/**
* Build an {@link ExceptionMatcher}.
* @return a new exception matcher
*/
public ExceptionMatcher build() {
return new ExceptionMatcher(buildEntries(new ArrayList<>(this.exceptionClasses), this.matchIfFound),
!this.matchIfFound, this.traverseCauses);
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\ExceptionMatcher.java | 1 |
请完成以下Java代码 | private boolean matchesSavedRequest(HttpServletRequest request, @Nullable SavedRequest savedRequest) {
if (savedRequest == null) {
return false;
}
String currentUrl = UrlUtils.buildFullRequestUrl(request);
return savedRequest.getRedirectUrl().equals(currentUrl);
}
/**
* Allows selective use of saved requests for a subset of requests. By default any
* request will be cached by the {@code saveRequest} method.
* <p>
* If set, only matching requests will be cached.
* @param requestMatcher a request matching strategy which defines which requests
* should be cached.
*/
public void setRequestMatcher(RequestMatcher requestMatcher) { | Assert.notNull(requestMatcher, "requestMatcher should not be null");
this.requestMatcher = requestMatcher;
}
/**
* Sets the {@link Consumer}, allowing customization of cookie.
* @param cookieCustomizer customize for cookie
* @since 6.4
*/
public void setCookieCustomizer(Consumer<Cookie> cookieCustomizer) {
Assert.notNull(cookieCustomizer, "cookieCustomizer cannot be null");
this.cookieCustomizer = cookieCustomizer;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\CookieRequestCache.java | 1 |
请完成以下Java代码 | public class InStock {
private String wareHouse;
private Integer quantity;
public InStock(String wareHouse, int quantity) {
this.wareHouse = wareHouse;
this.quantity = quantity;
}
public String getWareHouse() {
return wareHouse;
}
public void setWareHouse(String wareHouse) {
this.wareHouse = wareHouse;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override | public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
InStock inStock = (InStock) o;
return Objects.equals(wareHouse, inStock.wareHouse) && Objects.equals(quantity, inStock.quantity);
}
@Override
public int hashCode() {
return Objects.hash(wareHouse, quantity);
}
} | repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\projection\model\InStock.java | 1 |
请完成以下Spring Boot application配置 | #DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:mysql://localhost:3306/myhome?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=root
spring.datasource.password=posilka2020
#Hibernate
#The SQL dialect make Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQL5InnoDBDia | lect
#Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE | repos\Spring-Boot-Advanced-Projects-main\Registration-FullStack-Springboot\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public boolean isUpdateRequired() {
if (StringUtils.isEmpty(targetName) || StringUtils.isEmpty(targetVersion) || !isSupported()) {
return false;
} else {
String targetPackageId = getPackageId(targetName, targetVersion);
String currentPackageId = getPackageId(currentName, currentVersion);
if (StringUtils.isNotEmpty(failedPackageId) && failedPackageId.equals(targetPackageId)) {
return false;
} else {
if (targetPackageId.equals(currentPackageId)) {
return false;
} else if (StringUtils.isNotEmpty(targetTag) && targetTag.equals(currentPackageId)) {
return false;
} else if (StringUtils.isNotEmpty(currentVersion3)) {
if (StringUtils.isNotEmpty(targetTag) && (currentVersion3.contains(targetTag) || targetTag.contains(currentVersion3))) {
return false;
}
return !currentVersion3.contains(targetPackageId);
} else {
return true;
}
}
}
}
@JsonIgnore
public boolean isSupported() {
return StringUtils.isNotEmpty(currentName) || StringUtils.isNotEmpty(currentVersion) || StringUtils.isNotEmpty(currentVersion3); | }
@JsonIgnore
public boolean isAssigned() {
return StringUtils.isNotEmpty(targetName) && StringUtils.isNotEmpty(targetVersion);
}
public abstract void update(Result result);
protected static String getPackageId(String name, String version) {
return (StringUtils.isNotEmpty(name) ? name : "") + (StringUtils.isNotEmpty(version) ? version : "");
}
public abstract OtaPackageType getType();
@JsonIgnore
public String getTargetPackageId() {
return getPackageId(targetName, targetVersion);
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\ota\LwM2MClientOtaInfo.java | 1 |
请完成以下Java代码 | private IInvoiceCandidatesChangesChecker newInvoiceCandidatesChangesChecker()
{
if (isFailOnChanges())
{
return new InvoiceCandidatesChangesChecker()
.setTotalNetAmtToInvoiceChecksum(_totalNetAmtToInvoiceChecksum);
}
else
{
return IInvoiceCandidatesChangesChecker.NULL;
}
}
@Override
public IInvoiceCandidateEnqueuer setTotalNetAmtToInvoiceChecksum(final BigDecimal totalNetAmtToInvoiceChecksum)
{
this._totalNetAmtToInvoiceChecksum = totalNetAmtToInvoiceChecksum;
return this; | }
@Override
public IInvoiceCandidateEnqueuer setAsyncBatchId(final AsyncBatchId asyncBatchId)
{
_asyncBatchId = asyncBatchId;
return this;
}
@Override
public IInvoiceCandidateEnqueuer setPriority(final IWorkpackagePrioStrategy priority)
{
_priority = priority;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateEnqueuer.java | 1 |
请完成以下Java代码 | public class JSONDocumentList
{
@NonNull private final List<JSONDocument> result;
@NonNull private final Set<DocumentId> missingIds;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@NonNull private final List<JSONViewOrderBy> orderBys;
@Builder(toBuilder = true)
@Jacksonized
private JSONDocumentList(
@Nullable final List<JSONDocument> result,
@Nullable final Set<DocumentId> missingIds,
@Nullable final List<JSONViewOrderBy> orderBys)
{
this.result = result != null ? ImmutableList.copyOf(result) : ImmutableList.of();
this.missingIds = normalizeMissingIds(missingIds);
this.orderBys = orderBys != null ? ImmutableList.copyOf(orderBys) : ImmutableList.of();
}
private static ImmutableSet<DocumentId> normalizeMissingIds(final @Nullable Set<DocumentId> missingIds)
{
return missingIds != null ? ImmutableSet.copyOf(missingIds) : ImmutableSet.of();
}
public static JSONDocumentList ofDocumentsList(
@NonNull final OrderedDocumentsList documents,
@NonNull final JSONDocumentOptions options,
@Nullable final Boolean hasComments)
{
return builder()
.result(JSONDocument.ofDocumentsList(documents.toList(), options, hasComments))
.orderBys(JSONViewOrderBy.ofList(documents.getOrderBys()))
.build();
}
public List<JSONDocument> toList() {return result;}
public JSONDocumentList withMissingIdsUpdatedFromExpectedRowIds(@NonNull final DocumentIdsSelection expectedRowIds)
{
final ImmutableSet<DocumentId> missingIdsNew = normalizeMissingIds(computeMissingIdsFromExpectedRowIds(expectedRowIds));
if (Objects.equals(this.missingIds, missingIdsNew)) | {
return this;
}
return toBuilder().missingIds(missingIdsNew).build();
}
public Set<DocumentId> computeMissingIdsFromExpectedRowIds(final DocumentIdsSelection expectedRowIds)
{
if (expectedRowIds.isEmpty() || expectedRowIds.isAll())
{
return null;
}
else
{
final ImmutableSet<DocumentId> existingRowIds = getRowIds();
return Sets.difference(expectedRowIds.toSet(), existingRowIds);
}
}
private ImmutableSet<DocumentId> getRowIds()
{
return result.stream()
.map(JSONDocument::getRowId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CommentRequest {
private String id;
private String url;
private String author;
private String message;
private String type;
private boolean saveProcessInstanceId;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
} | public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isSaveProcessInstanceId() {
return saveProcessInstanceId;
}
public void setSaveProcessInstanceId(boolean saveProcessInstanceId) {
this.saveProcessInstanceId = saveProcessInstanceId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\engine\CommentRequest.java | 2 |
请完成以下Java代码 | public ProcessExecutor executeSync()
{
processInfo.setAsync(false); // #1160 advise the process info, that we want a synchronous execution
final ProcessExecutor worker = build();
worker.executeSync();
return worker;
}
private ProcessExecutor build()
{
try
{
prepareAD_PInstance(processInfo);
}
catch (final Throwable e)
{
final ProcessExecutionResult result = processInfo.getResult();
result.markAsError(e);
if (listener != null)
{
listener.onProcessInitError(processInfo);
}
else
{
throw AdempiereException.wrapIfNeeded(e);
}
}
return new ProcessExecutor(this);
}
private void prepareAD_PInstance(final ProcessInfo pi)
{
//
// Save process info to database, including parameters.
adPInstanceDAO.saveProcessInfo(pi);
}
private ProcessInfo getProcessInfo()
{
return processInfo;
}
public Builder setListener(final IProcessExecutionListener listener)
{
this.listener = listener;
return this; | }
private IProcessExecutionListener getListener()
{
return listener;
}
/**
* Advice the executor to propagate the error in case the execution failed.
*/
public Builder onErrorThrowException()
{
this.onErrorThrowException = true;
return this;
}
public Builder onErrorThrowException(final boolean onErrorThrowException)
{
this.onErrorThrowException = onErrorThrowException;
return this;
}
/**
* Advice the executor to switch current context with process info's context.
*
* @see ProcessInfo#getCtx()
* @see Env#switchContext(Properties)
*/
public Builder switchContextWhenRunning()
{
this.switchContextWhenRunning = true;
return this;
}
/**
* Sets the callback to be executed after AD_PInstance is created but before the actual process is started.
* If the callback fails, the exception is propagated, so the process will not be started.
* <p>
* A common use case of <code>beforeCallback</code> is to create to selections which are linked to this process instance.
*/
public Builder callBefore(final Consumer<ProcessInfo> beforeCallback)
{
this.beforeCallback = beforeCallback;
return this;
}
}
} // ProcessCtl | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutor.java | 1 |
请完成以下Java代码 | public void setIsDone (boolean IsDone)
{
set_Value (COLUMNNAME_IsDone, Boolean.valueOf(IsDone));
}
/** Get Erledigt.
@return Erledigt */
@Override
public boolean isDone ()
{
Object oo = get_Value(COLUMNNAME_IsDone);
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)
{
set_Value (COLUMNNAME_Phone, Phone);
}
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Grund.
@param Reason Grund */
@Override
public void setReason (java.lang.String Reason)
{
set_Value (COLUMNNAME_Reason, Reason);
}
/** Get Grund.
@return Grund */
@Override | public java.lang.String getReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reason);
}
/** Set Sachbearbeiter.
@param ResponsiblePerson Sachbearbeiter */
@Override
public void setResponsiblePerson (java.lang.String ResponsiblePerson)
{
set_Value (COLUMNNAME_ResponsiblePerson, ResponsiblePerson);
}
/** Get Sachbearbeiter.
@return Sachbearbeiter */
@Override
public java.lang.String getResponsiblePerson ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponsiblePerson);
}
/** Set Status.
@param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Rejection_Detail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void createIssueSchedules(@NonNull final PPOrderIssuePlan plan)
{
final ArrayListMultimap<PPOrderBOMLineId, PPOrderIssueSchedule> allExistingSchedules = ppOrderIssueScheduleService.getByOrderId(plan.getOrderId())
.stream()
.collect(GuavaCollectors.toArrayListMultimapByKey(PPOrderIssueSchedule::getPpOrderBOMLineId));
final ArrayList<PPOrderIssueSchedule> schedules = new ArrayList<>();
final SeqNoProvider seqNoProvider = SeqNoProvider.ofInt(10);
for (final PPOrderIssuePlanStep planStep : plan.getSteps())
{
final PPOrderBOMLineId orderBOMLineId = planStep.getOrderBOMLineId();
final ArrayList<PPOrderIssueSchedule> bomLineExistingSchedules = new ArrayList<>(allExistingSchedules.removeAll(orderBOMLineId));
bomLineExistingSchedules.sort(Comparator.comparing(PPOrderIssueSchedule::getSeqNo));
for (final PPOrderIssueSchedule existingSchedule : bomLineExistingSchedules)
{
if (existingSchedule.isIssued())
{
final PPOrderIssueSchedule existingScheduleChanged = ppOrderIssueScheduleService.changeSeqNo(existingSchedule, seqNoProvider.getAndIncrement());
schedules.add(existingScheduleChanged);
}
else
{
ppOrderIssueScheduleService.delete(existingSchedule);
}
} | final PPOrderIssueSchedule schedule = ppOrderIssueScheduleService.createSchedule(
PPOrderIssueScheduleCreateRequest.builder()
.ppOrderId(ppOrderId)
.ppOrderBOMLineId(orderBOMLineId)
.seqNo(seqNoProvider.getAndIncrement())
.productId(planStep.getProductId())
.qtyToIssue(planStep.getQtyToIssue())
.issueFromHUId(planStep.getPickFromTopLevelHUId())
.issueFromLocatorId(planStep.getPickFromLocatorId())
.isAlternativeIssue(planStep.isAlternative())
.build());
schedules.add(schedule);
}
loader.addToCache(schedules);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\commands\create_job\ManufacturingJobCreateCommand.java | 2 |
请完成以下Java代码 | public static boolean isSameYear(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return false;
}
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
}
/**
* 获取两个日期之间的所有日期列表,包含开始和结束日期
*
* @param begin
* @param end
* @return
*/
public static List<Date> getDateRangeList(Date begin, Date end) {
List<Date> dateList = new ArrayList<>();
if (begin == null || end == null) {
return dateList;
}
// 清除时间部分,只比较日期
Calendar beginCal = Calendar.getInstance();
beginCal.setTime(begin); | beginCal.set(Calendar.HOUR_OF_DAY, 0);
beginCal.set(Calendar.MINUTE, 0);
beginCal.set(Calendar.SECOND, 0);
beginCal.set(Calendar.MILLISECOND, 0);
Calendar endCal = Calendar.getInstance();
endCal.setTime(end);
endCal.set(Calendar.HOUR_OF_DAY, 0);
endCal.set(Calendar.MINUTE, 0);
endCal.set(Calendar.SECOND, 0);
endCal.set(Calendar.MILLISECOND, 0);
if (endCal.before(beginCal)) {
return dateList;
}
dateList.add(beginCal.getTime());
while (beginCal.before(endCal)) {
beginCal.add(Calendar.DAY_OF_YEAR, 1);
dateList.add(beginCal.getTime());
}
return dateList;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateUtils.java | 1 |
请完成以下Java代码 | public class Msv3SubstitutionDataPersister
{
public static Msv3SubstitutionDataPersister newInstanceWithOrgId(final OrgId orgId)
{
return new Msv3SubstitutionDataPersister(orgId);
}
@NonNull
private final OrgId orgId;
public I_MSV3_Substitution storeSubstitutionOrNull(@Nullable final OrderResponsePackageItemSubstitution itemSubstitution)
{
if (itemSubstitution == null)
{
return null;
}
final I_MSV3_Substitution substitutionRecord = newInstance(I_MSV3_Substitution.class);
substitutionRecord.setAD_Org_ID(orgId.getRepoId());
substitutionRecord.setMSV3_Grund(itemSubstitution.getDefectReason().value());
substitutionRecord.setMSV3_LieferPzn(itemSubstitution.getPzn().getValueAsString());
substitutionRecord.setMSV3_Substitutionsgrund(itemSubstitution.getSubstitutionReason().value());
save(substitutionRecord);
return substitutionRecord; | }
public I_MSV3_Substitution storeSubstitutionOrNull(@Nullable final StockAvailabilitySubstitution substitution)
{
if (substitution == null)
{
return null;
}
final I_MSV3_Substitution substitutionRecord = newInstance(I_MSV3_Substitution.class);
substitutionRecord.setMSV3_Grund(substitution.getReason().value());
substitutionRecord.setMSV3_LieferPzn(substitution.getPzn().getValueAsString());
substitutionRecord.setMSV3_Substitutionsgrund(substitution.getType().value());
save(substitutionRecord);
return substitutionRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\common\Msv3SubstitutionDataPersister.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ImageCode createImageCode() {
int width = 100; // 验证码图片宽度
int height = 36; // 验证码图片长度
int length = 4; // 验证码位数
int expireIn = 60; // 验证码有效时间 60s
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuilder sRand = new StringBuilder();
for (int i = 0; i < length; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand.append(rand);
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16); | }
g.dispose();
return new ImageCode(image, sRand.toString(), expireIn);
}
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
} | repos\SpringAll-master\36.Spring-Security-ValidateCode\src\main\java\cc\mrbird\web\controller\ValidateController.java | 2 |
请完成以下Java代码 | public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TASK_MAIL, MailTaskJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
// will be handled by ServiceTaskJsonConverter
}
protected String getStencilId(BaseElement baseElement) {
return STENCIL_TASK_MAIL;
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
// will be handled by ServiceTaskJsonConverter
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap | ) {
ServiceTask task = new ServiceTask();
task.setType(ServiceTask.MAIL_TASK);
addField(PROPERTY_MAILTASK_TO, elementNode, task);
addField(PROPERTY_MAILTASK_FROM, elementNode, task);
addField(PROPERTY_MAILTASK_SUBJECT, elementNode, task);
addField(PROPERTY_MAILTASK_CC, elementNode, task);
addField(PROPERTY_MAILTASK_BCC, elementNode, task);
addField(PROPERTY_MAILTASK_TEXT, elementNode, task);
addField(PROPERTY_MAILTASK_HTML, elementNode, task);
addField(PROPERTY_MAILTASK_CHARSET, elementNode, task);
return task;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\MailTaskJsonConverter.java | 1 |
请完成以下Java代码 | public class FactAcctLogDBTableWatcher implements Runnable
{
private static final Logger logger = LogManager.getLogger(FactAcctLogDBTableWatcher.class);
private final ISysConfigBL sysConfigBL;
private final FactAcctLogService factAcctLogService;
private static final String SYSCONFIG_PollIntervalInSeconds = "de.metas.acct.aggregation.FactAcctLogDBTableWatcher.pollIntervalInSeconds";
private static final Duration DEFAULT_PollInterval = Duration.ofSeconds(10);
@VisibleForTesting
static final String SYSCONFIG_RetrieveBatchSize = "de.metas.acct.aggregation.FactAcctLogDBTableWatcher.retrieveBatchSize";
private static final QueryLimit DEFAULT_RetrieveBatchSize = QueryLimit.ofInt(2000);
@Builder
private FactAcctLogDBTableWatcher(
@NonNull final ISysConfigBL sysConfigBL,
@NonNull final FactAcctLogService factAcctLogService)
{
this.sysConfigBL = sysConfigBL;
this.factAcctLogService = factAcctLogService;
}
@Override
public void run()
{
while (true)
{
try
{
sleep();
}
catch (final InterruptedException e)
{
logger.info("Got interrupt request. Exiting.");
return;
}
try
{
processNow();
}
catch (final Exception ex)
{
logger.warn("Failed to process. Ignored.", ex);
}
}
} | private void sleep() throws InterruptedException
{
final Duration pollInterval = getPollInterval();
logger.debug("Sleeping {}", pollInterval);
Thread.sleep(pollInterval.toMillis());
}
private Duration getPollInterval()
{
final int pollIntervalInSeconds = sysConfigBL.getIntValue(SYSCONFIG_PollIntervalInSeconds, -1);
return pollIntervalInSeconds > 0
? Duration.ofSeconds(pollIntervalInSeconds)
: DEFAULT_PollInterval;
}
private QueryLimit getRetrieveBatchSize()
{
final int retrieveBatchSize = sysConfigBL.getIntValue(SYSCONFIG_RetrieveBatchSize, -1);
return retrieveBatchSize > 0 ? QueryLimit.ofInt(retrieveBatchSize) : DEFAULT_RetrieveBatchSize;
}
@VisibleForTesting
FactAcctLogProcessResult processNow()
{
FactAcctLogProcessResult finalResult = FactAcctLogProcessResult.ZERO;
boolean mightHaveMore;
do
{
final QueryLimit retrieveBatchSize = getRetrieveBatchSize();
final FactAcctLogProcessResult result = factAcctLogService.processAll(retrieveBatchSize);
finalResult = finalResult.combineWith(result);
mightHaveMore = retrieveBatchSize.isLessThanOrEqualTo(result.getProcessedLogRecordsCount());
logger.debug("processNow: retrieveBatchSize={}, result={}, mightHaveMore={}", retrieveBatchSize, result, mightHaveMore);
}
while (mightHaveMore);
logger.debug("processNow: DONE. Processed {}", finalResult);
return finalResult;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\FactAcctLogDBTableWatcher.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.