instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean hasStartFormKey() {
return hasStartFormKey;
}
@Override
public boolean getHasStartFormKey() {
return hasStartFormKey;
}
@Override
public void setStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
@Override
public boolean isGraphicalNotationDefined() {
return isGraphicalNotationDefined;
}
@Override
public boolean hasGraphicalNotation() {
return isGraphicalNotationDefined;
}
public boolean getIsGraphicalNotationDefined() {
return isGraphicalNotationDefined;
}
public void setIsGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
@Override
public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
@Override
public int getSuspensionState() {
return suspensionState;
}
@Override
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
@Override
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
@Override
public String getDerivedFrom() {
return derivedFrom;
}
@Override
public void setDerivedFrom(String derivedFrom) {
this.derivedFrom = derivedFrom;
}
@Override
public String getDerivedFromRoot() {
return derivedFromRoot;
} | @Override
public void setDerivedFromRoot(String derivedFromRoot) {
this.derivedFromRoot = derivedFromRoot;
}
@Override
public int getDerivedVersion() {
return derivedVersion;
}
@Override
public void setDerivedVersion(int derivedVersion) {
this.derivedVersion = derivedVersion;
}
@Override
public String getEngineVersion() {
return engineVersion;
}
@Override
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
@Override
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | void add(Throwable exception, ExitCodeExceptionMapper mapper) {
Assert.notNull(exception, "'exception' must not be null");
Assert.notNull(mapper, "'mapper' must not be null");
add(new MappedExitCodeGenerator(exception, mapper));
}
void addAll(ExitCodeGenerator... generators) {
Assert.notNull(generators, "'generators' must not be null");
addAll(Arrays.asList(generators));
}
void addAll(Iterable<? extends ExitCodeGenerator> generators) {
Assert.notNull(generators, "'generators' must not be null");
for (ExitCodeGenerator generator : generators) {
add(generator);
}
}
void add(ExitCodeGenerator generator) {
Assert.notNull(generator, "'generator' must not be null");
this.generators.add(generator);
AnnotationAwareOrderComparator.sort(this.generators);
}
@Override
public Iterator<ExitCodeGenerator> iterator() {
return this.generators.iterator();
}
/**
* Get the final exit code that should be returned. The final exit code is the first
* non-zero exit code that is {@link ExitCodeGenerator#getExitCode generated}.
* @return the final exit code.
*/
int getExitCode() {
int exitCode = 0;
for (ExitCodeGenerator generator : this.generators) {
try {
int value = generator.getExitCode();
if (value != 0) {
exitCode = value;
break; | }
}
catch (Exception ex) {
exitCode = 1;
ex.printStackTrace();
}
}
return exitCode;
}
/**
* Adapts an {@link ExitCodeExceptionMapper} to an {@link ExitCodeGenerator}.
*/
private static class MappedExitCodeGenerator implements ExitCodeGenerator {
private final Throwable exception;
private final ExitCodeExceptionMapper mapper;
MappedExitCodeGenerator(Throwable exception, ExitCodeExceptionMapper mapper) {
this.exception = exception;
this.mapper = mapper;
}
@Override
public int getExitCode() {
return this.mapper.getExitCode(this.exception);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ExitCodeGenerators.java | 1 |
请完成以下Java代码 | public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
} | @Override
public void setWEBUI_Dashboard_ID (final int WEBUI_Dashboard_ID)
{
if (WEBUI_Dashboard_ID < 1)
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, null);
else
set_ValueNoCheck (COLUMNNAME_WEBUI_Dashboard_ID, WEBUI_Dashboard_ID);
}
@Override
public int getWEBUI_Dashboard_ID()
{
return get_ValueAsInt(COLUMNNAME_WEBUI_Dashboard_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java-gen\de\metas\ui\web\base\model\X_WEBUI_Dashboard.java | 1 |
请完成以下Java代码 | Optional<UserName> getUserNameToUpdate() {
return ofNullable(userNameToUpdate);
}
Optional<String> getPasswordToUpdate() {
return ofNullable(passwordToUpdate);
}
Optional<Image> getImageToUpdate() {
return ofNullable(imageToUpdate);
}
Optional<String> getBioToUpdate() {
return ofNullable(bioToUpdate);
}
private UserUpdateRequest(UserUpdateRequestBuilder builder) {
this.emailToUpdate = builder.emailToUpdate;
this.userNameToUpdate = builder.userNameToUpdate;
this.passwordToUpdate = builder.passwordToUpdate;
this.imageToUpdate = builder.imageToUpdate;
this.bioToUpdate = builder.bioToUpdate;
}
public static class UserUpdateRequestBuilder {
private Email emailToUpdate;
private UserName userNameToUpdate;
private String passwordToUpdate;
private Image imageToUpdate;
private String bioToUpdate;
public UserUpdateRequestBuilder emailToUpdate(Email emailToUpdate) {
this.emailToUpdate = emailToUpdate;
return this;
}
public UserUpdateRequestBuilder userNameToUpdate(UserName userNameToUpdate) {
this.userNameToUpdate = userNameToUpdate;
return this;
} | public UserUpdateRequestBuilder passwordToUpdate(String passwordToUpdate) {
this.passwordToUpdate = passwordToUpdate;
return this;
}
public UserUpdateRequestBuilder imageToUpdate(Image imageToUpdate) {
this.imageToUpdate = imageToUpdate;
return this;
}
public UserUpdateRequestBuilder bioToUpdate(String bioToUpdate) {
this.bioToUpdate = bioToUpdate;
return this;
}
public UserUpdateRequest build() {
return new UserUpdateRequest(this);
}
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\UserUpdateRequest.java | 1 |
请完成以下Java代码 | public Set<Integer> getProductIds()
{
loadIfNeeded();
return productIds;
}
@Override
public Set<Integer> getBpartnerIds()
{
loadIfNeeded();
return bpartnerIds;
}
@Override
public Set<Integer> getLocatorIds()
{
loadIfNeeded();
return locatorIds; | }
@Override
public Set<ShipmentScheduleAttributeSegment> getAttributes()
{
loadIfNeeded();
return attributeSegments;
}
@Override
public Set<Integer> getBillBPartnerIds()
{
return ImmutableSet.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\segments\ShipmentScheduleSegmentFromHUAttribute.java | 1 |
请完成以下Java代码 | public int getX() {
return x;
}
@Override
public void setX(int x) {
this.x = x;
}
@Override
public int getY() {
return y;
}
@Override
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
} | @Override
public boolean isAsync() {
return isAsync;
}
public void setAsync(boolean isAsync) {
this.isAsync = isAsync;
}
@Override
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java | 1 |
请完成以下Java代码 | public Set<String> getStatusCodes() {
return statusCodes;
}
public CircuitBreakerConfig setStatusCodes(String... statusCodes) {
return setStatusCodes(new LinkedHashSet<>(Arrays.asList(statusCodes)));
}
public CircuitBreakerConfig setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes;
return this;
}
public boolean isResumeWithoutError() {
return resumeWithoutError;
}
public CircuitBreakerConfig setResumeWithoutError(boolean resumeWithoutError) {
this.resumeWithoutError = resumeWithoutError;
return this;
}
}
public static class CircuitBreakerStatusCodeException extends ResponseStatusException { | public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) {
super(statusCode);
}
}
public static class FilterSupplier extends SimpleFilterSupplier {
public FilterSupplier() {
super(CircuitBreakerFilterFunctions.class);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\CircuitBreakerFilterFunctions.java | 1 |
请完成以下Java代码 | public CardTransaction2Choice getTx() {
return tx;
}
/**
* Sets the value of the tx property.
*
* @param value
* allowed object is
* {@link CardTransaction2Choice }
*
*/
public void setTx(CardTransaction2Choice value) {
this.tx = value;
}
/**
* Gets the value of the prePdAcct property.
*
* @return
* possible object is
* {@link CashAccount24 } | *
*/
public CashAccount24 getPrePdAcct() {
return prePdAcct;
}
/**
* Sets the value of the prePdAcct property.
*
* @param value
* allowed object is
* {@link CashAccount24 }
*
*/
public void setPrePdAcct(CashAccount24 value) {
this.prePdAcct = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\CardTransaction2.java | 1 |
请完成以下Java代码 | public boolean isDetached() {
return caseInstance.getSuperExecutionId() == null;
}
@Override
public void detachState() {
caseInstance.setSuperExecution(null);
}
@Override
public void attachState(MigratingScopeInstance targetActivityInstance) {
caseInstance.setSuperExecution(targetActivityInstance.resolveRepresentativeExecution());
}
@Override | public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
public void migrateState() {
// nothing to do
}
@Override
public void migrateDependentEntities() {
// nothing to do
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingCalledCaseInstance.java | 1 |
请完成以下Java代码 | public final void setBlob(final int parameterIndex, final InputStream inputStream) throws SQLException
{
traceSqlParam(parameterIndex, inputStream);
delegate.setBlob(parameterIndex, inputStream);
}
@Override
public final void setNClob(final int parameterIndex, final Reader reader) throws SQLException
{
traceSqlParam(parameterIndex, reader);
delegate.setNClob(parameterIndex, reader);
}
@Override
public final void setNString(final int parameterIndex, final String value) throws SQLException
{
traceSqlParam(parameterIndex, value);
delegate.setNString(parameterIndex, value);
}
@Override
public final ResultSet executeQuery() throws SQLException
{
return trace(() -> delegate.executeQuery());
}
@Override
public ResultSet executeQueryAndLogMigationScripts() throws SQLException
{
return trace(() -> delegate.executeQueryAndLogMigationScripts());
}
@Override
public final int executeUpdate() throws SQLException
{ | return trace(() -> delegate.executeUpdate());
}
@Override
public final void clearParameters() throws SQLException
{
delegate.clearParameters();
}
@Override
public final boolean execute() throws SQLException
{
return trace(() -> delegate.execute());
}
@Override
public final void addBatch() throws SQLException
{
trace(() -> {
delegate.addBatch();
return null;
});
}
@Override
public final ResultSetMetaData getMetaData() throws SQLException
{
return delegate.getMetaData();
}
@Override
public final ParameterMetaData getParameterMetaData() throws SQLException
{
return delegate.getParameterMetaData();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\sql\impl\TracingPreparedStatement.java | 1 |
请完成以下Java代码 | public String toString() {
StringBuilder builder2 = new StringBuilder();
builder2
.append("StartMessageDeploymentDefinitionImpl [messageSubscription=")
.append(messageSubscription)
.append(", processDefinition=")
.append(processDefinition)
.append("]");
return builder2.toString();
}
public static Builder builder() {
return new Builder();
}
/**
* Creates a builder to build {@link StartMessageDeploymentDefinitionImpl} and initialize it with the given object.
* @param startMessageEventSubscriptionImpl to initialize the builder with
* @return created builder
*/
public static Builder builderFrom(StartMessageDeploymentDefinitionImpl startMessageEventSubscriptionImpl) {
return new Builder(startMessageEventSubscriptionImpl);
}
/**
* Builder to build {@link StartMessageDeploymentDefinitionImpl}.
*/
public static final class Builder {
private StartMessageSubscription messageSubscription;
private ProcessDefinition processDefinition;
public Builder() {}
private Builder(StartMessageDeploymentDefinitionImpl startMessageEventSubscriptionImpl) {
this.messageSubscription = startMessageEventSubscriptionImpl.messageSubscription;
this.processDefinition = startMessageEventSubscriptionImpl.processDefinition;
}
/**
* Builder method for messageEventSubscription parameter.
* @param messageEventSubscription field to set
* @return builder
*/
public Builder withMessageSubscription(StartMessageSubscription messageEventSubscription) {
this.messageSubscription = messageEventSubscription; | return this;
}
/**
* Builder method for processDefinition parameter.
* @param processDefinition field to set
* @return builder
*/
public Builder withProcessDefinition(ProcessDefinition processDefinition) {
this.processDefinition = processDefinition;
return this;
}
/**
* Builder method of the builder.
* @return built class
*/
public StartMessageDeploymentDefinitionImpl build() {
return new StartMessageDeploymentDefinitionImpl(this);
}
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\StartMessageDeploymentDefinitionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void save(TenantId tenantId, RpcId rpcId, RpcStatus newStatus, JsonNode response) {
Rpc foundRpc = rpcService.findById(tenantId, rpcId);
if (foundRpc != null) {
foundRpc.setStatus(newStatus);
if (response != null) {
foundRpc.setResponse(response);
}
Rpc saved = rpcService.save(foundRpc);
pushRpcMsgToRuleEngine(tenantId, saved);
} else {
log.warn("[{}] Failed to update RPC status because RPC was already deleted", rpcId);
}
}
private void pushRpcMsgToRuleEngine(TenantId tenantId, Rpc rpc) {
TbMsg msg = TbMsg.newMsg() | .type(TbMsgType.valueOf("RPC_" + rpc.getStatus().name()))
.originator(rpc.getDeviceId())
.copyMetaData(TbMsgMetaData.EMPTY)
.data(JacksonUtil.toString(rpc))
.build();
tbClusterService.pushMsgToRuleEngine(tenantId, rpc.getDeviceId(), msg, null);
}
public Rpc findRpcById(TenantId tenantId, RpcId rpcId) {
return rpcService.findById(tenantId, rpcId);
}
public PageData<Rpc> findAllByDeviceIdAndStatus(TenantId tenantId, DeviceId deviceId, RpcStatus rpcStatus, PageLink pageLink) {
return rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\rpc\TbRpcService.java | 2 |
请完成以下Java代码 | public Optional<User> findById(String userId) {
return Optional.ofNullable(map.get(userId));
}
/**
* Finds all the users from the in-memory data store
* The default implementation is an In-Memory persistence
*/
public Optional<List<User>> findAll() {
return Optional.of(new ArrayList<>(map.values()));
}
/**
* Delete the user from the data store
* The default implementation is an In-Memory persistence
* @param userId The user that has to be deleted | */
public void delete(String userId) {
map.remove(userId);
}
/**
* Checks if the user exists
* The default implementation is an In-Memory persistence
* @param userId The user that has to be checked for
*/
public boolean isExists(String userId) {
return map.containsKey(userId);
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\httpfirewall\dao\InMemoryUserDao.java | 1 |
请完成以下Java代码 | private ImmutableSet<HuId> filterOutInvalidHUs(@NonNull final PickingSlotRow pickingSlotRowOrHU)
{
final ImmutableSet.Builder<HuId> hus = ImmutableSet.builder();
if (pickingSlotRowOrHU.isPickingSlotRow())
{
for (final PickingSlotRow pickingSlotRow : pickingSlotRowOrHU.getIncludedRows())
{
if (isValidHu(pickingSlotRow))
{
hus.add(pickingSlotRow.getHuId());
}
}
}
else
{
if (isValidHu(pickingSlotRowOrHU))
{
hus.add(pickingSlotRowOrHU.getHuId());
}
}
return hus.build();
}
private boolean isValidHu(@NonNull final PickingSlotRow pickingSlotRowOrHU)
{
if (!pickingSlotRowOrHU.isPickedHURow())
{
return false;
// return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU));
}
if (!pickingSlotRowOrHU.isTopLevelHU())
{
return false;
// return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_SELECT_PICKED_HU));
}
if (checkIsEmpty(pickingSlotRowOrHU))
{
return false;
// return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_PICK_SOMETHING));
}
//noinspection RedundantIfStatement
if (pickingSlotRowOrHU.isProcessed())
{
return false;
// return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_WEBUI_PICKING_NO_UNPROCESSED_RECORDS));
}
return true;
} | @Override
protected String doIt() throws Exception
{
final PickingSlotRow rowToProcess = getSingleSelectedRow();
final ImmutableSet<HuId> hUs = filterOutInvalidHUs(rowToProcess);
final ShipmentScheduleId shipmentScheduleId = null;
//noinspection ConstantConditions
pickingCandidateService.processForHUIds(hUs, shipmentScheduleId);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
invalidatePickingSlotsView();
invalidatePackablesView();
}
private boolean checkIsEmpty(final PickingSlotRow pickingSlotRowOrHU)
{
Check.assume(pickingSlotRowOrHU.isPickedHURow(), "Was expecting an HuId but found none!");
if (pickingSlotRowOrHU.getHuQtyCU() != null && pickingSlotRowOrHU.getHuQtyCU().signum() > 0)
{
return false;
}
final I_M_HU hu = handlingUnitsBL.getById(pickingSlotRowOrHU.getHuId());
return handlingUnitsBL.isEmptyStorage(hu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\process\WEBUI_Picking_M_Picking_Candidate_Process.java | 1 |
请完成以下Java代码 | class MutableUser implements MutableUserDetails {
private static final long serialVersionUID = 620L;
private @Nullable String password;
private final UserDetails delegate;
MutableUser(UserDetails user) {
this.delegate = user;
this.password = user.getPassword();
}
@Override
public @Nullable String getPassword() {
return this.password;
}
@Override
public void setPassword(@Nullable String password) {
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.delegate.getAuthorities();
}
@Override
public String getUsername() {
return this.delegate.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return this.delegate.isAccountNonExpired();
} | @Override
public boolean isAccountNonLocked() {
return this.delegate.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return this.delegate.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
return this.delegate.isEnabled();
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\provisioning\MutableUser.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PickFromHU
{
@NonNull HuId topLevelHUId;
@With
boolean huReservedForThisLine;
@NonNull LocatorId locatorId;
//
// Relevant HU Attributes:
@NonNull String huCode;
@Nullable LocalDate expiringDate;
@Nullable String serialNo;
@Nullable String lotNumber;
@Nullable String repackNumber;
@With
@NonNull AlternativePickFromKeys alternatives;
@Builder
private PickFromHU(
@NonNull final HuId topLevelHUId,
final boolean huReservedForThisLine,
@NonNull final LocatorId locatorId,
@Nullable final String huCode,
@Nullable final LocalDate expiringDate,
@Nullable final String serialNo,
@Nullable final String lotNumber,
@Nullable final String repackNumber, | @Nullable final AlternativePickFromKeys alternatives)
{
this.topLevelHUId = topLevelHUId;
this.huReservedForThisLine = huReservedForThisLine;
this.locatorId = locatorId;
this.huCode = huCode != null ? huCode : topLevelHUId.toHUValue();
this.expiringDate = expiringDate;
this.serialNo = serialNo;
this.lotNumber = lotNumber;
this.repackNumber = repackNumber;
this.alternatives = alternatives != null ? alternatives : AlternativePickFromKeys.EMPTY;
}
public PickFromHU withHuReservedForThisLine()
{
return withHuReservedForThisLine(true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\pickFromHUs\PickFromHU.java | 2 |
请完成以下Java代码 | 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 Record Sort No.
@param SortNo
Determines in what order the records are displayed | */
public void setSortNo (int SortNo)
{
set_Value (COLUMNNAME_SortNo, Integer.valueOf(SortNo));
}
/** Get Record Sort No.
@return Determines in what order the records are displayed
*/
public int getSortNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SortNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Field.java | 1 |
请完成以下Java代码 | protected boolean isHistoryEventProduced() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
return historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_CREATE, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_DELETE, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_RESOLVE, null);
}
public DbOperation deleteHistoricIncidentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize); | return getDbEntityManager()
.deletePreserveOrder(HistoricIncidentEntity.class, "deleteHistoricIncidentsByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
public void addRemovalTimeToHistoricIncidentsByBatchId(String batchId, Date removalTime) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("batchId", batchId);
parameters.put("removalTime", removalTime);
getDbEntityManager()
.updatePreserveOrder(HistoricIncidentEntity.class, "updateHistoricIncidentsByBatchId", parameters);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricIncidentManager.java | 1 |
请完成以下Java代码 | public class AssetInfoEntity extends AbstractAssetEntity<AssetInfo> {
public static final Map<String,String> assetInfoColumnMap = new HashMap<>();
static {
assetInfoColumnMap.put("customerTitle", "c.title");
assetInfoColumnMap.put("assetProfileName", "p.name");
}
private String customerTitle;
private boolean customerIsPublic;
private String assetProfileName;
public AssetInfoEntity() {
super();
}
public AssetInfoEntity(AssetEntity assetEntity,
String customerTitle,
Object customerAdditionalInfo, | String assetProfileName) {
super(assetEntity);
this.customerTitle = customerTitle;
if (customerAdditionalInfo != null && ((JsonNode)customerAdditionalInfo).has("isPublic")) {
this.customerIsPublic = ((JsonNode)customerAdditionalInfo).get("isPublic").asBoolean();
} else {
this.customerIsPublic = false;
}
this.assetProfileName = assetProfileName;
}
@Override
public AssetInfo toData() {
return new AssetInfo(super.toAsset(), customerTitle, customerIsPublic, assetProfileName);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\AssetInfoEntity.java | 1 |
请完成以下Java代码 | public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
set_ValueNoCheck (COLUMNNAME_Price, Price);
}
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Produktschlüssel.
@param ProductValue
Key of the Product
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{
set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Produktschlüssel.
@return Key of the Product
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
} | /** Set SKU.
@param SKU
Stock Keeping Unit
*/
@Override
public void setSKU (java.lang.String SKU)
{
set_ValueNoCheck (COLUMNNAME_SKU, SKU);
}
/** Get SKU.
@return Stock Keeping Unit
*/
@Override
public java.lang.String getSKU ()
{
return (java.lang.String)get_Value(COLUMNNAME_SKU);
}
/** Set Symbol.
@param UOMSymbol
Symbol for a Unit of Measure
*/
@Override
public void setUOMSymbol (java.lang.String UOMSymbol)
{
set_ValueNoCheck (COLUMNNAME_UOMSymbol, UOMSymbol);
}
/** Get Symbol.
@return Symbol for a Unit of Measure
*/
@Override
public java.lang.String getUOMSymbol ()
{
return (java.lang.String)get_Value(COLUMNNAME_UOMSymbol);
}
/** Set UPC/EAN.
@param UPC
Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public void setUPC (java.lang.String UPC)
{
set_ValueNoCheck (COLUMNNAME_UPC, UPC);
}
/** Get UPC/EAN.
@return Bar Code (Universal Product Code or its superset European Article Number)
*/
@Override
public java.lang.String getUPC ()
{
return (java.lang.String)get_Value(COLUMNNAME_UPC);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLine_v.java | 1 |
请完成以下Java代码 | public void updatePostCalculationAmountsForCostElement(
final CurrencyPrecision precision,
final CostElementId costElementId)
{
final List<PPOrderCost> costs = filterAndList(PPOrderCostFilter.builder()
.costElementId(costElementId)
.build());
final List<PPOrderCost> inboundCosts = costs.stream()
.filter(PPOrderCost::isInboundCost)
.collect(ImmutableList.toImmutableList());
final PPOrderCost mainProductCost = costs.stream()
.filter(PPOrderCost::isMainProduct)
.collect(GuavaCollectors.singleElementOrThrow(() -> new AdempiereException("Single main product cost could not be found in " + costs)));
final ImmutableList<PPOrderCost> coProductCosts = costs.stream()
.filter(PPOrderCost::isCoProduct)
.collect(ImmutableList.toImmutableList());
//
// Update inbound costs and calculate total inbound costs
inboundCosts.forEach(PPOrderCost::setPostCalculationAmountAsAccumulatedAmt);
final CostAmount totalInboundCostAmount = inboundCosts.stream()
.map(PPOrderCost::getPostCalculationAmount)
.reduce(CostAmount::add)
.orElseThrow(() -> new AdempiereException("No inbound costs found in " + costs));
//
// Update co-product costs and calculate total co-product costs
coProductCosts.forEach(cost -> cost.setPostCalculationAmount(totalInboundCostAmount.multiply(cost.getCoProductCostDistributionPercent(), precision))); | final CostAmount totalCoProductsCostAmount = coProductCosts.stream()
.map(PPOrderCost::getPostCalculationAmount)
.reduce(CostAmount::add)
.orElseGet(totalInboundCostAmount::toZero);
//
// Update main product cost
mainProductCost.setPostCalculationAmount(totalInboundCostAmount.subtract(totalCoProductsCostAmount));
//
// Clear by-product costs
costs.stream()
.filter(PPOrderCost::isByProduct)
.forEach(PPOrderCost::setPostCalculationAmountAsZero);
}
private Set<CostElementId> getCostElementIds()
{
return costs.keySet()
.stream()
.map(CostSegmentAndElement::getCostElementId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCosts.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result putRecycleBin(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
try {
String ids = jsonObject.getString("ids");
if (StringUtils.isNotBlank(ids)) {
sysDictService.revertLogicDeleted(Arrays.asList(ids.split(",")));
return Result.ok("操作成功!");
}
} catch (Exception e) {
e.printStackTrace();
return Result.error("操作失败!");
}
return Result.ok("还原成功");
}
/**
* 彻底删除字典
*
* @param ids 被删除的字典ID,多个id用半角逗号分割
* @return
*/
@RequiresPermissions("system:dict:deleteRecycleBin")
@RequestMapping(value = "/deleteRecycleBin", method = RequestMethod.DELETE)
public Result deleteRecycleBin(@RequestParam("ids") String ids) {
try {
if (StringUtils.isNotBlank(ids)) {
sysDictService.removeLogicDeleted(Arrays.asList(ids.split(",")));
}
return Result.ok("删除成功!");
} catch (Exception e) {
e.printStackTrace();
return Result.error("删除失败!");
}
}
/**
* VUEN-2584【issue】平台sql注入漏洞几个问题
* 部分特殊函数 可以将查询结果混夹在错误信息中,导致数据库的信息暴露
* @param e
* @return
*/
@ExceptionHandler(java.sql.SQLException.class)
public Result<?> handleSQLException(Exception e){
String msg = e.getMessage();
String extractvalue = "extractvalue";
String updatexml = "updatexml"; | if(msg!=null && (msg.toLowerCase().indexOf(extractvalue)>=0 || msg.toLowerCase().indexOf(updatexml)>=0)){
return Result.error("校验失败,sql解析异常!");
}
return Result.error("校验失败,sql解析异常!" + msg);
}
/**
* 根据应用id获取字典列表和详情
* @param request
*/
@GetMapping("/getDictListByLowAppId")
public Result<List<SysDictVo>> getDictListByLowAppId(HttpServletRequest request){
String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request));
List<SysDictVo> list = sysDictService.getDictListByLowAppId(lowAppId);
return Result.ok(list);
}
/**
* 添加字典
* @param sysDictVo
* @param request
* @return
*/
@PostMapping("/addDictByLowAppId")
public Result<String> addDictByLowAppId(@RequestBody SysDictVo sysDictVo,HttpServletRequest request){
String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request));
String tenantId = oConvertUtils.getString(TokenUtils.getTenantIdByRequest(request));
sysDictVo.setLowAppId(lowAppId);
sysDictVo.setTenantId(oConvertUtils.getInteger(tenantId, null));
sysDictService.addDictByLowAppId(sysDictVo);
return Result.ok("添加成功");
}
@PutMapping("/editDictByLowAppId")
public Result<String> editDictByLowAppId(@RequestBody SysDictVo sysDictVo,HttpServletRequest request){
String lowAppId = oConvertUtils.getString(TokenUtils.getLowAppIdByRequest(request));
sysDictVo.setLowAppId(lowAppId);
sysDictService.editDictByLowAppId(sysDictVo);
return Result.ok("编辑成功");
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDictController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getAmount() {
return amount;
}
/**
* Sets the value of the amount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmount(BigDecimal value) {
this.amount = value;
}
/**
* Free text comment field for the given discount.
*
* @return
* possible object is
* {@link String }
*
*/
public String getComment() { | return comment;
}
/**
* Sets the value of the comment property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComment(String value) {
this.comment = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DiscountType.java | 2 |
请完成以下Spring Boot application配置 | spring:
application:
name: user-service # 服务名
# Zipkin 配置项,对应 ZipkinProperties 类
zipkin:
base-url: http://127.0.0.1:9411 # Zipkin 服务的地址
# Spring Cloud Sleuth 配置项
sleuth:
# Spring Cloud Sleuth 针对 Web 组件的配置项,例如说 SpringMVC
web:
enabled: true # 是否开启,默认为 true
data | :
# Elasticsearch 配置项
elasticsearch:
cluster-name: elasticsearch # 集群名
cluster-nodes: 127.0.0.1:9300 # 集群节点 | repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-db-elasticsearch\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ExcelExportConstants
{
public static ExcelExportConstants givenOrDefault(@Nullable final ExcelExportConstants constants)
{
return coalesce(constants, getFromSysConfig());
}
public static ExcelExportConstants getFromSysConfig()
{
final ISysConfigBL sysconfigs = Services.get(ISysConfigBL.class);
return ExcelExportConstants.builder()
.maxRowsToAllowCellWidthAutoSize(sysconfigs.getIntValue(SYSCONFIG_MaxRowsToAllowCellWidthAutoSize, DEFAULT_MaxRowsToAllowCellWidthAutoSize))
.useStreamingWorkbookImplementation(sysconfigs.getBooleanValue(SYSCONFIG_UseStreamingWorkbookImplementation, DEFAULT_UseStreamingWorkbookImplementation))
.allRowsPageSize(sysconfigs.getIntValue(SYSCONFIG_ALL_ROWS_PAGE_SIZE, DEFAULT_ALL_ROWS_PAGE_SIZE))
.build();
} | private static final String SYSCONFIG_MaxRowsToAllowCellWidthAutoSize = "de.metas.excel.MaxRowsToAllowCellWidthAutoSize";
private static final String SYSCONFIG_UseStreamingWorkbookImplementation = "de.metas.excel.UseStreamingWorkbookImplementation";
private static final String SYSCONFIG_ALL_ROWS_PAGE_SIZE = "de.metas.excel.ViewExcelExporter.AllRowsPageSize";
public static final int DEFAULT_MaxRowsToAllowCellWidthAutoSize = 100_000;
@Default
private int maxRowsToAllowCellWidthAutoSize = DEFAULT_MaxRowsToAllowCellWidthAutoSize;
public static final boolean DEFAULT_UseStreamingWorkbookImplementation = false;
private boolean useStreamingWorkbookImplementation;
public static final int DEFAULT_ALL_ROWS_PAGE_SIZE = 10000;
@Default
private int allRowsPageSize = DEFAULT_ALL_ROWS_PAGE_SIZE;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\ExcelExportConstants.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(codeService.removeByIds(Func.toLongList(ids)));
}
/**
* 复制
*/
@PostMapping("/copy")
@ApiOperationSupport(order = 5)
@Operation(summary = "复制", description = "传入id")
public R copy(@Parameter(description = "主键", required = true) @RequestParam Long id) {
Code code = codeService.getById(id);
code.setId(null);
code.setCodeName(code.getCodeName() + "-copy");
return R.status(codeService.save(code));
}
/**
* 代码生成
*/
@PostMapping("/gen-code")
@ApiOperationSupport(order = 6)
@Operation(summary = "代码生成", description = "传入ids")
public R genCode(@Parameter(description = "主键集合", required = true) @RequestParam String ids, @RequestParam(defaultValue = "saber3") String system) {
Collection<Code> codes = codeService.listByIds(Func.toLongList(ids));
codes.forEach(code -> { | BladeCodeGenerator generator = new BladeCodeGenerator();
// 设置数据源
Datasource datasource = datasourceService.getById(code.getDatasourceId());
generator.setDriverName(datasource.getDriverClass());
generator.setUrl(datasource.getUrl());
generator.setUsername(datasource.getUsername());
generator.setPassword(datasource.getPassword());
// 设置基础配置
generator.setSystemName(system);
generator.setServiceName(code.getServiceName());
generator.setPackageName(code.getPackageName());
generator.setPackageDir(code.getApiPath());
generator.setPackageWebDir(code.getWebPath());
generator.setTablePrefix(Func.toStrArray(code.getTablePrefix()));
generator.setIncludeTables(Func.toStrArray(code.getTableName()));
// 设置是否继承基础业务字段
generator.setHasSuperEntity(code.getBaseMode() == 2);
// 设置是否开启包装器模式
generator.setHasWrapper(code.getWrapMode() == 2);
generator.run();
});
return R.success("代码生成成功");
}
} | repos\SpringBlade-master\blade-ops\blade-develop\src\main\java\org\springblade\develop\controller\CodeController.java | 2 |
请完成以下Java代码 | private static ImmutableList<MADBoilerPlateVarEval> retrieveAll()
{
return queryBL.createQueryBuilder(I_AD_BoilerPlate_Var_Eval.Table_Name)
.orderBy(I_AD_BoilerPlate_Var_Eval.COLUMNNAME_AD_BoilerPlate_Var_ID)
.orderBy(I_AD_BoilerPlate_Var_Eval.COLUMNNAME_C_DocType_ID)
.create()
.listImmutable(MADBoilerPlateVarEval.class);
}
@SuppressWarnings("unused")
public MADBoilerPlateVarEval(Properties ctx, int AD_BoilerPlate_Var_Eval_ID, String trxName)
{
super(ctx, AD_BoilerPlate_Var_Eval_ID, trxName);
}
@SuppressWarnings("unused")
public MADBoilerPlateVarEval(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
}
@Override
public I_AD_BoilerPlate_Var getAD_BoilerPlate_Var() throws RuntimeException | {
if (get_TrxName() == null)
return MADBoilerPlateVar.get(getCtx(), getAD_BoilerPlate_Var_ID());
else
return super.getAD_BoilerPlate_Var();
}
@Override
public I_C_DocType getC_DocType() throws RuntimeException
{
if (get_TrxName() == null)
return MDocType.get(getCtx(), getC_DocType_ID());
else
return super.getC_DocType();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlateVarEval.java | 1 |
请完成以下Java代码 | public void updateOrderCostsOnOrderLineChanged(final OrderCostDetailOrderLinePart orderLineInfo)
{
orderCostRepository.changeByOrderLineId(
orderLineInfo.getOrderLineId(),
orderCost -> {
orderCost.updateOrderLineInfoIfApplies(orderLineInfo, moneyService::getStdPrecision, uomConversionBL);
updateCreatedOrderLineIfAny(orderCost);
});
}
private void updateCreatedOrderLineIfAny(@NonNull final OrderCost orderCost)
{
if (orderCost.getCreatedOrderLineId() == null)
{
return;
}
CreateOrUpdateOrderLineFromOrderCostCommand.builder()
.orderBL(orderBL)
.moneyService(moneyService) | .orderCost(orderCost)
.build()
.execute();
}
public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId)
{
orderCostRepository.deleteByCreatedOrderLineId(createdOrderLineId);
}
public boolean isCostGeneratedOrderLine(@NonNull final OrderLineId orderLineId)
{
return orderCostRepository.hasCostsByCreatedOrderLineIds(ImmutableSet.of(orderLineId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostService.java | 1 |
请完成以下Java代码 | public final class ALoginRes_sl extends ListResourceBundle
{
// TODO Run native2ascii to convert to plain ASCII !!
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Povezava" },
{ "Defaults", "Privzete vrednosti" },
{ "Login", "Prijava" },
{ "File", "Datoteka" },
{ "Exit", "Izhod" },
{ "Help", "Pomo\u010d" },
{ "About", "O programu" },
{ "Host", "Stre\u017enik" },
{ "Database", "Baza podatkov" },
{ "User", "Uporabnik" },
{ "EnterUser", "Vpi\u0161i uporabnika" },
{ "Password", "Geslo" },
{ "EnterPassword", "Vpi\u0161i geslo" },
{ "Language", "Jezik" },
{ "SelectLanguage", "Izbira jezika" },
{ "Role", "Vloga" },
{ "Client", "Podjetje" },
{ "Organization", "Organizacija" },
{ "Date", "Datum" },
{ "Warehouse", "Skladi\u0161\u010de" },
{ "Printer", "Tiskalnik" },
{ "Connected", "Povezano" },
{ "NotConnected", "Ni povezano" }, | { "DatabaseNotFound", "Ne najdem baze podatkov" },
{ "UserPwdError", "Geslo ni pravilno" },
{ "RoleNotFound", "Ne najdem izbrane vloge" },
{ "Authorized", "Avtoriziran" },
{ "Ok", "V redu" },
{ "Cancel", "Prekli\u010di" },
{ "VersionConflict", "Konflikt verzij" },
{ "VersionInfo", "Stre\u017enik <> Odjemalec" },
{ "PleaseUpgrade", "Prosim nadgradite program" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_sl.java | 1 |
请完成以下Java代码 | public static FaultInfo extractFaultInfoOrNull(final Object value)
{
if (value instanceof Msv3FaultInfo)
{
final Msv3FaultInfo msv3FaultInfo = (Msv3FaultInfo)value;
return fromJAXB(msv3FaultInfo);
}
else
{
return null;
}
}
public static final FaultInfo fromJAXB(final Msv3FaultInfo msv3FaultInfo)
{
if (msv3FaultInfo == null)
{
return null;
}
return FaultInfo.builder()
.errorCode(msv3FaultInfo.getErrorCode())
.userMessage(msv3FaultInfo.getEndanwenderFehlertext())
.technicalMessage(msv3FaultInfo.getTechnischerFehlertext())
.build();
} | public final Msv3FaultInfo toJAXB(final FaultInfo faultInfo)
{
if (faultInfo == null)
{
return null;
}
final Msv3FaultInfo soap = jaxbObjectFactory.createMsv3FaultInfo();
soap.setErrorCode(faultInfo.getErrorCode());
soap.setEndanwenderFehlertext(faultInfo.getUserMessage());
soap.setTechnischerFehlertext(faultInfo.getTechnicalMessage());
return soap;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\util\v2\MiscJAXBConvertersV2.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: dubbo-zookeeper-service-introspection-consumer-sample
demo:
service:
version: 1.0.0
embedded:
zookeeper:
port: 2181
dubbo:
application:
## "composite" is a new metadata type introduced since 2.7.8
metadata-type: composite
registry:
address: zookeeper://127.0.0.1:${embedded.zookeeper.port}/?registry-type=service
file: ${user.home}/dubbo-cache/${s | pring.application.name}/dubbo.cache
## "dubbo.registry.use-as-*" property will be auto-detected since 2.7.8
# use-as-config-center: true
# use-as-metadata-center: true | repos\dubbo-spring-boot-project-master\dubbo-spring-boot-samples\service-introspection-samples\zookeeper-samples\consumer-sample\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | private static class KPIDataCacheKey
{
@NonNull KPIId kpiId;
@NonNull KPITimeRangeDefaults timeRangeDefaults;
@NonNull KPIDataContext context;
}
@Value
@ToString(exclude = "data" /* because it's too big */)
private static class KPIDataCacheValue
{
public static KPIDataCacheValue ok(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted)
{
return new KPIDataCacheValue(data, defaultMaxStaleAccepted);
}
@NonNull Instant created = SystemTime.asInstant();
@NonNull Duration defaultMaxStaleAccepted;
KPIDataResult data;
public KPIDataCacheValue(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted)
{ | this.data = data;
this.defaultMaxStaleAccepted = defaultMaxStaleAccepted;
}
public boolean isExpired()
{
return isExpired(null);
}
public boolean isExpired(@Nullable final Duration maxStaleAccepted)
{
final Duration maxStaleAcceptedEffective = maxStaleAccepted != null
? maxStaleAccepted
: defaultMaxStaleAccepted;
final Instant now = SystemTime.asInstant();
final Duration staleActual = Duration.between(created, now);
final boolean expired = staleActual.compareTo(maxStaleAcceptedEffective) > 0;
logger.trace("isExpired={}, now={}, maxStaleAcceptedEffective={}, staleActual={}, cacheValue={}", expired, now, maxStaleAcceptedEffective, staleActual, this);
return expired;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataProvider.java | 2 |
请完成以下Java代码 | class SharedPrinter {
private final Semaphore semEven = new Semaphore(0);
private final Semaphore semOdd = new Semaphore(1);
void printEvenNum(int num) {
try {
semEven.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + ":"+num);
semOdd.release();
}
void printOddNum(int num) {
try {
semOdd.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(Thread.currentThread().getName() + ":"+ num);
semEven.release();
}
}
class Even implements Runnable {
private final SharedPrinter sp;
private final int max;
Even(SharedPrinter sp, int max) {
this.sp = sp;
this.max = max;
}
@Override
public void run() {
for (int i = 2; i <= max; i = i + 2) {
sp.printEvenNum(i);
} | }
}
class Odd implements Runnable {
private SharedPrinter sp;
private int max;
Odd(SharedPrinter sp, int max) {
this.sp = sp;
this.max = max;
}
@Override
public void run() {
for (int i = 1; i <= max; i = i + 2) {
sp.printOddNum(i);
}
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-2\src\main\java\com\baeldung\concurrent\evenandodd\PrintEvenOddSemaphore.java | 1 |
请完成以下Java代码 | public synchronized <T> T getBeanOrNull(@NonNull final Class<T> beanType)
{
assertJUnitMode();
final ArrayList<Object> beans = map.get(ClassReference.of(beanType));
if (beans == null || beans.isEmpty())
{
return null;
}
if (beans.size() > 1)
{
logger.warn("Found more than one bean for {} but returning the first one: {}", beanType, beans);
}
final T beanImpl = castBean(beans.get(0), beanType);
logger.debug("JUnit testing Returning manually registered bean: {}", beanImpl);
return beanImpl;
}
private static <T> T castBean(final Object beanImpl, final Class<T> ignoredBeanType)
{
@SuppressWarnings("unchecked") final T beanImplCasted = (T)beanImpl;
return beanImplCasted;
}
public synchronized <T> ImmutableList<T> getBeansOfTypeOrNull(@NonNull final Class<T> beanType)
{
assertJUnitMode(); | List<Object> beanObjs = map.get(ClassReference.of(beanType));
if (beanObjs == null)
{
final List<Object> assignableBeans = map.values()
.stream()
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(impl -> beanType.isAssignableFrom(impl.getClass()))
.collect(Collectors.toList());
if (assignableBeans.isEmpty())
{
return null;
}
beanObjs = assignableBeans;
}
return beanObjs
.stream()
.map(beanObj -> castBean(beanObj, beanType))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\JUnitBeansMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InfoFromBuyer
{
public static final String SERIALIZED_NAME_NOTE = "note";
@SerializedName(SERIALIZED_NAME_NOTE)
private String note;
public static final String SERIALIZED_NAME_RETURN_SHIPMENT_TRACKING = "returnShipmentTracking";
@SerializedName(SERIALIZED_NAME_RETURN_SHIPMENT_TRACKING)
private List<TrackingInfo> returnShipmentTracking = null;
public InfoFromBuyer note(String note)
{
this.note = note;
return this;
}
/**
* This field shows any note that was left by the buyer for in regards to the dispute.
*
* @return note
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "This field shows any note that was left by the buyer for in regards to the dispute.")
public String getNote()
{
return note;
}
public void setNote(String note)
{
this.note = note;
}
public InfoFromBuyer returnShipmentTracking(List<TrackingInfo> returnShipmentTracking)
{
this.returnShipmentTracking = returnShipmentTracking;
return this;
}
public InfoFromBuyer addReturnShipmentTrackingItem(TrackingInfo returnShipmentTrackingItem)
{
if (this.returnShipmentTracking == null)
{
this.returnShipmentTracking = new ArrayList<>();
}
this.returnShipmentTracking.add(returnShipmentTrackingItem);
return this;
}
/**
* This array shows shipment tracking information for one or more shipping packages being returned to the buyer after a payment dispute.
*
* @return returnShipmentTracking
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "This array shows shipment tracking information for one or more shipping packages being returned to the buyer after a payment dispute.")
public List<TrackingInfo> getReturnShipmentTracking()
{
return returnShipmentTracking;
}
public void setReturnShipmentTracking(List<TrackingInfo> returnShipmentTracking) | {
this.returnShipmentTracking = returnShipmentTracking;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
InfoFromBuyer infoFromBuyer = (InfoFromBuyer)o;
return Objects.equals(this.note, infoFromBuyer.note) &&
Objects.equals(this.returnShipmentTracking, infoFromBuyer.returnShipmentTracking);
}
@Override
public int hashCode()
{
return Objects.hash(note, returnShipmentTracking);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class InfoFromBuyer {\n");
sb.append(" note: ").append(toIndentedString(note)).append("\n");
sb.append(" returnShipmentTracking: ").append(toIndentedString(returnShipmentTracking)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\InfoFromBuyer.java | 2 |
请完成以下Java代码 | public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setLineNetAmt (final BigDecimal LineNetAmt)
{
set_Value (COLUMNNAME_LineNetAmt, LineNetAmt);
}
@Override
public BigDecimal getLineNetAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_LineNetAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
} | @Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReceived (final BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
@Override
public BigDecimal getQtyReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java | 1 |
请完成以下Java代码 | public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setMsgTip (final @Nullable java.lang.String MsgTip)
{
set_Value (COLUMNNAME_MsgTip, MsgTip);
}
@Override
public java.lang.String getMsgTip()
{
return get_ValueAsString(COLUMNNAME_MsgTip);
}
/**
* MsgType AD_Reference_ID=103
* Reference name: AD_Message Type
*/
public static final int MSGTYPE_AD_Reference_ID=103;
/** Fehler = E */
public static final String MSGTYPE_Fehler = "E";
/** Information = I */ | public static final String MSGTYPE_Information = "I";
/** Menü = M */
public static final String MSGTYPE_Menue = "M";
@Override
public void setMsgType (final java.lang.String MsgType)
{
set_Value (COLUMNNAME_MsgType, MsgType);
}
@Override
public java.lang.String getMsgType()
{
return get_ValueAsString(COLUMNNAME_MsgType);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CustomerMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2019-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CustomerMapping customerMapping = (CustomerMapping) o;
return Objects.equals(this._id, customerMapping._id) &&
Objects.equals(this.customerId, customerMapping.customerId) &&
Objects.equals(this.updated, customerMapping.updated);
}
@Override
public int hashCode() {
return Objects.hash(_id, customerId, updated);
} | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CustomerMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" customerId: ").append(toIndentedString(customerId)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\CustomerMapping.java | 2 |
请完成以下Java代码 | public boolean isActive() {
return caseActivityInstanceState == ACTIVE.getStateCode();
}
public boolean isSuspended() {
return caseActivityInstanceState == SUSPENDED.getStateCode();
}
public boolean isCompleted() {
return caseActivityInstanceState == COMPLETED.getStateCode();
}
public boolean isTerminated() {
return caseActivityInstanceState == TERMINATED.getStateCode();
}
public String toString() {
return this.getClass().getSimpleName()
+ "[caseActivityId=" + caseActivityId
+ ", caseActivityName=" + caseActivityName
+ ", caseActivityInstanceId=" + id
+ ", caseActivityInstanceState=" + caseActivityInstanceState | + ", parentCaseActivityInstanceId=" + parentCaseActivityInstanceId
+ ", taskId=" + taskId
+ ", calledProcessInstanceId=" + calledProcessInstanceId
+ ", calledCaseInstanceId=" + calledCaseInstanceId
+ ", durationInMillis=" + durationInMillis
+ ", createTime=" + startTime
+ ", endTime=" + endTime
+ ", eventType=" + eventType
+ ", caseExecutionId=" + caseExecutionId
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseActivityInstanceEventEntity.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
} | public long getId() {
return id;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
@Override
public String toString() {
return String.format("ID: %d\nName: %s\nLast Modified: %s\nAbout: %s\n", getId(), getName(), getLastModified(), getAbout());
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\interceptors\entity\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PurchaseService {
private final PaymentMethodClient paymentMethodClient;
private final ReportClient reportClient;
public PurchaseService(PaymentMethodClient paymentMethodClient, ReportClient reportClient) {
this.paymentMethodClient = paymentMethodClient;
this.reportClient = reportClient;
}
public String executePurchase(String siteId) throws ExecutionException, InterruptedException {
CompletableFuture<String> paymentMethodsFuture = CompletableFuture.supplyAsync(() -> paymentMethodClient.getAvailablePaymentMethods(siteId))
.orTimeout(400, TimeUnit.MILLISECONDS)
.exceptionally(ex -> {
if (ex.getCause() instanceof FeignException && ((FeignException) ex.getCause()).status() == 404) {
return "cash";
}
if (ex.getCause() instanceof RetryableException) {
// handle REST timeout
throw new RuntimeException("REST call network timeout!"); | }
if (ex instanceof TimeoutException) {
// handle thread timeout
throw new RuntimeException("Thread timeout!", ex);
}
throw new RuntimeException("Unrecoverable error!", ex);
});
CompletableFuture.runAsync(() -> reportClient.sendReport("Purchase Order Report"))
.orTimeout(400, TimeUnit.MILLISECONDS);
return String.format("Purchase executed with payment method %s", paymentMethodsFuture.get());
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign-2\src\main\java\com\baeldung\cloud\openfeign\completablefuturefeignclient\PurchaseService.java | 2 |
请完成以下Java代码 | public static String compile(String tag, String name)
{
if (tag.startsWith("m")) return Predefine.TAG_NUMBER;
else if (tag.startsWith("nr")) return Predefine.TAG_PEOPLE;
else if (tag.startsWith("ns")) return Predefine.TAG_PLACE;
else if (tag.startsWith("nt")) return Predefine.TAG_GROUP;
else if (tag.startsWith("t")) return Predefine.TAG_TIME;
else if (tag.equals("x")) return Predefine.TAG_CLUSTER;
else if (tag.equals("nx")) return Predefine.TAG_PROPER;
else if (tag.equals("xx")) return Predefine.TAG_OTHER;
// switch (tag)
// {
// case "m":
// case "mq":
// return Predefine.TAG_NUMBER;
// case "nr":
// case "nr1":
// case "nr2": | // case "nrf":
// case "nrj":
// return Predefine.TAG_PEOPLE;
// case "ns":
// case "nsf":
// return Predefine.TAG_PLACE;
// case "nt":
// return Predefine.TAG_TIME;
// case "x":
// return Predefine.TAG_CLUSTER;
// case "nx":
// return Predefine.TAG_PROPER;
// }
return name;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\PosTagCompiler.java | 1 |
请完成以下Java代码 | public Instant getParameterValueAsInstantOrNull(@NonNull final String parameterName)
{
final DocumentFilterParam param = getParameterOrNull(parameterName);
if (param == null)
{
return null;
}
return param.getValueAsInstant();
}
@Nullable
public Instant getParameterValueToAsInstantOrNull(@NonNull final String parameterName)
{
final DocumentFilterParam param = getParameterOrNull(parameterName);
if (param == null)
{
return null;
}
return param.getValueToAsInstant();
}
@Nullable
public <T extends RepoIdAware> T getParameterValueAsRepoIdOrNull(@NonNull final String parameterName, @NonNull final IntFunction<T> repoIdMapper)
{
final DocumentFilterParam param = getParameterOrNull(parameterName);
if (param == null)
{
return null;
}
return param.getValueAsRepoIdOrNull(repoIdMapper);
}
@Nullable
public <T extends ReferenceListAwareEnum> T getParameterValueAsRefListOrNull(@NonNull final String parameterName, @NonNull final Function<String, T> mapper)
{
final DocumentFilterParam param = getParameterOrNull(parameterName);
if (param == null)
{
return null;
}
return param.getValueAsRefListOrNull(mapper);
}
@Nullable
public <T> T getParameterValueAs(@NonNull final String parameterName)
{
final DocumentFilterParam param = getParameterOrNull(parameterName);
if (param == null)
{
return null;
}
@SuppressWarnings("unchecked") final T value = (T)param.getValue();
return value;
}
//
//
//
//
//
public static final class DocumentFilterBuilder
{
public DocumentFilterBuilder setFilterId(final String filterId)
{
return filterId(filterId);
}
public DocumentFilterBuilder setCaption(@NonNull final ITranslatableString caption) | {
return caption(caption);
}
public DocumentFilterBuilder setCaption(@NonNull final String caption)
{
return caption(TranslatableStrings.constant(caption));
}
public DocumentFilterBuilder setFacetFilter(final boolean facetFilter)
{
return facetFilter(facetFilter);
}
public boolean hasParameters()
{
return !Check.isEmpty(parameters)
|| !Check.isEmpty(internalParameterNames);
}
public DocumentFilterBuilder setParameters(@NonNull final List<DocumentFilterParam> parameters)
{
return parameters(parameters);
}
public DocumentFilterBuilder addParameter(@NonNull final DocumentFilterParam parameter)
{
return parameter(parameter);
}
public DocumentFilterBuilder addInternalParameter(@NonNull final DocumentFilterParam parameter)
{
parameter(parameter);
internalParameterName(parameter.getFieldName());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilter.java | 1 |
请完成以下Java代码 | private void unsuccessfulRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response,
AuthenticationException ex) throws IOException {
Throwable cause = ex.getCause();
LogMessage message = LogMessage.format("Authorization Request failed: %s", cause);
if (InvalidClientRegistrationIdException.class.isAssignableFrom(cause.getClass())) {
// Log an invalid registrationId at WARN level to allow these errors to be
// tuned separately from other errors
this.logger.warn(message, ex);
}
else {
this.logger.error(message, ex);
}
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer {
@Override | protected void initExtractorMap() {
super.initExtractorMap();
registerExtractor(ServletException.class, (throwable) -> {
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
return ((ServletException) throwable).getRootCause();
});
}
}
private static final class OAuth2AuthorizationRequestException extends AuthenticationException {
OAuth2AuthorizationRequestException(Throwable cause) {
super(cause.getMessage(), cause);
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationRequestRedirectFilter.java | 1 |
请完成以下Java代码 | private static final class DefaultOidcUserInfoMapper
implements Function<OidcUserInfoAuthenticationContext, OidcUserInfo> {
// @formatter:off
private static final List<String> EMAIL_CLAIMS = Arrays.asList(
StandardClaimNames.EMAIL,
StandardClaimNames.EMAIL_VERIFIED
);
private static final List<String> PHONE_CLAIMS = Arrays.asList(
StandardClaimNames.PHONE_NUMBER,
StandardClaimNames.PHONE_NUMBER_VERIFIED
);
private static final List<String> PROFILE_CLAIMS = Arrays.asList(
StandardClaimNames.NAME,
StandardClaimNames.FAMILY_NAME,
StandardClaimNames.GIVEN_NAME,
StandardClaimNames.MIDDLE_NAME,
StandardClaimNames.NICKNAME,
StandardClaimNames.PREFERRED_USERNAME,
StandardClaimNames.PROFILE,
StandardClaimNames.PICTURE,
StandardClaimNames.WEBSITE,
StandardClaimNames.GENDER,
StandardClaimNames.BIRTHDATE,
StandardClaimNames.ZONEINFO,
StandardClaimNames.LOCALE,
StandardClaimNames.UPDATED_AT
);
// @formatter:on
@Override
public OidcUserInfo apply(OidcUserInfoAuthenticationContext authenticationContext) {
OAuth2Authorization authorization = authenticationContext.getAuthorization();
OidcIdToken idToken = authorization.getToken(OidcIdToken.class).getToken();
OAuth2AccessToken accessToken = authenticationContext.getAccessToken();
Map<String, Object> scopeRequestedClaims = getClaimsRequestedByScope(idToken.getClaims(),
accessToken.getScopes());
return new OidcUserInfo(scopeRequestedClaims);
} | private static Map<String, Object> getClaimsRequestedByScope(Map<String, Object> claims,
Set<String> requestedScopes) {
Set<String> scopeRequestedClaimNames = new HashSet<>(32);
scopeRequestedClaimNames.add(StandardClaimNames.SUB);
if (requestedScopes.contains(OidcScopes.ADDRESS)) {
scopeRequestedClaimNames.add(StandardClaimNames.ADDRESS);
}
if (requestedScopes.contains(OidcScopes.EMAIL)) {
scopeRequestedClaimNames.addAll(EMAIL_CLAIMS);
}
if (requestedScopes.contains(OidcScopes.PHONE)) {
scopeRequestedClaimNames.addAll(PHONE_CLAIMS);
}
if (requestedScopes.contains(OidcScopes.PROFILE)) {
scopeRequestedClaimNames.addAll(PROFILE_CLAIMS);
}
Map<String, Object> requestedClaims = new HashMap<>(claims);
requestedClaims.keySet().removeIf((claimName) -> !scopeRequestedClaimNames.contains(claimName));
return requestedClaims;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\authentication\OidcUserInfoAuthenticationProvider.java | 1 |
请完成以下Java代码 | public static void setSuspensionState(TaskEntity taskEntity, SuspensionState state) {
if (taskEntity.getSuspensionState() == state.getStateCode()) {
throw new FlowableException("Cannot set suspension state '" + state + "' for " + taskEntity + "': already in state '" + state + "'.");
}
taskEntity.setSuspensionState(state.getStateCode());
addTaskSuspensionStateEntryLog(taskEntity, state);
dispatchStateChangeEvent(taskEntity, state);
}
protected static void addTaskSuspensionStateEntryLog(TaskEntity taskEntity, SuspensionState state) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
TaskServiceConfiguration taskServiceConfiguration = processEngineConfiguration.getTaskServiceConfiguration();
if (taskServiceConfiguration.isEnableHistoricTaskLogging()) {
BaseHistoricTaskLogEntryBuilderImpl taskLogEntryBuilder = new BaseHistoricTaskLogEntryBuilderImpl(taskEntity);
ObjectNode data = taskServiceConfiguration.getObjectMapper().createObjectNode();
data.put("previousSuspensionState", taskEntity.getSuspensionState());
data.put("newSuspensionState", state.getStateCode());
taskLogEntryBuilder.timeStamp(taskServiceConfiguration.getClock().getCurrentTime());
taskLogEntryBuilder.userId(Authentication.getAuthenticatedUserId());
taskLogEntryBuilder.data(data.toString());
taskLogEntryBuilder.type(HistoricTaskLogEntryType.USER_TASK_SUSPENSIONSTATE_CHANGED.name());
taskServiceConfiguration.getInternalHistoryTaskManager().recordHistoryUserTaskLog(taskLogEntryBuilder); | }
}
protected static void dispatchStateChangeEvent(Object entity, SuspensionState state) {
CommandContext commandContext = Context.getCommandContext();
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
FlowableEventDispatcher eventDispatcher = null;
if (commandContext != null) {
eventDispatcher = processEngineConfiguration.getEventDispatcher();
}
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
FlowableEngineEventType eventType = null;
if (state == SuspensionState.ACTIVE) {
eventType = FlowableEngineEventType.ENTITY_ACTIVATED;
} else {
eventType = FlowableEngineEventType.ENTITY_SUSPENDED;
}
eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(eventType, entity), processEngineConfiguration.getEngineCfgKey());
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\SuspensionStateUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BPGroupId getBPGroupByBPartnerId(@NonNull final BPartnerId bpartnerId)
{
return BPGroupId.ofRepoId(getByBPartnerId(bpartnerId).getC_BP_Group_ID());
}
@Override
@Nullable
public I_C_BP_Group getDefaultByClientOrgId(@NonNull final ClientAndOrgId clientAndOrgId)
{
final BPGroupId bpGroupId = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_BP_Group.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_BP_Group.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId())
.addInArrayFilter(I_C_BP_Group.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId(), OrgId.ANY)
.addEqualsFilter(I_C_BP_Group.COLUMNNAME_IsDefault, true)
.orderByDescending(I_C_BP_Group.COLUMNNAME_AD_Org_ID)
.create()
.firstId(BPGroupId::ofRepoIdOrNull);
if (bpGroupId == null)
{
logger.warn("No default BP group found for {}", clientAndOrgId);
return null;
}
return getById(bpGroupId);
} | @Override
public BPartnerNameAndGreetingStrategyId getBPartnerNameAndGreetingStrategyId(@NonNull final BPGroupId bpGroupId)
{
final I_C_BP_Group bpGroup = getById(bpGroupId);
return StringUtils.trimBlankToOptional(bpGroup.getBPNameAndGreetingStrategy())
.map(BPartnerNameAndGreetingStrategyId::ofString)
.orElse(DoNothingBPartnerNameAndGreetingStrategy.ID);
}
@Override
public void save(@NonNull final I_C_BP_Group bpGroup)
{
InterfaceWrapperHelper.saveRecord(bpGroup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPGroupDAO.java | 2 |
请完成以下Java代码 | public class PaymentsToReconcileViewFactory implements IViewFactory, IViewsIndexStorage
{
static final String WINDOW_ID_String = "paymentsToReconcile";
public static final WindowId WINDOW_ID = WindowId.fromJson(WINDOW_ID_String);
private final BankStatementReconciliationViewFactory banksStatementReconciliationViewFactory;
public PaymentsToReconcileViewFactory(
@NonNull final BankStatementReconciliationViewFactory banksStatementReconciliationViewFactory)
{
this.banksStatementReconciliationViewFactory = banksStatementReconciliationViewFactory;
}
@Override
public void setViewsRepository(@NonNull final IViewsRepository viewsRepository)
{
// nothing
}
@Override
public IView createView(final @NonNull CreateViewRequest request)
{
throw new UnsupportedOperationException();
}
@Override
public ViewLayout getViewLayout(
final WindowId windowId,
final JSONViewDataType viewDataType,
final ViewProfileId profileId)
{
Check.assumeEquals(windowId, WINDOW_ID, "windowId");
return ViewLayout.builder()
.setWindowId(WINDOW_ID)
.setCaption(TranslatableStrings.empty())
.setAllowOpeningRowDetails(false)
.addElementsFromViewRowClass(PaymentToReconcileRow.class, viewDataType)
.build();
}
@Override
public WindowId getWindowId()
{
return WINDOW_ID;
}
@Override
public void put(final IView view)
{ | throw new UnsupportedOperationException();
}
@Nullable
@Override
public PaymentsToReconcileView getByIdOrNull(@NonNull final ViewId paymentsToReconcileViewId)
{
final ViewId bankStatementReconciliationViewId = toBankStatementReconciliationViewId(paymentsToReconcileViewId);
final BankStatementReconciliationView bankStatementReconciliationView = banksStatementReconciliationViewFactory.getByIdOrNull(bankStatementReconciliationViewId);
return bankStatementReconciliationView != null
? bankStatementReconciliationView.getPaymentsToReconcileView()
: null;
}
private static ViewId toBankStatementReconciliationViewId(@NonNull final ViewId paymentsToReconcileViewId)
{
return paymentsToReconcileViewId.withWindowId(BankStatementReconciliationViewFactory.WINDOW_ID);
}
@Override
public void closeById(final ViewId viewId, final ViewCloseAction closeAction)
{
// nothing
}
@Override
public Stream<IView> streamAllViews()
{
return banksStatementReconciliationViewFactory.streamAllViews()
.map(BankStatementReconciliationView::cast)
.map(BankStatementReconciliationView::getPaymentsToReconcileView);
}
@Override
public void invalidateView(final ViewId paymentsToReconcileViewId)
{
final PaymentsToReconcileView paymentsToReconcileView = getByIdOrNull(paymentsToReconcileViewId);
if (paymentsToReconcileView != null)
{
paymentsToReconcileView.invalidateAll();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\bankstatement_reconciliation\PaymentsToReconcileViewFactory.java | 1 |
请完成以下Java代码 | String getEntityTypeForTableName(final String tableName)
{
return TableIdsCache.instance.getEntityType(tableName);
}
/**
* Get PO class.
*
* @param className fully qualified class name
* @return class or <code>null</code> if model class was not found or it's not valid
*/
private Class<?> loadModelClassForClassname(final String className)
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
final Class<?> clazz = classLoader.loadClass(className);
// Make sure that it is a PO class
if (!PO.class.isAssignableFrom(clazz))
{
log.debug("Skip {} because it does not have PO class as supertype", clazz);
return null;
}
return clazz;
}
catch (ClassNotFoundException e)
{
if (log.isDebugEnabled())
{
log.debug("No class found for " + className + " (classloader: " + classLoader + ")", e);
}
}
return null; | }
private final Constructor<?> findIDConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, int.class, String.class });
}
public Constructor<?> getIDConstructor(final Class<?> modelClass)
{
try
{
return class2idConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ID constructor for " + modelClass, e);
}
}
private final Constructor<?> findResultSetConstructor(final Class<?> modelClass) throws NoSuchMethodException, SecurityException
{
return modelClass.getDeclaredConstructor(new Class[] { Properties.class, ResultSet.class, String.class });
}
public Constructor<?> getResultSetConstructor(final Class<?> modelClass)
{
try
{
return class2resultSetConstructor.get(modelClass);
}
catch (ExecutionException e)
{
throw new AdempiereException("Cannot get ResultSet constructor for " + modelClass, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelClassLoader.java | 1 |
请完成以下Java代码 | public Builder registeredClient(RegisteredClient registeredClient) {
return put(RegisteredClient.class, registeredClient);
}
/**
* Sets the {@link OAuth2AuthorizationRequest authorization request}.
* @param authorizationRequest the {@link OAuth2AuthorizationRequest}
* @return the {@link Builder} for further configuration
*/
public Builder authorizationRequest(OAuth2AuthorizationRequest authorizationRequest) {
return put(OAuth2AuthorizationRequest.class, authorizationRequest);
}
/**
* Sets the {@link OAuth2AuthorizationConsent authorization consent}.
* @param authorizationConsent the {@link OAuth2AuthorizationConsent}
* @return the {@link Builder} for further configuration
*/
public Builder authorizationConsent(OAuth2AuthorizationConsent authorizationConsent) {
return put(OAuth2AuthorizationConsent.class, authorizationConsent); | }
/**
* Builds a new {@link OAuth2AuthorizationCodeRequestAuthenticationContext}.
* @return the {@link OAuth2AuthorizationCodeRequestAuthenticationContext}
*/
@Override
public OAuth2AuthorizationCodeRequestAuthenticationContext build() {
Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null");
return new OAuth2AuthorizationCodeRequestAuthenticationContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeRequestAuthenticationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AttributeSetHelper
{
private final IAttributeDAO attributeDAO = Services.get(IAttributeDAO.class);
public List<CreateAttributeInstanceReq> toCreateAttributeInstanceReqList(@NonNull final Collection<JsonAttributeInstance> jsonAttributeInstances)
{
return jsonAttributeInstances.stream()
.map(this::toCreateAttributeInstanceReq)
.collect(ImmutableList.toImmutableList());
}
private CreateAttributeInstanceReq toCreateAttributeInstanceReq(@NonNull final JsonAttributeInstance jsonAttributeInstance)
{
return CreateAttributeInstanceReq.builder()
.attributeCode(AttributeCode.ofString(jsonAttributeInstance.getAttributeCode()))
.value(extractAttributeValueObject(jsonAttributeInstance))
.build();
}
private Object extractAttributeValueObject(@NonNull final JsonAttributeInstance attributeInstance) | {
final I_M_Attribute attribute = attributeDAO.retrieveAttributeByValue(attributeInstance.getAttributeCode());
final AttributeValueType targetAttributeType = AttributeValueType.ofCode(attribute.getAttributeValueType());
switch (targetAttributeType)
{
case DATE:
return attributeInstance.getValueDate();
case NUMBER:
return attributeInstance.getValueNumber();
case STRING:
case LIST:
return attributeInstance.getValueStr();
default:
throw new IllegalArgumentException("@NotSupported@ @AttributeValueType@=" + targetAttributeType + ", @M_Attribute_ID@=" + attribute.getM_Attribute_ID());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\AttributeSetHelper.java | 2 |
请完成以下Java代码 | public Stream<HuForInventoryLine> ofHURecord(@NonNull final I_M_HU huRecord)
{
final HuForInventoryLineBuilder builder = HuForInventoryLine
.builder()
.orgId(OrgId.ofRepoId(huRecord.getAD_Org_ID()))
.locatorId(IHandlingUnitsBL.extractLocatorId(huRecord));
return handlingUnitsBL
.getStorageFactory()
.streamHUProductStorages(huRecord)
.filter(huProductStorage -> !huProductStorage.isEmpty())
.map(huProductStorage -> createHuForInventoryLine(builder, huProductStorage));
}
private HuForInventoryLine createHuForInventoryLine( | @NonNull final HuForInventoryLineBuilder huForInventoryLineBuilder,
@NonNull final IHUProductStorage huProductStorage)
{
final AttributesKey attributesKey = handlingUnitsBL.getAttributesKeyForInventory(huProductStorage.getM_HU());
final Quantity qty = huProductStorage.getQty();
return huForInventoryLineBuilder
.storageAttributesKey(attributesKey)
.huId(huProductStorage.getHuId())
.productId(huProductStorage.getProductId())
.quantityBooked(qty)
.quantityCount(qty)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\HuForInventoryLineFactory.java | 1 |
请完成以下Java代码 | public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<HistoricDecisionInputInstance> getInputs() {
if(inputs != null) {
return inputs;
} else {
throw LOG.historicDecisionInputInstancesNotFetchedException();
}
}
@Override
public List<HistoricDecisionOutputInstance> getOutputs() {
if(outputs != null) {
return outputs;
} else {
throw LOG.historicDecisionOutputInstancesNotFetchedException();
}
}
public void setInputs(List<HistoricDecisionInputInstance> inputs) {
this.inputs = inputs;
}
public void setOutputs(List<HistoricDecisionOutputInstance> outputs) {
this.outputs = outputs;
}
public void delete() {
Context
.getCommandContext()
.getDbEntityManager()
.delete(this);
}
public void addInput(HistoricDecisionInputInstance decisionInputInstance) {
if(inputs == null) {
inputs = new ArrayList<HistoricDecisionInputInstance>();
}
inputs.add(decisionInputInstance);
} | public void addOutput(HistoricDecisionOutputInstance decisionOutputInstance) {
if(outputs == null) {
outputs = new ArrayList<HistoricDecisionOutputInstance>();
}
outputs.add(decisionOutputInstance);
}
public Double getCollectResultValue() {
return collectResultValue;
}
public void setCollectResultValue(Double collectResultValue) {
this.collectResultValue = collectResultValue;
}
public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
public void setRootDecisionInstanceId(String rootDecisionInstanceId) {
this.rootDecisionInstanceId = rootDecisionInstanceId;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) {
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java | 1 |
请完成以下Java代码 | public class DhlCustomDeliveryData implements CustomDeliveryData
{
@Singular
@NonNull
private final ImmutableList<DhlCustomDeliveryDataDetail> details;
@NonNull
public static DhlCustomDeliveryData cast(@NonNull final CustomDeliveryData customDeliveryData)
{
return (DhlCustomDeliveryData)customDeliveryData;
}
@NonNull
public ImmutableList<DhlCustomDeliveryDataDetail> getDetails()
{
return ImmutableList.copyOf(details);
}
@NonNull
public DhlCustomDeliveryDataDetail getDetailByPackageId(final PackageId packageId)
{
//noinspection OptionalGetWithoutIsPresent
return details.stream()
.filter(it -> Objects.equals(it.getPackageId(), packageId))
.findFirst()
.get(); | }
@NonNull
public DhlCustomDeliveryDataDetail getDetailBySequenceNumber(@NonNull final DhlSequenceNumber sequenceNumber)
{
//noinspection OptionalGetWithoutIsPresent
return details.stream()
.filter(it -> it.getSequenceNumber().equals(sequenceNumber))
.findFirst()
.get();
}
@NonNull
public DhlCustomDeliveryData withDhlCustomDeliveryDataDetails(@Nullable final ImmutableList<DhlCustomDeliveryDataDetail> details)
{
if (details == null)
{
return this;
}
return toBuilder()
.clearDetails()
.details(details)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\model\DhlCustomDeliveryData.java | 1 |
请完成以下Java代码 | public Json oper(String operate) {
this.put(KEY_OPER, operate);
return this;
}
/** 设置操作结果是否成功的标记 */
public Json succ(boolean success) {
this.put(KEY_SUCC, success);
return this;
}
/** 设置操作结果的代码 */
public Json code(int code) {
this.put(KEY_CODE, code);
return this;
}
/** 设置操作结果的信息 */
public Json msg(String message) { | this.put(KEY_MSG, message);
return this;
}
/** 设置操作返回的数据 */
public Json data(Object dataVal) {
this.put(KEY_DATA, dataVal);
return this;
}
/** 设置操作返回的数据,数据使用自定义的key存储 */
public Json data(String dataKey, Object dataVal) {
this.put(dataKey, dataVal);
return this;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\vo\Json.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Saml2AuthenticationToken getToken() {
return this.token;
}
}
/**
* A tuple containing an OpenSAML {@link Assertion} and its associated authentication
* token.
*
* @since 5.4
*/
static class AssertionToken {
private final Saml2AuthenticationToken token;
private final Assertion assertion; | AssertionToken(Assertion assertion, Saml2AuthenticationToken token) {
this.token = token;
this.assertion = assertion;
}
Assertion getAssertion() {
return this.assertion;
}
Saml2AuthenticationToken getToken() {
return this.token;
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\BaseOpenSamlAuthenticationProvider.java | 2 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getAdminCount() {
return adminCount;
}
public void setAdminCount(Integer adminCount) {
this.adminCount = adminCount;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getSort() { | return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", description=").append(description);
sb.append(", adminCount=").append(adminCount);
sb.append(", createTime=").append(createTime);
sb.append(", status=").append(status);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsRole.java | 1 |
请完成以下Java代码 | public void patternMatches(Blackhole bh) {
// Above approach "value.matches(PATTERN)" makes this internally
// 5_000_000 Pattern objects created
// 5_000_000 Matcher objects created
for (String value : values) {
bh.consume(Pattern.matches(PATTERN, value));
}
}
@Benchmark
public void stringMatchs(Blackhole bh) {
// 5_000_000 Pattern objects created
// 5_000_000 Matcher objects created
Instant start = Instant.now();
for (String value : values) { | bh.consume(value.matches(PATTERN));
}
}
@Setup()
public void setUp() {
preCompiledPattern = Pattern.compile(PATTERN);
matcherFromPreCompiledPattern = preCompiledPattern.matcher("");
values = new ArrayList<>();
for (int x = 1; x <= 5_000_000; x++) {
values.add(String.valueOf(x));
}
}
} | repos\tutorials-master\core-java-modules\core-java-regex-3\src\main\java\com\baeldung\patternreuse\PatternPerformanceComparison.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class WebSocketConfiguration {
@Bean
@ConditionalOnMissingBean
GraphQlWebSocketHandler graphQlWebSocketHandler(WebGraphQlHandler webGraphQlHandler,
GraphQlProperties properties, ObjectProvider<ServerHttpMessageConvertersCustomizer> customizers) {
return new GraphQlWebSocketHandler(webGraphQlHandler, getJsonConverter(customizers),
properties.getWebsocket().getConnectionInitTimeout(), properties.getWebsocket().getKeepAlive());
}
private HttpMessageConverter<Object> getJsonConverter(
ObjectProvider<ServerHttpMessageConvertersCustomizer> customizers) {
ServerBuilder serverBuilder = HttpMessageConverters.forServer().registerDefaults();
customizers.forEach((customizer) -> customizer.customize(serverBuilder));
for (HttpMessageConverter<?> converter : serverBuilder.build()) {
if (canReadJsonMap(converter)) {
return asObjectHttpMessageConverter(converter);
}
}
throw new IllegalStateException("No JSON converter");
}
private boolean canReadJsonMap(HttpMessageConverter<?> candidate) {
return candidate.canRead(Map.class, MediaType.APPLICATION_JSON);
}
@SuppressWarnings("unchecked")
private HttpMessageConverter<Object> asObjectHttpMessageConverter(HttpMessageConverter<?> converter) {
return (HttpMessageConverter<Object>) converter;
} | @Bean
HandlerMapping graphQlWebSocketMapping(GraphQlWebSocketHandler handler, GraphQlProperties properties) {
String path = properties.getWebsocket().getPath();
Assert.state(path != null, "'path' must not be null");
logger.info(LogMessage.format("GraphQL endpoint WebSocket %s", path));
WebSocketHandlerMapping mapping = new WebSocketHandlerMapping();
mapping.setWebSocketUpgradeMatch(true);
mapping.setUrlMap(Collections.singletonMap(path,
handler.initWebSocketHttpRequestHandler(new DefaultHandshakeHandler())));
mapping.setOrder(-2); // Ahead of HTTP endpoint ("routerFunctionMapping" bean)
return mapping;
}
}
static class GraphiQlResourceHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphiql/index.html");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\servlet\GraphQlWebMvcAutoConfiguration.java | 2 |
请完成以下Java代码 | protected void installService(OperationContext context, ManagedProcessEngineMetadata processEngineConfiguration) {
MscManagedProcessEngineController service = new MscManagedProcessEngineController(processEngineConfiguration);
ServiceName serviceName = ServiceNames.forManagedProcessEngine(processEngineConfiguration.getEngineName());
ServiceBuilder<?> serviceBuilder = context.getServiceTarget().addService(serviceName);
service.initializeServiceBuilder(processEngineConfiguration, serviceBuilder, serviceName, processEngineConfiguration.getJobExecutorAcquisitionName());
serviceBuilder.setInstance(service);
serviceBuilder.install();
}
protected ManagedProcessEngineMetadata transformConfiguration(final OperationContext context, String engineName, final ModelNode model) throws OperationFailedException {
return new ManagedProcessEngineMetadata(
SubsystemAttributeDefinitons.DEFAULT.resolveModelAttribute(context, model).asBoolean(),
engineName,
SubsystemAttributeDefinitons.DATASOURCE.resolveModelAttribute(context, model).asString(),
SubsystemAttributeDefinitons.HISTORY_LEVEL.resolveModelAttribute(context, model).asString(),
SubsystemAttributeDefinitons.CONFIGURATION.resolveModelAttribute(context, model).asString(),
getProperties(SubsystemAttributeDefinitons.PROPERTIES.resolveModelAttribute(context, model)),
getPlugins(SubsystemAttributeDefinitons.PLUGINS.resolveModelAttribute(context, model))
);
}
protected List<ProcessEnginePluginXml> getPlugins(ModelNode plugins) {
List<ProcessEnginePluginXml> pluginConfigurations = new ArrayList<>();
if (plugins.isDefined()) {
for (final ModelNode plugin : plugins.asList()) {
ProcessEnginePluginXml processEnginePluginXml = new ProcessEnginePluginXml() {
@Override
public String getPluginClass() {
return plugin.get(Element.PLUGIN_CLASS.getLocalName()).asString();
}
@Override
public Map<String, String> getProperties() {
return ProcessEngineAdd.this.getProperties(plugin.get(Element.PROPERTIES.getLocalName()));
}
}; | pluginConfigurations.add(processEnginePluginXml);
}
}
return pluginConfigurations;
}
protected Map<String, String> getProperties(ModelNode properties) {
Map<String, String> propertyMap = new HashMap<>();
if (properties.isDefined()) {
for (Property property : properties.asPropertyList()) {
propertyMap.put(property.getName(), property.getValue().asString());
}
}
return propertyMap;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\extension\handler\ProcessEngineAdd.java | 1 |
请完成以下Java代码 | public List<Map<String, Object>> getRuleResults() {
return ruleResults;
}
public List<Object> getOutputValues(String outputName) {
List<Object> outputValues = new ArrayList<>();
for (Map<String, Object> ruleOutputValues : ruleResults) {
outputValues.add(ruleOutputValues.get(outputName));
}
return outputValues;
}
public Map<String, Object> getFirstRuleResult() {
if (ruleResults.size() > 0) {
return ruleResults.get(0); | } else {
return null;
}
}
public Map<String, Object> getSingleRuleResult() {
if (ruleResults.isEmpty()) {
return null;
} else if (ruleResults.size() > 1) {
throw new FlowableException("Decision has multiple results");
} else {
return getFirstRuleResult();
}
}
} | repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\DmnDecisionRuleResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void exportStockToShopware(@NonNull final Exchange exchange)
{
final ExportStockRouteContext exportStockRouteContext = exchange.getProperty(ROUTE_PROPERTY_EXPORT_STOCK_CONTEXT, ExportStockRouteContext.class);
final JsonStock jsonStock = exchange.getIn().getBody(JsonStock.class);
final ShopwareClient shopwareClient = exportStockRouteContext.getShopwareClient();
shopwareClient.exportStock(jsonStock, exportStockRouteContext.getJsonAvailableForSales().getProductIdentifier().getExternalReference());
}
private void createJsonStock(@NonNull final Exchange exchange)
{
final ExportStockRouteContext exportStockRouteContext = exchange.getProperty(ROUTE_PROPERTY_EXPORT_STOCK_CONTEXT, ExportStockRouteContext.class);
final BigDecimal stockBD = exportStockRouteContext.getJsonAvailableForSales()
.getStock()
.setScale(0, RoundingMode.CEILING);
final JsonStock jsonStock = JsonStock.builder()
.stock(stockBD.intValueExact())
.build();
exchange.getIn().setBody(jsonStock);
}
private void buildAndAttachRouteContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
if (request.getAdPInstanceId() != null)
{
exchange.getIn().setHeader(HEADER_PINSTANCE_ID, request.getAdPInstanceId().getValue());
processLogger.logMessage("Shopware6:ExportStock process started!" + Instant.now(), request.getAdPInstanceId().getValue());
} | final String clientId = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_ID);
final String clientSecret = request.getParameters().get(ExternalSystemConstants.PARAM_CLIENT_SECRET);
final String basePath = request.getParameters().get(ExternalSystemConstants.PARAM_BASE_PATH);
final PInstanceLogger pInstanceLogger = PInstanceLogger.builder()
.processLogger(processLogger)
.pInstanceId(request.getAdPInstanceId())
.build();
final ShopwareClient shopwareClient = ShopwareClient.of(clientId, clientSecret, basePath, pInstanceLogger);
final JsonAvailableForSales jsonAvailableForSales = getJsonAvailableForSales(request);
final ExportStockRouteContext exportStockRouteContext = ExportStockRouteContext.builder()
.shopwareClient(shopwareClient)
.jsonAvailableForSales(jsonAvailableForSales)
.build();
exchange.setProperty(ROUTE_PROPERTY_EXPORT_STOCK_CONTEXT, exportStockRouteContext);
}
@NonNull
private JsonAvailableForSales getJsonAvailableForSales(@NonNull final JsonExternalSystemRequest request)
{
try
{
return objectMapper.readValue(request.getParameters().get(ExternalSystemConstants.PARAM_JSON_AVAILABLE_FOR_SALES), JsonAvailableForSales.class);
}
catch (final IOException e)
{
throw new RuntimeException("Unable to deserialize JsonAvailableStock", e);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\stock\ExportStockRouteBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ApiAuditConfigRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, ApiAuditConfigsMap> cache = CCache.<Integer, ApiAuditConfigsMap>builder()
.tableName(I_API_Audit_Config.Table_Name)
.build();
public ImmutableList<ApiAuditConfig> getActiveConfigsByOrgId(@NonNull final OrgId orgId)
{
return getMap().getActiveConfigsByOrgId(orgId);
}
public ImmutableList<ApiAuditConfig> getAllConfigsByOrgId(@NonNull final OrgId orgId)
{
return queryBL.createQueryBuilder(I_API_Audit_Config.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_API_Audit_Config.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY)
.create()
.list()
.stream()
.map(ApiAuditConfigRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
}
@NonNull
public ApiAuditConfig getConfigById(@NonNull final ApiAuditConfigId id)
{
return getMap().getConfigById(id);
}
private ApiAuditConfigsMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private ApiAuditConfigsMap retrieveMap()
{
return ApiAuditConfigsMap.ofList(
queryBL.createQueryBuilder(I_API_Audit_Config.class)
.create()
.stream()
.map(ApiAuditConfigRepository::fromRecord)
.collect(ImmutableList.toImmutableList()));
}
@NonNull
private static ApiAuditConfig fromRecord(@NonNull final I_API_Audit_Config record)
{ | return ApiAuditConfig.builder()
.apiAuditConfigId(ApiAuditConfigId.ofRepoId(record.getAPI_Audit_Config_ID()))
.active(record.isActive())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.seqNo(record.getSeqNo())
.isBypassAudit(record.isBypassAudit())
.forceProcessedAsync(record.isForceProcessedAsync())
.keepRequestDays(record.getKeepRequestDays())
.keepRequestBodyDays(record.getKeepRequestBodyDays())
.keepResponseDays(record.getKeepResponseDays())
.keepResponseBodyDays(record.getKeepResponseBodyDays())
.keepErroredRequestDays(record.getKeepErroredRequestDays())
.method(HttpMethod.ofNullableCode(record.getMethod()))
.pathPrefix(record.getPathPrefix())
.notifyUserInCharge(NotificationTriggerType.ofNullableCode(record.getNotifyUserInCharge()))
.userGroupInChargeId(UserGroupId.ofRepoIdOrNull(record.getAD_UserGroup_InCharge_ID()))
.performAuditAsync(!record.isSynchronousAuditLoggingEnabled())
.wrapApiResponse(record.isWrapApiResponse())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\apirequest\config\ApiAuditConfigRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence maxOccurs="unbounded">
* <element ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}InvoiceFooter" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"invoiceFooter"
})
public static class InvoiceFooters {
@XmlElement(name = "InvoiceFooter")
protected List<InvoiceFooterType> invoiceFooter;
/**
* Gets the value of the invoiceFooter property.
*
* <p> | * This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the invoiceFooter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInvoiceFooter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link InvoiceFooterType }
*
*
*/
public List<InvoiceFooterType> getInvoiceFooter() {
if (invoiceFooter == null) {
invoiceFooter = new ArrayList<InvoiceFooterType>();
}
return this.invoiceFooter;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICExtensionType.java | 2 |
请完成以下Java代码 | private Set<String> sortedStrings(Collection<String> input) {
return sortedStrings(input, Function.identity());
}
private <S> Set<String> sortedStrings(Collection<S> input, Function<S, String> converter) {
TreeSet<String> results = new TreeSet<>();
for (S item : input) {
results.add(converter.apply(item));
}
return results;
}
private static final class Descriptor {
private final String propertyName; | private final @Nullable Origin origin;
private Descriptor(String propertyName, @Nullable Origin origin) {
this.propertyName = propertyName;
this.origin = origin;
}
static Descriptor get(PropertySource<?> source, String propertyName) {
Origin origin = OriginLookup.getOrigin(source, propertyName);
return new Descriptor(propertyName, origin);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java | 1 |
请完成以下Java代码 | public class QueryPropertyImpl implements QueryProperty {
private static final long serialVersionUID = 1L;
protected String name;
protected String function;
public QueryPropertyImpl(String name) {
this(name, null);
}
public QueryPropertyImpl(String name, String function) {
this.name = name;
this.function = function;
}
public String getName() {
return name;
}
public String getFunction() {
return function;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((function == null) ? 0 : function.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result; | }
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
QueryPropertyImpl other = (QueryPropertyImpl) obj;
if (function == null) {
if (other.function != null)
return false;
} else if (!function.equals(other.function))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String toString() {
return "QueryProperty["
+ "name=" + name
+ ", function=" + function
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\QueryPropertyImpl.java | 1 |
请完成以下Java代码 | public DeviceProfile findByName(TenantId tenantId, String profileName) {
return DaoUtil.getData(deviceProfileRepository.findByTenantIdAndName(tenantId.getId(), profileName));
}
@Override
public PageData<DeviceProfile> findAllWithImages(PageLink pageLink) {
return DaoUtil.toPageData(deviceProfileRepository.findAllByImageNotNull(DaoUtil.toPageable(pageLink)));
}
@Override
public List<EntityInfo> findTenantDeviceProfileNames(UUID tenantId, boolean activeOnly) {
return activeOnly ?
deviceProfileRepository.findActiveTenantDeviceProfileNames(tenantId) :
deviceProfileRepository.findAllTenantDeviceProfileNames(tenantId);
}
@Override
public List<DeviceProfileInfo> findDeviceProfilesByTenantIdAndIds(UUID tenantId, List<UUID> deviceProfileIds) {
return deviceProfileRepository.findDeviceProfileInfosByTenantIdAndIdIn(tenantId, deviceProfileIds);
}
@Override
public DeviceProfile findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(deviceProfileRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public DeviceProfile findByTenantIdAndName(UUID tenantId, String name) {
return DaoUtil.getData(deviceProfileRepository.findByTenantIdAndName(tenantId, name));
}
@Override
public PageData<DeviceProfile> findByTenantId(UUID tenantId, PageLink pageLink) {
return findDeviceProfiles(TenantId.fromUUID(tenantId), pageLink);
} | @Override
public DeviceProfileId getExternalIdByInternal(DeviceProfileId internalId) {
return Optional.ofNullable(deviceProfileRepository.getExternalIdById(internalId.getId()))
.map(DeviceProfileId::new).orElse(null);
}
@Override
public DeviceProfile findDefaultEntityByTenantId(UUID tenantId) {
return findDefaultDeviceProfile(TenantId.fromUUID(tenantId));
}
@Override
public List<DeviceProfileInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) {
return deviceProfileRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, PageRequest.of(0, limit));
}
@Override
public List<DeviceProfileInfo> findByImageLink(String imageLink, int limit) {
return deviceProfileRepository.findByImageLink(imageLink, PageRequest.of(0, limit));
}
@Override
public PageData<DeviceProfile> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findDeviceProfiles(tenantId, pageLink);
}
@Override
public List<DeviceProfileFields> findNextBatch(UUID id, int batchSize) {
return deviceProfileRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE_PROFILE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceProfileDao.java | 1 |
请完成以下Java代码 | abstract class VEditorAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
public VEditorAction(final String name, final KeyStroke accelerator)
{
super(name);
putValue(Action.ACCELERATOR_KEY, accelerator);
}
@Override
public abstract void actionPerformed(final ActionEvent e);
public final String getName()
{
final Object nameObj = getValue(Action.NAME);
return nameObj == null ? "" : nameObj.toString();
}
public final KeyStroke getAccelerator()
{
return (KeyStroke)getValue(ACCELERATOR_KEY);
}
/**
* Install the action and the key bindings to given component.
*
* @param comp
* @param inputMapCondition one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
*/
public final void installTo(final JComponent comp, final int inputMapCondition)
{
if (comp == null)
{ | return;
}
final String actionName = getName();
final ActionMap actionMap = comp.getActionMap();
actionMap.put(actionName, this);
final KeyStroke accelerator = getAccelerator();
if (accelerator != null)
{
final InputMap inputMap = comp.getInputMap(inputMapCondition);
inputMap.put(accelerator, actionName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorAction.java | 1 |
请完成以下Java代码 | public int getFact_Acct_UserChange_ID()
{
return get_ValueAsInt(COLUMNNAME_Fact_Acct_UserChange_ID);
}
@Override
public void setLocal_Currency_ID (final int Local_Currency_ID)
{
if (Local_Currency_ID < 1)
set_Value (COLUMNNAME_Local_Currency_ID, null);
else
set_Value (COLUMNNAME_Local_Currency_ID, Local_Currency_ID);
}
@Override
public int getLocal_Currency_ID()
{
return get_ValueAsInt(COLUMNNAME_Local_Currency_ID);
}
@Override
public void setMatchKey (final @Nullable java.lang.String MatchKey)
{
set_Value (COLUMNNAME_MatchKey, MatchKey);
}
@Override
public java.lang.String getMatchKey()
{
return get_ValueAsString(COLUMNNAME_MatchKey);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
/**
* PostingSign AD_Reference_ID=541699
* Reference name: PostingSign
*/
public static final int POSTINGSIGN_AD_Reference_ID=541699;
/** DR = D */
public static final String POSTINGSIGN_DR = "D"; | /** CR = C */
public static final String POSTINGSIGN_CR = "C";
@Override
public void setPostingSign (final java.lang.String PostingSign)
{
set_Value (COLUMNNAME_PostingSign, PostingSign);
}
@Override
public java.lang.String getPostingSign()
{
return get_ValueAsString(COLUMNNAME_PostingSign);
}
@Override
public void setUserElementString1 (final @Nullable java.lang.String UserElementString1)
{
set_Value (COLUMNNAME_UserElementString1, UserElementString1);
}
@Override
public java.lang.String getUserElementString1()
{
return get_ValueAsString(COLUMNNAME_UserElementString1);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_UserChange.java | 1 |
请完成以下Java代码 | public void setSalesPartnerCode (final @Nullable java.lang.String SalesPartnerCode)
{
set_Value (COLUMNNAME_SalesPartnerCode, SalesPartnerCode);
}
@Override
public java.lang.String getSalesPartnerCode()
{
return get_ValueAsString(COLUMNNAME_SalesPartnerCode);
}
@Override
public void setSalesRep_ID (final int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID);
}
@Override
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setSendEMail (final boolean SendEMail)
{
set_Value (COLUMNNAME_SendEMail, SendEMail);
}
@Override
public boolean isSendEMail()
{
return get_ValueAsBoolean(COLUMNNAME_SendEMail);
}
@Override
public void setTotalLines (final BigDecimal TotalLines)
{
set_ValueNoCheck (COLUMNNAME_TotalLines, TotalLines);
}
@Override
public BigDecimal getTotalLines()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TotalLines);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(final org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID); | }
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public void setUserFlag (final @Nullable java.lang.String UserFlag)
{
set_Value (COLUMNNAME_UserFlag, UserFlag);
}
@Override
public java.lang.String getUserFlag()
{
return get_ValueAsString(COLUMNNAME_UserFlag);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CustomersService {
private final DataSource dataSource;
public CustomersService(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Customer> customersEligibleForOffers() throws SQLException {
try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) {
ResultSet resultSet = stmt.executeQuery("SELECT * FROM customers");
List<Customer> customers = new ArrayList<>();
while (resultSet.next()) {
Customer customer = mapCustomer(resultSet);
if (customer.status() == Status.ACTIVE || customer.status() == Status.LOYAL) { | customers.add(customer);
}
}
return customers;
}
}
private Customer mapCustomer(ResultSet resultSet) throws SQLException {
return new Customer(
resultSet.getInt("id"),
resultSet.getString("name"),
Status.valueOf(resultSet.getString("status"))
);
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\jdbc\mocking\CustomersService.java | 2 |
请完成以下Java代码 | public ResponseEntity<QuoteDTO> updateQuote(@Valid @RequestBody QuoteDTO quoteDTO) throws URISyntaxException {
log.debug("REST request to update Quote : {}", quoteDTO);
if (quoteDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
QuoteDTO result = quoteService.save(quoteDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, quoteDTO.getId().toString()))
.body(result);
}
/**
* GET /quotes : get all the quotes.
*
* @param pageable the pagination information
* @param criteria the criterias which the requested entities should match
* @return the ResponseEntity with status 200 (OK) and the list of quotes in body
*/
@GetMapping("/quotes")
@Timed
public ResponseEntity<List<QuoteDTO>> getAllQuotes(QuoteCriteria criteria, Pageable pageable) {
log.debug("REST request to get Quotes by criteria: {}", criteria);
Page<QuoteDTO> page = quoteQueryService.findByCriteria(criteria, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/quotes");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /quotes/count : count all the quotes.
*
* @param criteria the criterias which the requested entities should match
* @return the ResponseEntity with status 200 (OK) and the count in body
*/
@GetMapping("/quotes/count")
@Timed
public ResponseEntity<Long> countQuotes (QuoteCriteria criteria) {
log.debug("REST request to count Quotes by criteria: {}", criteria);
return ResponseEntity.ok().body(quoteQueryService.countByCriteria(criteria));
}
/**
* GET /quotes/:id : get the "id" quote.
*
* @param id the id of the quoteDTO to retrieve | * @return the ResponseEntity with status 200 (OK) and with body the quoteDTO, or with status 404 (Not Found)
*/
@GetMapping("/quotes/{id}")
@Timed
public ResponseEntity<QuoteDTO> getQuote(@PathVariable Long id) {
log.debug("REST request to get Quote : {}", id);
Optional<QuoteDTO> quoteDTO = quoteService.findOne(id);
return ResponseUtil.wrapOrNotFound(quoteDTO);
}
/**
* DELETE /quotes/:id : delete the "id" quote.
*
* @param id the id of the quoteDTO to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/quotes/{id}")
@Timed
public ResponseEntity<Void> deleteQuote(@PathVariable Long id) {
log.debug("REST request to delete Quote : {}", id);
quoteService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\web\rest\QuoteResource.java | 1 |
请完成以下Java代码 | protected void addQty(final int qtyToAdd)
{
qty = qty.add(BigDecimal.valueOf(qtyToAdd));
}
protected void subtractQty(final int qtyToSubtract)
{
qty = qty.subtract(BigDecimal.valueOf(qtyToSubtract));
}
/**
*
* @return packing materials amount(qty)'s unit of measure
*/
public I_C_UOM getC_UOM()
{
return uom;
}
private int getC_UOM_ID()
{
final int uomId = uom == null ? -1 : uom.getC_UOM_ID();
return uomId > 0 ? uomId : -1;
}
public I_M_Locator getM_Locator()
{
return locator;
}
private int getM_Locator_ID()
{
final int locatorId = locator == null ? -1 : locator.getM_Locator_ID();
return locatorId > 0 ? locatorId : -1;
}
public I_M_Material_Tracking getM_MaterialTracking()
{
return materialTracking;
}
private int getM_MaterialTracking_ID()
{
final int materialTrackingId = materialTracking == null ? -1 : materialTracking.getM_Material_Tracking_ID();
return materialTrackingId > 0 ? materialTrackingId : -1;
}
protected void add(@NonNull final HUPackingMaterialDocumentLineCandidate candidateToAdd)
{
if (this == candidateToAdd)
{
throw new IllegalArgumentException("Cannot add to it self: " + candidateToAdd);
}
if (!Objects.equals(getProductId(), candidateToAdd.getProductId())
|| getC_UOM_ID() != candidateToAdd.getC_UOM_ID()
|| getM_Locator_ID() != candidateToAdd.getM_Locator_ID() | || getM_MaterialTracking_ID() != candidateToAdd.getM_MaterialTracking_ID())
{
throw new HUException("Candidates are not matching."
+ "\nthis: " + this
+ "\ncandidate to add: " + candidateToAdd);
}
qty = qty.add(candidateToAdd.qty);
// add sources; might be different
addSources(candidateToAdd.getSources());
}
public void addSourceIfNotNull(final IHUPackingMaterialCollectorSource huPackingMaterialCollectorSource)
{
if (huPackingMaterialCollectorSource != null)
{
sources.add(huPackingMaterialCollectorSource);
}
}
private void addSources(final Set<IHUPackingMaterialCollectorSource> huPackingMaterialCollectorSources)
{
if (!huPackingMaterialCollectorSources.isEmpty())
{
sources.addAll(huPackingMaterialCollectorSources);
}
}
public Set<IHUPackingMaterialCollectorSource> getSources()
{
return ImmutableSet.copyOf(sources);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialDocumentLineCandidate.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_ImpEx_Connector[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Beschreibung.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Konnektor.
@param ImpEx_Connector_ID Konnektor */
public void setImpEx_Connector_ID (int ImpEx_Connector_ID)
{
if (ImpEx_Connector_ID < 1)
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, Integer.valueOf(ImpEx_Connector_ID));
}
/** Get Konnektor.
@return Konnektor */
public int getImpEx_Connector_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_Connector_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public de.metas.impex.model.I_ImpEx_ConnectorType getImpEx_ConnectorType() throws RuntimeException | {
return (de.metas.impex.model.I_ImpEx_ConnectorType)MTable.get(getCtx(), de.metas.impex.model.I_ImpEx_ConnectorType.Table_Name)
.getPO(getImpEx_ConnectorType_ID(), get_TrxName()); }
/** Set Konnektor-Typ.
@param ImpEx_ConnectorType_ID Konnektor-Typ */
public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID)
{
if (ImpEx_ConnectorType_ID < 1)
set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, null);
else
set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID));
}
/** Get Konnektor-Typ.
@return Konnektor-Typ */
public int getImpEx_ConnectorType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_Connector.java | 1 |
请完成以下Java代码 | public CalculateTaxResult calculateTax(final I_C_Tax tax, final BigDecimal amount, final boolean taxIncluded, final int scale)
{
return TaxUtils.from(tax).calculateTax(amount, taxIncluded, scale);
}
public BigDecimal calculateTaxAmt(final I_C_Tax tax, final BigDecimal amount, final boolean taxIncluded, final int scale)
{
return calculateTax(tax, amount, taxIncluded, scale).getTaxAmount();
}
@Override
public BigDecimal calculateBaseAmt(@NonNull final I_C_Tax tax, @NonNull final BigDecimal amount, final boolean taxIncluded, final int scale)
{
return TaxUtils.from(tax).calculateBaseAmt(amount, taxIncluded, scale);
}
@Override
public void setupIfIsWholeTax(final I_C_Tax tax)
{
if (!tax.isWholeTax())
{
return;
}
tax.setRate(BigDecimal.valueOf(100));
tax.setIsTaxExempt(false);
tax.setIsDocumentLevel(true);
// tax.setIsSalesTax(false); // does not matter
}
@Override
public TaxCategoryId retrieveRegularTaxCategoryId()
{
final TaxCategoryId taxCategoryId = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_TaxCategory.class)
.addEqualsFilter(I_C_TaxCategory.COLUMN_VATType, X_C_TaxCategory.VATTYPE_RegularVAT)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.orderBy(I_C_TaxCategory.COLUMN_Name)
.create()
.firstId(TaxCategoryId::ofRepoIdOrNull); | if (taxCategoryId == null)
{
throw new AdempiereException("No tax category found for Regular VATType");
}
return taxCategoryId;
}
@NonNull
public Optional<TaxCategoryId> getTaxCategoryIdByInternalName(@NonNull final String internalName)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_TaxCategory.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_TaxCategory.COLUMNNAME_InternalName, internalName)
.create()
.firstOnlyOptional(I_C_TaxCategory.class)
.map(I_C_TaxCategory::getC_TaxCategory_ID)
.map(TaxCategoryId::ofRepoId);
}
@Override
public Tax getDefaultTax(final TaxCategoryId taxCategoryId)
{
return taxDAO.getDefaultTax(taxCategoryId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\tax\api\impl\TaxBL.java | 1 |
请完成以下Java代码 | protected void configure() {
try {
bind(AccountService.class).to(AccountServiceImpl.class);
bind(Person.class).toConstructor(Person.class.getConstructor());
// bind(Person.class).toProvider(new Provider<Person>() {
// public Person get() {
// Person p = new Person();
// return p;
// }
// });
bind(Foo.class).toProvider(new Provider<Foo>() {
public Foo get() {
return new Foo();
}
});
bind(PersonDao.class).to(PersonDaoImpl.class);
} catch (NoSuchMethodException e) { | // TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Provides
public BookService bookServiceGenerator() {
return new BookServiceImpl();
}
} | repos\tutorials-master\di-modules\guice\src\main\java\com\baeldung\guice\modules\GuiceModule.java | 1 |
请完成以下Java代码 | public void updateProductDescriptionFromProductBOMIfConfigured(final I_C_OrderLine orderLine)
{
orderLineBL.updateProductDescriptionFromProductBOMIfConfigured(orderLine);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID })
public void updateProductDocumentNote(final I_C_OrderLine orderLine)
{
orderLineBL.updateProductDocumentNote(orderLine);
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsGroupCompensationLine, I_C_OrderLine.COLUMNNAME_C_Order_CompensationGroup_ID })
public void renumberLinesIfCompensationGroupChanged(@NonNull final I_C_OrderLine orderLine)
{
if (!OrderGroupCompensationUtils.isInGroup(orderLine))
{
return;
}
groupChangesHandler.renumberOrderLinesForOrderId(OrderId.ofRepoId(orderLine.getC_Order_ID()));
}
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE },
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_M_Product_ID, I_C_OrderLine.COLUMNNAME_QtyOrdered })
public void updateWeight(@NonNull final I_C_OrderLine orderLine)
{
final I_C_Order order = orderBL.getById(OrderId.ofRepoId(orderLine.getC_Order_ID()));
orderBL.setWeightFromLines(order);
saveRecord(order);
} | @ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge, I_C_OrderLine.COLUMNNAME_PriceActual, I_C_OrderLine.COLUMNNAME_PriceEntered })
public void updatePriceToZero(final I_C_OrderLine orderLine)
{
if (orderLine.isWithoutCharge())
{
orderLine.setPriceActual(BigDecimal.ZERO);
orderLine.setPriceEntered(BigDecimal.ZERO);
orderLine.setIsManualPrice(true);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_OrderLine.COLUMNNAME_IsWithoutCharge})
public void updatePriceToStd(final I_C_OrderLine orderLine)
{
if (!orderLine.isWithoutCharge())
{
orderLine.setPriceActual(orderLine.getPriceStd());
orderLine.setPriceEntered(orderLine.getPriceStd());
orderLine.setIsManualPrice(false);
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
orderLineBL.updateLineNetAmtFromQtyEntered(orderLine);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\model\interceptor\C_OrderLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setProcessInstanceVariables(List<QueryVariable> processInstanceVariables) {
this.processInstanceVariables = processInstanceVariables;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessBusinessKey() {
return processBusinessKey;
}
public void setProcessBusinessKey(String processBusinessKey) {
this.processBusinessKey = processBusinessKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getSignalEventSubscriptionName() {
return signalEventSubscriptionName;
}
public void setSignalEventSubscriptionName(String signalEventSubscriptionName) {
this.signalEventSubscriptionName = signalEventSubscriptionName;
}
public String getMessageEventSubscriptionName() {
return messageEventSubscriptionName;
}
public void setMessageEventSubscriptionName(String messageEventSubscriptionName) {
this.messageEventSubscriptionName = messageEventSubscriptionName;
}
public String getActivityId() {
return activityId;
} | public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
}
public Boolean getWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public Set<String> getProcessInstanceIds() {
return processInstanceIds;
}
public void setProcessInstanceIds(Set<String> processInstanceIds) {
this.processInstanceIds = processInstanceIds;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionQueryRequest.java | 2 |
请完成以下Java代码 | public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Type getType() {
return type;
}
public void setType(Type type) { | this.type = type;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\enums\Article.java | 1 |
请完成以下Java代码 | public UserQuery userEmail(String email) {
this.email = email;
return this;
}
public UserQuery userEmailLike(String emailLike) {
ensureNotNull("Provided emailLike", emailLike);
this.emailLike = emailLike;
return this;
}
public UserQuery memberOfGroup(String groupId) {
ensureNotNull("Provided groupId", groupId);
this.groupId = groupId;
return this;
}
public UserQuery potentialStarter(String procDefId) {
ensureNotNull("Provided processDefinitionId", procDefId);
this.procDefId = procDefId;
return this;
}
public UserQuery memberOfTenant(String tenantId) {
ensureNotNull("Provided tenantId", tenantId);
this.tenantId = tenantId;
return this;
}
//sorting //////////////////////////////////////////////////////////
public UserQuery orderByUserId() {
return orderBy(UserQueryProperty.USER_ID);
}
public UserQuery orderByUserEmail() {
return orderBy(UserQueryProperty.EMAIL);
}
public UserQuery orderByUserFirstName() {
return orderBy(UserQueryProperty.FIRST_NAME);
} | public UserQuery orderByUserLastName() {
return orderBy(UserQueryProperty.LAST_NAME);
}
//getters //////////////////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId;
}
public String getTenantId() {
return tenantId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\UserQueryImpl.java | 1 |
请完成以下Java代码 | private final ICopyPasteSupportEditor getCopyPasteSupport()
{
if (_copyPasteSupport == null)
{
_copyPasteSupport = createCopyPasteSupport(getEditor());
if (!NullCopyPasteSupportEditor.isNull(_copyPasteSupport))
{
// Setup the copy/paste action if needed
CopyPasteAction.getCreateAction(_copyPasteSupport, getActionType());
}
}
return _copyPasteSupport;
}
private static ICopyPasteSupportEditor createCopyPasteSupport(final VEditor editor)
{
if (editor == null)
{
return NullCopyPasteSupportEditor.instance;
}
//
// Check if editor implements our interface
if (editor instanceof ICopyPasteSupportEditor)
{
return (ICopyPasteSupportEditor)editor;
}
//
// Check if editor is aware of ICopyPasteSupport
if (editor instanceof ICopyPasteSupportEditorAware)
{
final ICopyPasteSupportEditorAware copyPasteSupportAware = (ICopyPasteSupportEditorAware)editor;
final ICopyPasteSupportEditor copyPasteSupport = copyPasteSupportAware.getCopyPasteSupport();
return copyPasteSupport == null ? NullCopyPasteSupportEditor.instance : copyPasteSupport;
}
return NullCopyPasteSupportEditor.instance;
}
@Override
public String getName()
{
return getActionType().getAD_Message();
}
@Override
public String getIcon()
{
return null;
}
@Override
public KeyStroke getKeyStroke() | {
return getActionType().getKeyStroke();
}
@Override
public boolean isAvailable()
{
return !NullCopyPasteSupportEditor.isNull(getCopyPasteSupport());
}
@Override
public boolean isRunnable()
{
return getCopyPasteSupport().isCopyPasteActionAllowed(getActionType());
}
@Override
public boolean isHideWhenNotRunnable()
{
return false; // just gray it out
}
@Override
public void run()
{
getCopyPasteSupport().executeCopyPasteAction(getActionType());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\CopyPasteContextMenuAction.java | 1 |
请完成以下Java代码 | private static boolean isNotPkcs8Wrapper(String line) {
return !PKCS8_PEM_HEADER.equals(line) && !PKCS8_PEM_FOOTER.equals(line);
}
private static class X509PemDecoder implements Converter<List<String>, RSAPublicKey> {
private final KeyFactory keyFactory;
X509PemDecoder(KeyFactory keyFactory) {
this.keyFactory = keyFactory;
}
@Override
public @NonNull RSAPublicKey convert(List<String> lines) {
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (isNotX509PemWrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
try {
return (RSAPublicKey) this.keyFactory.generatePublic(new X509EncodedKeySpec(x509));
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private boolean isNotX509PemWrapper(String line) {
return !X509_PEM_HEADER.equals(line) && !X509_PEM_FOOTER.equals(line);
}
}
private static class X509CertificateDecoder implements Converter<List<String>, RSAPublicKey> {
private final CertificateFactory certificateFactory;
X509CertificateDecoder(CertificateFactory certificateFactory) {
this.certificateFactory = certificateFactory;
}
@Override | public @NonNull RSAPublicKey convert(List<String> lines) {
StringBuilder base64Encoded = new StringBuilder();
for (String line : lines) {
if (isNotX509CertificateWrapper(line)) {
base64Encoded.append(line);
}
}
byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString());
try (InputStream x509CertStream = new ByteArrayInputStream(x509)) {
X509Certificate certificate = (X509Certificate) this.certificateFactory
.generateCertificate(x509CertStream);
return (RSAPublicKey) certificate.getPublicKey();
}
catch (CertificateException | IOException ex) {
throw new IllegalArgumentException(ex);
}
}
private boolean isNotX509CertificateWrapper(String line) {
return !X509_CERT_HEADER.equals(line) && !X509_CERT_FOOTER.equals(line);
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\converter\RsaKeyConverters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_BPartner_Location
{
@Init
public void setupCallouts()
{
final IProgramaticCalloutProvider calloutProvider = Services.get(IProgramaticCalloutProvider.class);
calloutProvider.registerAnnotatedCallout(new de.metas.contracts.bpartner.interceptor.C_BPartner_Location());
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE,
ifColumnsChanged = { I_C_BPartner_Location.COLUMNNAME_Previous_ID })
public void updateNextLocation(final I_C_BPartner_Location bpLocation)
{
if (bpLocation.getPrevious_ID() > 0)
{
final BPartnerLocationId oldBPLocationId = BPartnerLocationId.ofRepoId(bpLocation.getC_BPartner_ID(), bpLocation.getPrevious_ID());
final BPartnerLocationId newBPLocationId = BPartnerLocationId.ofRepoId(bpLocation.getC_BPartner_ID(), bpLocation.getC_BPartner_Location_ID());
BPartnerLocationReplaceCommand.builder()
.oldBPLocationId(oldBPLocationId)
.newBPLocationId(newBPLocationId)
.newLocation(bpLocation)
.saveNewLocation(false) // because it will be saved after validator is triggered
.build()
.execute();
}
} | /**
* Prevents that a (the preceeding) location is terminated in the past.
* This is done by preventing that the current location's validFrom is set int he past.
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_C_BPartner_Location.COLUMNNAME_ValidFrom })
@CalloutMethod(columnNames = { I_C_BPartner_Location.COLUMNNAME_ValidFrom })
public void noTerminationInPast(final I_C_BPartner_Location bpLocation)
{
final Timestamp validFrom = bpLocation.getValidFrom();
if (validFrom != null && validFrom.before(Env.getDate()))
{
throw new AdempiereException("@AddressTerminatedInThePast@")
.appendParametersToMessage()
.setParameter("C_BPartner_Location.ValidFrom", validFrom)
.setParameter("Env.getDate()",Env.getDate())
.setParameter("C_BPartner_Location", bpLocation);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\interceptor\C_BPartner_Location.java | 2 |
请完成以下Java代码 | public boolean isEmpty()
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events;
return events == null || events.isEmpty();
}
private JSONDocumentChangedWebSocketEvent getCreateEvent(@NonNull final WindowId windowId, @NonNull final DocumentId documentId)
{
final EventKey key = new EventKey(windowId, documentId);
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events;
if (events == null)
{
throw new AdempiereException("already closed: " + this);
}
return events.computeIfAbsent(key, this::createEvent);
}
private JSONDocumentChangedWebSocketEvent createEvent(final EventKey key)
{
return JSONDocumentChangedWebSocketEvent.rootDocument(key.getWindowId(), key.getDocumentId());
}
public void staleRootDocument(final WindowId windowId, final DocumentId documentId)
{
staleRootDocument(windowId, documentId, false);
}
public void staleRootDocument(final WindowId windowId, final DocumentId documentId, final boolean markActiveTabStaled)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.markRootDocumentAsStaled();
if (markActiveTabStaled)
{
event.markActiveTabStaled();
}
}
public void staleTabs(final WindowId windowId, final DocumentId documentId, final Set<DetailId> tabIds)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.staleTabs(tabIds);
}
public void staleIncludedDocuments(final WindowId windowId, final DocumentId documentId, final DetailId tabId, final DocumentIdsSelection rowIds)
{
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.staleIncludedRows(tabId, rowIds);
}
public void mergeFrom(final WindowId windowId, final DocumentId documentId, final JSONIncludedTabInfo tabInfo) | {
final JSONDocumentChangedWebSocketEvent event = getCreateEvent(windowId, documentId);
event.addIncludedTabInfo(tabInfo);
}
public void mergeFrom(final JSONDocumentChangedWebSocketEventCollector from)
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> fromEvents = from._events;
if (fromEvents == null || fromEvents.isEmpty())
{
return;
}
fromEvents.forEach(this::mergeFrom);
}
private void mergeFrom(final EventKey key, final JSONDocumentChangedWebSocketEvent from)
{
final LinkedHashMap<EventKey, JSONDocumentChangedWebSocketEvent> events = this._events;
if (events == null)
{
throw new AdempiereException("already closed: " + this);
}
events.compute(key, (k, existingEvent) -> {
if (existingEvent == null)
{
return from.copy();
}
else
{
existingEvent.mergeFrom(from);
return existingEvent;
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEventCollector.java | 1 |
请完成以下Java代码 | protected boolean removeListenerEntry(final int workpackageId, final IQueueProcessorListener callback)
{
listenersLock.lock();
try
{
final List<ListenerEntry> entries = _listeners.get(workpackageId);
if (entries == null)
{
return false;
}
boolean removed = false;
for (final Iterator<ListenerEntry> it = entries.iterator(); it.hasNext();)
{
final ListenerEntry entry = it.next();
if (Util.same(entry.getListener(), callback))
{
it.remove();
removed = true;
}
}
if (entries.isEmpty())
{
_listeners.remove(workpackageId);
}
return removed;
}
finally
{
listenersLock.unlock();
}
}
@Override
public void fireWorkpackageProcessed(final I_C_Queue_WorkPackage workpackage, final IWorkpackageProcessor workpackageProcessor)
{
final int workpackageId = workpackage.getC_Queue_WorkPackage_ID();
final List<ListenerEntry> entries = getAndRemoveListenerEntries(workpackageId);
if (entries == null)
{
return;
}
for (final ListenerEntry entry : entries)
{
final IQueueProcessorListener listener = entry.getListener(); | try
{
listener.onWorkpackageProcessed(workpackage, workpackageProcessor);
}
catch (final Exception e)
{
logger.error("Error while executing " + listener + " for " + workpackage + " [SKIP]", e);
// NOTE: we are not throwing the error because there is not much to handle it, everything was consumed before
}
}
}
@Override
public void registerListener(@NonNull final IQueueProcessorListener listener, final int workpackageId)
{
Check.assume(workpackageId > 0, "workpackageId > 0");
// If it's null then don't register it
if (listener == NullQueueProcessorListener.instance)
{
return;
}
final ListenerEntry entry = new ListenerEntry(listener, workpackageId);
addListenerEntry(workpackageId, entry);
}
@Override
public boolean unregisterListener(final IQueueProcessorListener callback, final int workpackageId)
{
// If it's null then don't unregister it because it was never registered
if (callback == NullQueueProcessorListener.instance)
{
return false;
}
return removeListenerEntry(workpackageId, callback);
}
@Override
public boolean unregisterListeners(final int workpackageId)
{
return removeListenerEntry(workpackageId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\DefaultQueueProcessorEventDispatcher.java | 1 |
请完成以下Java代码 | private QuickInputDescriptor createQuickInputDescriptorOrNull(final QuickInputDescriptorKey key)
{
final IQuickInputDescriptorFactory quickInputDescriptorFactory = getQuickInputDescriptorFactory(key);
if (quickInputDescriptorFactory == null)
{
return null;
}
return quickInputDescriptorFactory.createQuickInputDescriptor(
key.getDocumentType(),
key.getDocumentTypeId(),
key.getIncludedTabId(),
key.getSoTrx());
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final QuickInputDescriptorKey key)
{
return getQuickInputDescriptorFactory(
//
// factory for included document:
IQuickInputDescriptorFactory.MatchingKey.includedDocument(
key.getDocumentType(),
key.getDocumentTypeId(),
key.getIncludedTableName().orElse(null)),
//
// factory for table:
IQuickInputDescriptorFactory.MatchingKey.ofTableName(key.getIncludedTableName().orElse(null)));
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final IQuickInputDescriptorFactory.MatchingKey... matchingKeys)
{
for (final IQuickInputDescriptorFactory.MatchingKey matchingKey : matchingKeys)
{
final IQuickInputDescriptorFactory factory = getQuickInputDescriptorFactory(matchingKey);
if (factory != null)
{
return factory;
}
} | return null;
}
private IQuickInputDescriptorFactory getQuickInputDescriptorFactory(final IQuickInputDescriptorFactory.MatchingKey matchingKey)
{
final ImmutableList<IQuickInputDescriptorFactory> matchingFactories = factories.get(matchingKey);
if (matchingFactories.isEmpty())
{
return null;
}
if (matchingFactories.size() > 1)
{
logger.warn("More than one factory found for {}. Using the first one.", matchingFactories);
}
return matchingFactories.get(0);
}
@lombok.Builder
@lombok.Value
private static class QuickInputDescriptorKey
{
@NonNull DocumentType documentType;
@NonNull DocumentId documentTypeId;
@NonNull Optional<String> includedTableName;
@NonNull DetailId includedTabId;
@NonNull Optional<SOTrx> soTrx;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputDescriptorFactoryService.java | 1 |
请完成以下Java代码 | public AbstractEngineConfiguration setCustomPreDeployers(List<EngineDeployer> customPreDeployers) {
this.customPreDeployers = customPreDeployers;
return this;
}
public List<EngineDeployer> getCustomPostDeployers() {
return customPostDeployers;
}
public AbstractEngineConfiguration setCustomPostDeployers(List<EngineDeployer> customPostDeployers) {
this.customPostDeployers = customPostDeployers;
return this;
}
public boolean isEnableConfiguratorServiceLoader() {
return enableConfiguratorServiceLoader;
}
public AbstractEngineConfiguration setEnableConfiguratorServiceLoader(boolean enableConfiguratorServiceLoader) {
this.enableConfiguratorServiceLoader = enableConfiguratorServiceLoader;
return this;
}
public List<EngineConfigurator> getConfigurators() {
return configurators;
}
public AbstractEngineConfiguration addConfigurator(EngineConfigurator configurator) {
if (configurators == null) {
configurators = new ArrayList<>();
}
configurators.add(configurator);
return this;
}
/**
* @return All {@link EngineConfigurator} instances. Will only contain values after init of the engine.
* Use the {@link #getConfigurators()} or {@link #addConfigurator(EngineConfigurator)} methods otherwise.
*/
public List<EngineConfigurator> getAllConfigurators() {
return allConfigurators;
}
public AbstractEngineConfiguration setConfigurators(List<EngineConfigurator> configurators) {
this.configurators = configurators;
return this;
}
public EngineConfigurator getIdmEngineConfigurator() {
return idmEngineConfigurator; | }
public AbstractEngineConfiguration setIdmEngineConfigurator(EngineConfigurator idmEngineConfigurator) {
this.idmEngineConfigurator = idmEngineConfigurator;
return this;
}
public EngineConfigurator getEventRegistryConfigurator() {
return eventRegistryConfigurator;
}
public AbstractEngineConfiguration setEventRegistryConfigurator(EngineConfigurator eventRegistryConfigurator) {
this.eventRegistryConfigurator = eventRegistryConfigurator;
return this;
}
public AbstractEngineConfiguration setForceCloseMybatisConnectionPool(boolean forceCloseMybatisConnectionPool) {
this.forceCloseMybatisConnectionPool = forceCloseMybatisConnectionPool;
return this;
}
public boolean isForceCloseMybatisConnectionPool() {
return forceCloseMybatisConnectionPool;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HistoryJobQuery jobTenantIdLike(String tenantIdLike) {
if (tenantIdLike == null) {
throw new FlowableIllegalArgumentException("Provided tenant id is null");
}
this.tenantIdLike = tenantIdLike;
return this;
}
@Override
public HistoryJobQuery jobWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public HistoryJobQuery lockOwner(String lockOwner) {
this.lockOwner = lockOwner;
return this;
}
@Override
public HistoryJobQuery locked() {
this.onlyLocked = true;
return this;
}
@Override
public HistoryJobQuery unlocked() {
this.onlyUnlocked = true;
return this;
}
@Override
public HistoryJobQuery withoutScopeType() {
this.withoutScopeType = true;
return this;
}
// sorting //////////////////////////////////////////
@Override
public HistoryJobQuery orderByJobId() {
return orderBy(JobQueryProperty.JOB_ID);
}
@Override
public HistoryJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
@Override
public HistoryJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobCountByQueryCriteria(this);
}
@Override
public List<HistoryJob> executeList(CommandContext commandContext) {
return jobServiceConfiguration.getHistoryJobEntityManager().findHistoryJobsByQueryCriteria(this);
}
// getters //////////////////////////////////////////
public String getHandlerType() {
return this.handlerType;
}
public Collection<String> getHandlerTypes() {
return handlerTypes;
}
public Date getNow() {
return jobServiceConfiguration.getClock().getCurrentTime();
} | public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getLockOwner() {
return lockOwner;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\HistoryJobQueryImpl.java | 2 |
请完成以下Java代码 | public static final class DocumentFilterBuilder
{
public DocumentFilterBuilder setFilterId(final String filterId)
{
return filterId(filterId);
}
public DocumentFilterBuilder setCaption(@NonNull final ITranslatableString caption)
{
return caption(caption);
}
public DocumentFilterBuilder setCaption(@NonNull final String caption)
{
return caption(TranslatableStrings.constant(caption));
}
public DocumentFilterBuilder setFacetFilter(final boolean facetFilter)
{
return facetFilter(facetFilter);
}
public boolean hasParameters()
{ | return !Check.isEmpty(parameters)
|| !Check.isEmpty(internalParameterNames);
}
public DocumentFilterBuilder setParameters(@NonNull final List<DocumentFilterParam> parameters)
{
return parameters(parameters);
}
public DocumentFilterBuilder addParameter(@NonNull final DocumentFilterParam parameter)
{
return parameter(parameter);
}
public DocumentFilterBuilder addInternalParameter(@NonNull final DocumentFilterParam parameter)
{
parameter(parameter);
internalParameterName(parameter.getFieldName());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilter.java | 1 |
请完成以下Java代码 | protected DecisionDefinition getDecisionDefinition(CommandContext commandContext) {
DeploymentCache deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentCache();
if (decisionDefinitionId != null) {
return findById(deploymentCache);
} else {
return findByKey(deploymentCache);
}
}
protected DecisionDefinition findById(DeploymentCache deploymentCache) {
return deploymentCache.findDeployedDecisionDefinitionById(decisionDefinitionId);
}
protected DecisionDefinition findByKey(DeploymentCache deploymentCache) {
DecisionDefinition decisionDefinition = null;
if (version == null && !isTenandIdSet) {
decisionDefinition = deploymentCache.findDeployedLatestDecisionDefinitionByKey(decisionDefinitionKey); | }
else if (version == null && isTenandIdSet) {
decisionDefinition = deploymentCache.findDeployedLatestDecisionDefinitionByKeyAndTenantId(decisionDefinitionKey, decisionDefinitionTenantId);
}
else if (version != null && !isTenandIdSet) {
decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByKeyAndVersion(decisionDefinitionKey, version);
}
else if (version != null && isTenandIdSet) {
decisionDefinition = deploymentCache.findDeployedDecisionDefinitionByKeyVersionAndTenantId(decisionDefinitionKey, version, decisionDefinitionTenantId);
}
return decisionDefinition;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\cmd\EvaluateDecisionTableCmd.java | 1 |
请完成以下Java代码 | public List<HistoricVariableUpdate> execute(CommandContext commandContext) {
List<HistoricVariableUpdate> historicVariableUpdates =
commandContext.getOptimizeManager().getHistoricVariableUpdates(occurredAfter, occurredAt, maxResults);
fetchVariableValues(historicVariableUpdates, commandContext);
return historicVariableUpdates;
}
private void fetchVariableValues(List<HistoricVariableUpdate> historicVariableUpdates,
CommandContext commandContext) {
if (!CollectionUtil.isEmpty(historicVariableUpdates)) {
List<String> byteArrayIds = getByteArrayIds(historicVariableUpdates);
if (!byteArrayIds.isEmpty()) {
// pre-fetch all byte arrays into dbEntityCache to avoid (n+1) number of queries
commandContext.getOptimizeManager().fetchHistoricVariableUpdateByteArrays(byteArrayIds);
}
resolveTypedValues(historicVariableUpdates);
}
}
protected boolean shouldFetchValue(HistoricDetailVariableInstanceUpdateEntity entity) {
final ValueType entityType = entity.getSerializer().getType();
// do no fetch values for byte arrays/blob variables (e.g. files or bytes)
return !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entityType.getName())
// nor object values unless enabled
&& (!ValueType.OBJECT.equals(entityType) || !excludeObjectValues);
}
protected boolean isHistoricDetailVariableInstanceUpdateEntity(HistoricVariableUpdate variableUpdate) {
return variableUpdate instanceof HistoricDetailVariableInstanceUpdateEntity;
}
protected List<String> getByteArrayIds(List<HistoricVariableUpdate> variableUpdates) {
List<String> byteArrayIds = new ArrayList<>();
for (HistoricVariableUpdate variableUpdate : variableUpdates) {
if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) { | HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate;
if (shouldFetchValue(entity)) {
String byteArrayId = entity.getByteArrayValueId();
if (byteArrayId != null) {
byteArrayIds.add(byteArrayId);
}
}
}
}
return byteArrayIds;
}
protected void resolveTypedValues(List<HistoricVariableUpdate> variableUpdates) {
for (HistoricVariableUpdate variableUpdate : variableUpdates) {
if (isHistoricDetailVariableInstanceUpdateEntity(variableUpdate)) {
HistoricDetailVariableInstanceUpdateEntity entity = (HistoricDetailVariableInstanceUpdateEntity) variableUpdate;
if (shouldFetchValue(entity)) {
try {
entity.getTypedValue(false);
} catch (Exception t) {
// do not fail if one of the variables fails to load
LOG.exceptionWhileGettingValueForVariable(t);
}
}
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\optimize\OptimizeHistoricVariableUpdateQueryCmd.java | 1 |
请完成以下Java代码 | private final ITrxManager getTrxManager()
{
final ITrxManager trxManager = trxManagerRef.get();
if (trxManager == null)
{
throw new AdempiereException("TrxManager service expired");
}
return trxManager;
}
@Override
public final String getJMXName()
{
return jmxName;
}
@Override
public void setDebugTrxCloseStacktrace(boolean debugTrxCloseStacktrace)
{
getTrxManager().setDebugTrxCloseStacktrace(debugTrxCloseStacktrace);
}
@Override
public boolean isDebugTrxCloseStacktrace()
{
return getTrxManager().isDebugTrxCloseStacktrace();
}
@Override
public void setDebugTrxCreateStacktrace(boolean debugTrxCreateStacktrace)
{
getTrxManager().setDebugTrxCreateStacktrace(debugTrxCreateStacktrace);
}
@Override
public boolean isDebugTrxCreateStacktrace()
{
return getTrxManager().isDebugTrxCreateStacktrace();
}
@Override
public void setDebugClosedTransactions(boolean enabled)
{
getTrxManager().setDebugClosedTransactions(enabled);
}
@Override
public boolean isDebugClosedTransactions()
{
return getTrxManager().isDebugClosedTransactions();
}
@Override
public String[] getActiveTransactionInfos()
{
final List<ITrx> trxs = getTrxManager().getActiveTransactionsList();
return toStringArray(trxs);
}
@Override
public String[] getDebugClosedTransactionInfos()
{
final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions();
return toStringArray(trxs);
}
private final String[] toStringArray(final List<ITrx> trxs) | {
if (trxs == null || trxs.isEmpty())
{
return new String[] {};
}
final String[] arr = new String[trxs.size()];
for (int i = 0; i < trxs.size(); i++)
{
final ITrx trx = trxs.get(0);
if (trx == null)
{
arr[i] = "null";
}
else
{
arr[i] = trx.toString();
}
}
return arr;
}
@Override
public void rollbackAndCloseActiveTrx(final String trxName)
{
final ITrxManager trxManager = getTrxManager();
if (trxManager.isNull(trxName))
{
throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName);
}
final ITrx trx = trxManager.getTrx(trxName);
if (trxManager.isNull(trx))
{
// shall not happen because getTrx is already throwning an exception
throw new IllegalArgumentException("No transaction was found for: " + trxName);
}
boolean rollbackOk = false;
try
{
rollbackOk = trx.rollback(true);
}
catch (SQLException e)
{
throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e);
}
if (!rollbackOk)
{
throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason");
}
}
@Override
public void setDebugConnectionBackendId(boolean debugConnectionBackendId)
{
getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId);
}
@Override
public boolean isDebugConnectionBackendId()
{
return getTrxManager().isDebugConnectionBackendId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java | 1 |
请完成以下Java代码 | private JsonPurchaseCandidate.JsonPurchaseCandidateBuilder preparePurchaseCandidateStatus(@NonNull final PurchaseCandidate candidate)
{
return JsonPurchaseCandidate.builder()
.externalSystemCode(poJsonConverters.getExternalSystemTypeById(candidate))
.externalHeaderId(JsonExternalIds.ofOrNull(candidate.getExternalHeaderId()))
.externalLineId(JsonExternalIds.ofOrNull(candidate.getExternalLineId()))
.purchaseDateOrdered(candidate.getPurchaseDateOrdered())
.purchaseDatePromised(candidate.getPurchaseDatePromised())
.metasfreshId(JsonMetasfreshId.of(candidate.getId().getRepoId()))
.externalPurchaseOrderUrl(candidate.getExternalPurchaseOrderUrl())
.processed(candidate.isProcessed());
}
private JsonPurchaseOrder toJsonOrder(@NonNull final I_C_Order order)
{
final boolean hasArchive = hasArchive(order);
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())); | return JsonPurchaseOrder.builder()
.dateOrdered(TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone))
.datePromised(TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone))
.docStatus(order.getDocStatus())
.documentNo(order.getDocumentNo())
.metasfreshId(JsonMetasfreshId.of(order.getC_Order_ID()))
.pdfAvailable(hasArchive)
.build();
}
private boolean hasArchive(final I_C_Order order)
{
return archiveBL.getLastArchive(TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID())).isPresent();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\PurchaseCandidatesStatusService.java | 1 |
请完成以下Java代码 | public PartyIdentification43 getMsgRcpt() {
return msgRcpt;
}
/**
* Sets the value of the msgRcpt property.
*
* @param value
* allowed object is
* {@link PartyIdentification43 }
*
*/
public void setMsgRcpt(PartyIdentification43 value) {
this.msgRcpt = value;
}
/**
* Gets the value of the msgPgntn property.
*
* @return
* possible object is
* {@link Pagination }
*
*/
public Pagination getMsgPgntn() {
return msgPgntn;
}
/**
* Sets the value of the msgPgntn property.
*
* @param value
* allowed object is
* {@link Pagination }
*
*/
public void setMsgPgntn(Pagination value) {
this.msgPgntn = value;
}
/**
* Gets the value of the orgnlBizQry property.
*
* @return
* possible object is
* {@link OriginalBusinessQuery1 }
*
*/
public OriginalBusinessQuery1 getOrgnlBizQry() {
return orgnlBizQry;
}
/**
* Sets the value of the orgnlBizQry property.
*
* @param value
* allowed object is
* {@link OriginalBusinessQuery1 } | *
*/
public void setOrgnlBizQry(OriginalBusinessQuery1 value) {
this.orgnlBizQry = value;
}
/**
* Gets the value of the addtlInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlInf() {
return addtlInf;
}
/**
* Sets the value of the addtlInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlInf(String value) {
this.addtlInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\GroupHeader58.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static AutoConfigurationReplacements load(Class<?> annotation, @Nullable ClassLoader classLoader) {
Assert.notNull(annotation, "'annotation' must not be null");
ClassLoader classLoaderToUse = decideClassloader(classLoader);
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
Map<String, String> replacements = new HashMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
replacements.putAll(readReplacements(url));
}
return new AutoConfigurationReplacements(replacements);
}
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location); | }
catch (IOException ex) {
throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<String, String> readReplacements(URL url) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) {
Properties properties = new Properties();
properties.load(reader);
return (Map) properties;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load replacements from location [" + url + "]", ex);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationReplacements.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Column(name = "source")
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
@Column(name = "destination")
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
@Column(name = "delivered", columnDefinition = "boolean")
public boolean isDelivered() {
return isDelivered;
}
public void setDelivered(boolean delivered) {
isDelivered = delivered;
} | @ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_item", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "item_index")
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
@ElementCollection(fetch = EAGER)
@CollectionTable(name = "consignment_checkin", joinColumns = @JoinColumn(name = "consignment_id"))
@OrderColumn(name = "checkin_index")
public List<Checkin> getCheckins() {
return checkins;
}
public void setCheckins(List<Checkin> checkins) {
this.checkins = checkins;
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\Consignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractProcessEngineAutoConfiguration extends AbstractProcessEngineConfiguration {
@Bean
public SpringAsyncExecutor springAsyncExecutor(TaskExecutor applicationTaskExecutor) {
return new SpringAsyncExecutor(applicationTaskExecutor, springRejectedJobsHandler());
}
@Bean
public SpringRejectedJobsHandler springRejectedJobsHandler() {
return new SpringCallerRunsRejectedJobsHandler();
}
protected Set<Class<?>> getCustomMybatisMapperClasses(List<String> customMyBatisMappers) {
Set<Class<?>> mybatisMappers = new HashSet<>();
for (String customMybatisMapperClassName : customMyBatisMappers) {
try {
Class customMybatisClass = Class.forName(customMybatisMapperClassName);
mybatisMappers.add(customMybatisClass);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class " + customMybatisMapperClassName + " has not been found.", e);
}
}
return mybatisMappers;
}
@Bean
public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration configuration) {
return super.springProcessEngineBean(configuration);
}
@Bean
@ConditionalOnMissingBean
@Override
public RuntimeService runtimeServiceBean(ProcessEngine processEngine) {
return super.runtimeServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public RepositoryService repositoryServiceBean(ProcessEngine processEngine) {
return super.repositoryServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean | @Override
public TaskService taskServiceBean(ProcessEngine processEngine) {
return super.taskServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public HistoryService historyServiceBean(ProcessEngine processEngine) {
return super.historyServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public ManagementService managementServiceBeanBean(ProcessEngine processEngine) {
return super.managementServiceBeanBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) {
return super.integrationContextManagerBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) {
return super.integrationContextServiceBean(processEngine);
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AbstractProcessEngineAutoConfiguration.java | 2 |
请完成以下Java代码 | protected void configureQuery(HistoricIncidentQueryImpl query) {
getAuthorizationManager().configureHistoricIncidentQuery(query);
getTenantManager().configureQuery(query);
}
protected boolean isHistoryEventProduced() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
return historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_CREATE, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_DELETE, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_RESOLVE, null);
}
public DbOperation deleteHistoricIncidentsByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo); | }
parameters.put("batchSize", batchSize);
return getDbEntityManager()
.deletePreserveOrder(HistoricIncidentEntity.class, "deleteHistoricIncidentsByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
public void addRemovalTimeToHistoricIncidentsByBatchId(String batchId, Date removalTime) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("batchId", batchId);
parameters.put("removalTime", removalTime);
getDbEntityManager()
.updatePreserveOrder(HistoricIncidentEntity.class, "updateHistoricIncidentsByBatchId", parameters);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricIncidentManager.java | 1 |
请完成以下Java代码 | public Message<?> preSend(Message<?> message, MessageChannel channel) {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
authentication = this.anonymous;
}
return MessageBuilder.fromMessage(message).setHeader(this.authenticationHeaderName, authentication).build();
}
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
return postReceive(message, channel);
}
@Override
public Message<?> postReceive(Message<?> message, MessageChannel channel) {
setup(message);
return message;
}
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler,
@Nullable Exception ex) {
cleanup();
}
private void setup(Message<?> message) {
Authentication authentication = message.getHeaders().get(this.authenticationHeaderName, Authentication.class);
SecurityContext currentContext = this.securityContextHolderStrategy.getContext();
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null) {
contextStack = new Stack<>();
originalContext.set(contextStack);
}
contextStack.push(currentContext);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
this.securityContextHolderStrategy.setContext(context);
}
private void cleanup() {
Stack<SecurityContext> contextStack = originalContext.get();
if (contextStack == null || contextStack.isEmpty()) {
this.securityContextHolderStrategy.clearContext(); | originalContext.remove();
return;
}
SecurityContext context = contextStack.pop();
try {
if (this.empty.equals(context)) {
this.securityContextHolderStrategy.clearContext();
originalContext.remove();
}
else {
this.securityContextHolderStrategy.setContext(context);
}
}
catch (Throwable ex) {
this.securityContextHolderStrategy.clearContext();
}
}
} | repos\spring-security-main\messaging\src\main\java\org\springframework\security\messaging\context\SecurityContextPropagationChannelInterceptor.java | 1 |
请完成以下Java代码 | public List<HistoricCaseInstance> findByCriteria(HistoricCaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return getDbSqlSession().selectList("selectHistoricCaseInstancesByQueryCriteria", query, getManagedEntityClass());
}
@Override
public long countByCriteria(HistoricCaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return (Long) getDbSqlSession().selectOne("selectHistoricCaseInstanceCountByQueryCriteria", query);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findWithVariablesByQueryCriteria(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
setSafeInValueLists(historicCaseInstanceQuery);
return getDbSqlSession().selectList("selectHistoricCaseInstancesWithVariablesByQueryCriteria", historicCaseInstanceQuery, getManagedEntityClass());
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricCaseInstance> findIdsByCriteria(HistoricCaseInstanceQueryImpl query) {
setSafeInValueLists(query);
return getDbSqlSession().selectList("selectHistoricCaseInstanceIdsByQueryCriteria", query, getManagedEntityClass());
}
@Override
public void deleteByCaseDefinitionId(String caseDefinitionId) {
getDbSqlSession().delete("deleteHistoricCaseInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass());
} | @Override
public void deleteHistoricCaseInstances(HistoricCaseInstanceQueryImpl historicCaseInstanceQuery) {
getDbSqlSession().delete("bulkDeleteHistoricCaseInstances", historicCaseInstanceQuery, getManagedEntityClass());
}
@Override
public void bulkDeleteHistoricCaseInstances(Collection<String> caseInstanceIds) {
getDbSqlSession().delete("bulkDeleteHistoricCaseInstancesByIds", createSafeInValuesList(caseInstanceIds), getManagedEntityClass());
}
protected void setSafeInValueLists(HistoricCaseInstanceQueryImpl caseInstanceQuery) {
if (caseInstanceQuery.getCaseInstanceIds() != null) {
caseInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(caseInstanceQuery.getCaseInstanceIds()));
}
if (caseInstanceQuery.getInvolvedGroups() != null) {
caseInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(caseInstanceQuery.getInvolvedGroups()));
}
if (caseInstanceQuery.getOrQueryObjects() != null && !caseInstanceQuery.getOrQueryObjects().isEmpty()) {
for (HistoricCaseInstanceQueryImpl orCaseInstanceQuery : caseInstanceQuery.getOrQueryObjects()) {
setSafeInValueLists(orCaseInstanceQuery);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisHistoricCaseInstanceDataManagerImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.