instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public int hashCode()
{
return new HashcodeBuilder()
.append(qtyToAllocate)
.append(transactions)
.append(attributeTransactions)
.toHashcode();
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
final MutableAllocationResult other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(qtyToAllocate, other.qtyToAllocate)
.append(transactions, other.transactions)
.append(attributeTransactions, other.attributeTransactions)
.isEqual();
}
@Override
public boolean isCompleted()
{
return qtyToAllocate.signum() == 0;
}
@Override
public void subtractAllocatedQty(@NonNull final BigDecimal qtyAllocated)
{
final BigDecimal qtyToAllocateNew = qtyToAllocate.subtract(qtyAllocated);
Check.assume(qtyToAllocateNew.signum() >= 0,
"Cannot allocate {} when qtyToAllocate is {}", qtyAllocated, qtyToAllocate);
qtyToAllocate = qtyToAllocateNew;
}
@Override
public BigDecimal getQtyToAllocate()
{
return qtyToAllocate;
}
@Override
public BigDecimal getQtyAllocated()
{
return qtyToAllocateInitial.subtract(qtyToAllocate);
}
@Override
public void addTransaction(final IHUTransactionCandidate trx)
{
transactions.add(trx);
}
@Override
public void addTransactions(final List<IHUTransactionCandidate> trxs)
{
trxs.forEach(trx -> addTransaction(trx));
}
|
@Override
public List<IHUTransactionCandidate> getTransactions()
{
return transactionsRO;
}
@Override
public void addAttributeTransaction(final IHUTransactionAttribute attributeTrx)
{
attributeTransactions.add(attributeTrx);
}
@Override
public void addAttributeTransactions(final List<IHUTransactionAttribute> attributeTrxs)
{
attributeTransactions.addAll(attributeTrxs);
}
@Override
public List<IHUTransactionAttribute> getAttributeTransactions()
{
return attributeTransactionsRO;
}
@Override
public void aggregateTransactions()
{
final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class);
final List<IHUTransactionCandidate> aggregateTransactions = huTrxBL.aggregateTransactions(transactions);
transactions.clear();
transactions.addAll(aggregateTransactions);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\MutableAllocationResult.java
| 1
|
请完成以下Java代码
|
public HTMLDocument getDocument()
{
return this.document;
}
@Override
public void requestFocus()
{
this.editor.requestFocus();
}
@Override
public boolean requestFocus(boolean temporary)
{
return this.editor.requestFocus(temporary);
}
@Override
public boolean requestFocusInWindow()
{
return this.editor.requestFocusInWindow();
}
public void setText(String html)
{
this.editor.setText(html);
}
public void setCaretPosition(int position)
{
this.editor.setCaretPosition(position);
|
}
public ActionMap getEditorActionMap()
{
return this.editor.getActionMap();
}
public InputMap getEditorInputMap(int condition)
{
return this.editor.getInputMap(condition);
}
public Keymap getEditorKeymap()
{
return this.editor.getKeymap();
}
public JTextComponent getTextComponent()
{
return this.editor;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java
| 1
|
请完成以下Java代码
|
private List<DocumentLayoutElementDescriptor> buildElements()
{
return elementsBuilders
.stream()
.filter(elementBuilder -> checkValid(elementBuilder))
.map(elementBuilder -> elementBuilder.build())
.filter(element -> checkValid(element))
.collect(GuavaCollectors.toImmutableList());
}
private final boolean checkValid(final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
if (elementBuilder.isConsumed())
{
logger.trace("Skip adding {} to {} because it's already consumed", elementBuilder, this);
return false;
}
if (elementBuilder.isEmpty())
{
logger.trace("Skip adding {} to {} because it's empty", elementBuilder, this);
return false;
}
return true;
}
private final boolean checkValid(final DocumentLayoutElementDescriptor element)
{
if (element.isEmpty())
{
logger.trace("Skip adding {} to {} because it does not have fields", element, this);
return false;
}
return true;
}
public Builder setInternalName(final String internalName)
{
this.internalName = internalName;
return this;
}
|
public Builder addElement(final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
elementsBuilders.add(elementBuilder);
return this;
}
public boolean hasElements()
{
return !elementsBuilders.isEmpty();
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementsBuilders.stream();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutElementLineDescriptor.java
| 1
|
请完成以下Java代码
|
public static class OAuth2AuthorizationConsentRowMapper implements RowMapper<OAuth2AuthorizationConsent> {
private final RegisteredClientRepository registeredClientRepository;
public OAuth2AuthorizationConsentRowMapper(RegisteredClientRepository registeredClientRepository) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
this.registeredClientRepository = registeredClientRepository;
}
@Override
public OAuth2AuthorizationConsent mapRow(ResultSet rs, int rowNum) throws SQLException {
String registeredClientId = rs.getString("registered_client_id");
RegisteredClient registeredClient = this.registeredClientRepository.findById(registeredClientId);
if (registeredClient == null) {
throw new DataRetrievalFailureException("The RegisteredClient with id '" + registeredClientId
+ "' was not found in the RegisteredClientRepository.");
}
String principalName = rs.getString("principal_name");
OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClientId,
principalName);
String authorizationConsentAuthorities = rs.getString("authorities");
if (authorizationConsentAuthorities != null) {
for (String authority : StringUtils.commaDelimitedListToSet(authorizationConsentAuthorities)) {
builder.authority(new SimpleGrantedAuthority(authority));
}
}
return builder.build();
}
protected final RegisteredClientRepository getRegisteredClientRepository() {
return this.registeredClientRepository;
}
}
|
/**
* The default {@code Function} that maps {@link OAuth2AuthorizationConsent} to a
* {@code List} of {@link SqlParameterValue}.
*/
public static class OAuth2AuthorizationConsentParametersMapper
implements Function<OAuth2AuthorizationConsent, List<SqlParameterValue>> {
@Override
public List<SqlParameterValue> apply(OAuth2AuthorizationConsent authorizationConsent) {
List<SqlParameterValue> parameters = new ArrayList<>();
parameters.add(new SqlParameterValue(Types.VARCHAR, authorizationConsent.getRegisteredClientId()));
parameters.add(new SqlParameterValue(Types.VARCHAR, authorizationConsent.getPrincipalName()));
Set<String> authorities = new HashSet<>();
for (GrantedAuthority authority : authorizationConsent.getAuthorities()) {
authorities.add(authority.getAuthority());
}
parameters
.add(new SqlParameterValue(Types.VARCHAR, StringUtils.collectionToDelimitedString(authorities, ",")));
return parameters;
}
}
static class JdbcOAuth2AuthorizationConsentServiceRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources()
.registerResource(new ClassPathResource(
"org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql"));
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\JdbcOAuth2AuthorizationConsentService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private RestartProcessInstanceBuilder createRestartProcessInstanceBuilder(RestartProcessInstanceDto restartProcessInstanceDto) {
RuntimeService runtimeService = engine.getRuntimeService();
RestartProcessInstanceBuilder builder = runtimeService
.restartProcessInstances(processDefinitionId);
if (restartProcessInstanceDto.getProcessInstanceIds() != null) {
builder.processInstanceIds(restartProcessInstanceDto.getProcessInstanceIds());
}
if (restartProcessInstanceDto.getHistoricProcessInstanceQuery() != null) {
builder.historicProcessInstanceQuery(restartProcessInstanceDto.getHistoricProcessInstanceQuery().toQuery(engine));
}
if (restartProcessInstanceDto.isInitialVariables()) {
builder.initialSetOfVariables();
}
if (restartProcessInstanceDto.isWithoutBusinessKey()) {
builder.withoutBusinessKey();
}
if (restartProcessInstanceDto.isSkipCustomListeners()) {
builder.skipCustomListeners();
}
if (restartProcessInstanceDto.isSkipIoMappings()) {
builder.skipIoMappings();
}
restartProcessInstanceDto.applyTo(builder, engine, objectMapper);
return builder;
}
public Response getDeployedStartForm() {
|
try {
InputStream deployedStartForm = engine.getFormService().getDeployedStartForm(processDefinitionId);
return Response.ok(deployedStartForm, getStartFormMediaType(processDefinitionId)).build();
} catch (NotFoundException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (NullValueException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
} catch (AuthorizationException e) {
throw new InvalidRequestException(Status.FORBIDDEN, e.getMessage());
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
}
protected String getStartFormMediaType(String processDefinitionId) {
String formKey = engine.getFormService().getStartFormKey(processDefinitionId);
CamundaFormRef camundaFormRef = engine.getFormService().getStartFormData(processDefinitionId).getCamundaFormRef();
if(formKey != null) {
return ContentTypeUtil.getFormContentType(formKey);
} else if(camundaFormRef != null) {
return ContentTypeUtil.getFormContentType(camundaFormRef);
}
return MediaType.APPLICATION_XHTML_XML;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\repository\impl\ProcessDefinitionResourceImpl.java
| 2
|
请完成以下Java代码
|
public static DetailDataRecordIdentifier createForReceiptSchedule(
@NonNull final MainDataRecordIdentifier mainDataRecordIdentifier,
final int receiptScheduleId)
{
return new DetailDataRecordIdentifier(mainDataRecordIdentifier, 0, receiptScheduleId);
}
int shipmentScheduleId;
int receiptScheduleId;
MainDataRecordIdentifier mainDataRecordIdentifier;
private DetailDataRecordIdentifier(
@NonNull final MainDataRecordIdentifier mainDataRecordIdentifier,
final int shipmentScheduleId,
final int receiptScheduleId)
{
this.receiptScheduleId = receiptScheduleId;
this.shipmentScheduleId = shipmentScheduleId;
this.mainDataRecordIdentifier = mainDataRecordIdentifier;
final boolean shipmentScheduleIdSet = shipmentScheduleId > 0;
final boolean receiptScheduleIdSet = receiptScheduleId > 0;
Check.errorUnless(shipmentScheduleIdSet ^ receiptScheduleIdSet,
"Either shipmentScheduleId or receipScheduleId (but not both!) needs to be < 0");
}
|
public IQuery<I_MD_Cockpit_DocumentDetail> createQuery()
{
final IQueryBuilder<I_MD_Cockpit_DocumentDetail> queryBuilder = mainDataRecordIdentifier.createQueryBuilder()
.andCollectChildren(I_MD_Cockpit_DocumentDetail.COLUMN_MD_Cockpit_ID);
if (shipmentScheduleId > 0)
{
queryBuilder.addEqualsFilter(I_MD_Cockpit_DocumentDetail.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleId);
}
if (receiptScheduleId > 0)
{
queryBuilder.addEqualsFilter(I_MD_Cockpit_DocumentDetail.COLUMN_M_ReceiptSchedule_ID, receiptScheduleId);
}
return queryBuilder.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\DetailDataRecordIdentifier.java
| 1
|
请完成以下Java代码
|
private ASIDocument getASIDocumentNoLock(final DocumentId asiDocId)
{
final ASIDocument asiDoc = id2asiDoc.get(asiDocId);
if (asiDoc == null)
{
throw new EntityNotFoundException("No product attributes found for asiId=" + asiDocId);
}
return asiDoc;
}
private void commit(final ASIDocument asiDoc)
{
final DocumentId asiDocId = asiDoc.getDocumentId();
if (asiDoc.isCompleted())
{
final ASIDocument asiDocRemoved = id2asiDoc.remove(asiDocId);
logger.trace("Removed from repository by ID={}: {}", asiDocId, asiDocRemoved);
}
else
{
final ASIDocument asiDocReadonly = asiDoc.copy(CopyMode.CheckInReadonly, NullDocumentChangesCollector.instance);
id2asiDoc.put(asiDocId, asiDocReadonly);
logger.trace("Added to repository: {}", asiDocReadonly);
}
}
public <R> R forASIDocumentReadonly(
@NonNull final DocumentId asiDocId,
@NonNull final DocumentCollection documentsCollection,
@NonNull final Function<ASIDocument, R> processor)
{
|
try (final IAutoCloseable ignored = getASIDocumentNoLock(asiDocId).lockForReading())
{
final ASIDocument asiDoc = getASIDocumentNoLock(asiDocId)
.copy(CopyMode.CheckInReadonly, NullDocumentChangesCollector.instance)
.bindContextDocumentIfPossible(documentsCollection);
return processor.apply(asiDoc);
}
}
public <R> R forASIDocumentWritable(
@NonNull final DocumentId asiDocId,
@NonNull final IDocumentChangesCollector changesCollector,
@NonNull final DocumentCollection documentsCollection,
@NonNull final Function<ASIDocument, R> processor)
{
try (final IAutoCloseable ignored = getASIDocumentNoLock(asiDocId).lockForWriting())
{
final ASIDocument asiDoc = getASIDocumentNoLock(asiDocId)
.copy(CopyMode.CheckOutWritable, changesCollector)
.bindContextDocumentIfPossible(documentsCollection);
final R result = processor.apply(asiDoc);
trxManager.runAfterCommit(() -> commit(asiDoc));
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASIRepository.java
| 1
|
请完成以下Java代码
|
public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) {
this.customPropertiesResolverImplementation = customPropertiesResolverImplementation;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance;
}
/**
* Return the script info, if present.
* <p>
* ScriptInfo must be populated, when {@code <executionListener type="script" ...>} e.g. when
* implementationType is 'script'.
* </p>
*/
@Override
public ScriptInfo getScriptInfo() {
return scriptInfo;
}
/**
* Sets the script info
*
* @see #getScriptInfo()
*/
@Override
public void setScriptInfo(ScriptInfo scriptInfo) {
this.scriptInfo = scriptInfo;
}
@Override
public FlowableListener clone() {
FlowableListener clone = new FlowableListener();
clone.setValues(this);
return clone;
|
}
public void setValues(FlowableListener otherListener) {
super.setValues(otherListener);
setEvent(otherListener.getEvent());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
if (otherListener.getScriptInfo() != null) {
setScriptInfo(otherListener.getScriptInfo().clone());
}
fieldExtensions = new ArrayList<>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
setOnTransaction(otherListener.getOnTransaction());
setCustomPropertiesResolverImplementationType(otherListener.getCustomPropertiesResolverImplementationType());
setCustomPropertiesResolverImplementation(otherListener.getCustomPropertiesResolverImplementation());
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\FlowableListener.java
| 1
|
请完成以下Java代码
|
public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public void setCommandExecutor(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public boolean isUseClassForNameClassLoading() {
return useClassForNameClassLoading;
}
public void setUseClassForNameClassLoading(boolean useClassForNameClassLoading) {
this.useClassForNameClassLoading = useClassForNameClassLoading;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
// getters and setters
// //////////////////////////////////////////////////////
|
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public boolean isReused() {
return reused;
}
public void setReused(boolean reused) {
this.reused = reused;
}
public Object getResult() {
return resultStack.pollLast();
}
public void setResult(Object result) {
resultStack.add(result);
}
public long getStartTime() {
return startTime;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\CommandContext.java
| 1
|
请完成以下Java代码
|
public final String getTrxName()
{
return get_TrxName();
}
@Nullable
protected final String getTableName()
{
return getProcessInfo().getTableNameOrNull();
}
/**
* Retrieves the records which where selected and attached to this process execution, i.e.
* <ul>
* <li>if there is any {@link ProcessInfo#getQueryFilterOrElse(IQueryFilter)} that will be used to fetch the records
* <li>else if the single record is set ({@link ProcessInfo}'s AD_Table_ID/Record_ID) that will will be used
* <li>else an exception is thrown
* </ul>
*
* @return query builder which will provide selected record(s)
*/
protected final <ModelType> IQueryBuilder<ModelType> retrieveSelectedRecordsQueryBuilder(final Class<ModelType> modelClass)
{
final ProcessInfo pi = getProcessInfo();
final String tableName = pi.getTableNameOrNull();
final int singleRecordId = pi.getRecord_ID();
final IContextAware contextProvider = PlainContextAware.newWithThreadInheritedTrx(getCtx());
final IQueryBuilder<ModelType> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(modelClass, tableName, contextProvider);
//
// Try fetching the selected records from AD_PInstance's WhereClause.
final IQueryFilter<ModelType> selectionQueryFilter = pi.getQueryFilterOrElse(null);
if (selectionQueryFilter != null)
{
queryBuilder.filter(selectionQueryFilter)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient();
}
//
// Try fetching the single selected record from AD_PInstance's AD_Table_ID/Record_ID.
else if (tableName != null && singleRecordId >= 0)
{
final String keyColumnName = InterfaceWrapperHelper.getKeyColumnName(tableName);
queryBuilder.addEqualsFilter(keyColumnName, singleRecordId);
// .addOnlyActiveRecordsFilter() // NOP, return it as is
|
// .addOnlyContextClient(); // NOP, return it as is
}
else
{
throw new AdempiereException("@NoSelection@");
}
return queryBuilder;
}
/**
* Exceptions to be thrown if we want to cancel the process run.
* <p>
* If this exception is thrown:
* <ul>
* <li>the process will be terminated right away
* <li>transaction (if any) will be rolled back
* <li>process summary message will be set from this exception message
* <li>process will NOT be flagged as error
* </ul>
*/
public static final class ProcessCanceledException extends AdempiereException
{
@VisibleForTesting
public static final AdMessageKey MSG_Canceled = AdMessageKey.of("Canceled");
public ProcessCanceledException()
{
super(MSG_Canceled);
}
}
protected final <T> int createSelection(@NonNull final IQueryBuilder<T> queryBuilder, @NonNull final PInstanceId pinstanceId)
{
return queryBuilder
.create()
.setRequiredAccess(Access.READ)
.createSelection(pinstanceId);
}
protected final UserId getLoggedUserId()
{
return Env.getLoggedUserId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\JavaProcess.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private <S> void addMainCallback(ListenableFuture<S> saveFuture, Consumer<S> onSuccess) {
addMainCallback(saveFuture, onSuccess, null);
}
private <S> void addMainCallback(ListenableFuture<S> saveFuture, Consumer<S> onSuccess, Consumer<Throwable> onFailure) {
DonAsynchron.withCallback(saveFuture, onSuccess, onFailure, tsCallBackExecutor);
}
private void checkInternalEntity(EntityId entityId) {
if (EntityType.API_USAGE_STATE.equals(entityId.getEntityType())) {
throw new RuntimeException("Can't update API Usage State!");
}
}
private FutureCallback<TimeseriesSaveResult> getApiUsageCallback(TenantId tenantId, CustomerId customerId, boolean sysTenant) {
return new FutureCallback<>() {
@Override
public void onSuccess(TimeseriesSaveResult result) {
Integer dataPoints = result.getDataPoints();
if (!sysTenant && dataPoints != null && dataPoints > 0) {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.STORAGE_DP_COUNT, dataPoints);
}
}
|
@Override
public void onFailure(Throwable t) {}
};
}
private FutureCallback<Void> getCalculatedFieldCallback(FutureCallback<List<String>> originalCallback, List<String> keys) {
return new FutureCallback<>() {
@Override
public void onSuccess(Void unused) {
originalCallback.onSuccess(keys);
}
@Override
public void onFailure(Throwable t) {
originalCallback.onFailure(t);
}
};
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultTelemetrySubscriptionService.java
| 2
|
请完成以下Java代码
|
private static java.util.Date truncDate(final java.util.Date date, final String truncValue)
{
if (truncValue == null)
{
// do not truncate
return date;
}
if (date == null)
{
return null;
}
return TimeUtil.trunc(date, truncValue);
}
/**
* Get String Representation
*
* @return info
*/
@Override
public String toString()
{
return getSQL(null);
}
public boolean isJoinAnd()
{
return joinAnd;
}
public String getColumnName()
{
return columnName;
}
/* package */void setColumnName(final String columnName)
{
this.columnName = columnName;
}
/**
* Get Info Name
*
* @return Info Name
*/
public String getInfoName()
{
return infoName;
} // getInfoName
public Operator getOperator()
{
|
return operator;
}
/**
* Get Info Operator
*
* @return info Operator
*/
public String getInfoOperator()
{
return operator == null ? null : operator.getCaption();
} // getInfoOperator
/**
* Get Display with optional To
*
* @return info display
*/
public String getInfoDisplayAll()
{
if (infoDisplayTo == null)
{
return infoDisplay;
}
StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
}
public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java
| 1
|
请完成以下Java代码
|
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
/** Set View ID.
@param ViewId View ID */
@Override
public void setViewId (java.lang.String ViewId)
{
set_Value (COLUMNNAME_ViewId, ViewId);
}
/** Get View ID.
@return View ID */
@Override
public java.lang.String getViewId ()
{
return (java.lang.String)get_Value(COLUMNNAME_ViewId);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
|
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
/**
* NotificationSeverity AD_Reference_ID=541947
* Reference name: NotificationSeverity
*/
public static final int NOTIFICATIONSEVERITY_AD_Reference_ID=541947;
/** Notice = Notice */
public static final String NOTIFICATIONSEVERITY_Notice = "Notice";
/** Warning = Warning */
public static final String NOTIFICATIONSEVERITY_Warning = "Warning";
/** Error = Error */
public static final String NOTIFICATIONSEVERITY_Error = "Error";
@Override
public void setNotificationSeverity (final java.lang.String NotificationSeverity)
{
set_Value (COLUMNNAME_NotificationSeverity, NotificationSeverity);
}
@Override
public java.lang.String getNotificationSeverity()
{
return get_ValueAsString(COLUMNNAME_NotificationSeverity);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Note.java
| 1
|
请完成以下Java代码
|
public class Person implements Hidable {
private String name;
private Address address;
private boolean hidden;
public Person(final String name, final Address address, final boolean hidden) {
super();
this.name = name;
this.address = address;
this.hidden = hidden;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
|
public Address getAddress() {
return address;
}
public void setAddress(final Address address) {
this.address = address;
}
@Override
public boolean isHidden() {
return hidden;
}
public void setHidden(final boolean hidden) {
this.hidden = hidden;
}
}
|
repos\tutorials-master\jackson-modules\jackson-custom-conversions\src\main\java\com\baeldung\skipfields\Person.java
| 1
|
请完成以下Java代码
|
public void addInvoice(@NonNull final InvoiceId invoiceId)
{
final InvoiceRow row = repository.getInvoiceRowByInvoiceId(invoiceId, evaluationDate).orElse(null);
if (row == null)
{
throw new AdempiereException("@InvoiceNotOpen@");
}
rowsHolder.compute(rows -> rows.addingRow(row));
}
@Override
public void patchRow(final RowEditingContext ctx, final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
final DocumentId rowIdToChange = ctx.getRowId();
rowsHolder.compute(rows -> rows.changingRow(rowIdToChange, row -> InvoiceRowReducers.reduce(row, fieldChangeRequests)));
}
public ImmutableList<InvoiceRow> getRowsWithPreparedForAllocationFlagSet()
{
return getAllRows()
|
.stream()
.filter(InvoiceRow::isPreparedForAllocation)
.collect(ImmutableList.toImmutableList());
}
public void markPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationSet));
}
public void unmarkPreparedForAllocation(@NonNull final DocumentIdsSelection rowIds)
{
rowsHolder.compute(rows -> rows.changingRows(rowIds, InvoiceRow::withPreparedForAllocationUnset));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRows.java
| 1
|
请完成以下Java代码
|
public String toString() {
if (this.files.size() == 1) {
return this.files.get(0).getPath();
}
return this.files.stream().map(File::toString).collect(Collectors.joining(", "));
}
/**
* Find the Docker Compose file by searching in the given working directory. Files are
* considered in the same order that {@code docker compose} uses, namely:
* <ul>
* <li>{@code compose.yaml}</li>
* <li>{@code compose.yml}</li>
* <li>{@code docker-compose.yaml}</li>
* <li>{@code docker-compose.yml}</li>
* </ul>
* @param workingDirectory the working directory to search or {@code null} to use the
* current directory
* @return the located file or {@code null} if no Docker Compose file can be found
*/
public static @Nullable DockerComposeFile find(@Nullable File workingDirectory) {
File base = (workingDirectory != null) ? workingDirectory : new File(".");
if (!base.exists()) {
return null;
}
Assert.state(base.isDirectory(), () -> "'%s' is not a directory".formatted(base));
Path basePath = base.toPath();
for (String candidate : SEARCH_ORDER) {
Path resolved = basePath.resolve(candidate);
if (Files.exists(resolved)) {
return of(resolved.toAbsolutePath().toFile());
}
|
}
return null;
}
/**
* Create a new {@link DockerComposeFile} for the given {@link File}.
* @param file the source file
* @return the Docker Compose file
*/
public static DockerComposeFile of(File file) {
Assert.notNull(file, "'file' must not be null");
Assert.isTrue(file.exists(), () -> "'file' [%s] must exist".formatted(file));
Assert.isTrue(file.isFile(), () -> "'file' [%s] must be a normal file".formatted(file));
return new DockerComposeFile(Collections.singletonList(file));
}
/**
* Creates a new {@link DockerComposeFile} for the given {@link File files}.
* @param files the source files
* @return the Docker Compose file
* @since 3.4.0
*/
public static DockerComposeFile of(Collection<? extends File> files) {
Assert.notNull(files, "'files' must not be null");
for (File file : files) {
Assert.notNull(file, "'files' must not contain null elements");
Assert.isTrue(file.exists(), () -> "'files' content [%s] must exist".formatted(file));
Assert.isTrue(file.isFile(), () -> "'files' content [%s] must be a normal file".formatted(file));
}
return new DockerComposeFile(List.copyOf(files));
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DockerComposeFile.java
| 1
|
请完成以下Java代码
|
public void setMandatory(final int M_Locator_ID, final int M_Product_ID, final BigDecimal MovementQty)
{
setM_Locator_ID(M_Locator_ID);
setM_Product_ID(M_Product_ID);
setMovementQty(MovementQty);
} // setMandatory
public void process()
{
saveEx();
if (getM_Product_ID() <= 0)
{
throw new FillMandatoryException(COLUMNNAME_M_Product_ID);
}
final IProductBL productBL = Services.get(IProductBL.class);
if (productBL.isStocked(ProductId.ofRepoIdOrNull(getM_Product_ID())))
{
// ** Create Material Transactions **
final MTransaction mTrx = new MTransaction(getCtx(),
getAD_Org_ID(),
MTransaction.MOVEMENTTYPE_WorkOrderPlus,
getM_Locator_ID(),
getM_Product_ID(),
getM_AttributeSetInstance_ID(),
getMovementQty().negate(),
getMovementDate(),
get_TrxName());
|
mTrx.setC_ProjectIssue_ID(getC_ProjectIssue_ID());
InterfaceWrapperHelper.save(mTrx);
final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class);
final IStorageBL storageBL = Services.get(IStorageBL.class);
final I_M_Locator loc = warehouseDAO.getLocatorByRepoId(getM_Locator_ID());
storageBL.add(getCtx(), loc.getM_Warehouse_ID(), getM_Locator_ID(),
getM_Product_ID(), getM_AttributeSetInstance_ID(), getM_AttributeSetInstance_ID(),
getMovementQty().negate(), null, null, get_TrxName());
}
setProcessed(true);
saveEx();
}
} // MProjectIssue
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProjectIssue.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getCacheFileName(FileType type, String originFileName, String cacheFilePrefixName, boolean isHtmlView, boolean isCompressFile) {
String cacheFileName;
if (type.equals(FileType.OFFICE)) {
cacheFileName = cacheFilePrefixName + (isHtmlView ? "html" : "pdf"); //生成文件添加类型后缀 防止同名文件
} else if (type.equals(FileType.PDF)) {
cacheFileName = originFileName;
} else if (type.equals(FileType.MEDIACONVERT)) {
cacheFileName = cacheFilePrefixName + "mp4";
} else if (type.equals(FileType.CAD)) {
String cadPreviewType = ConfigConstants.getCadPreviewType();
cacheFileName = cacheFilePrefixName + cadPreviewType; //生成文件添加类型后缀 防止同名文件
} else if (type.equals(FileType.COMPRESS)) {
cacheFileName = originFileName;
} else if (type.equals(FileType.TIFF)) {
cacheFileName = cacheFilePrefixName + ConfigConstants.getTifPreviewType();
} else {
cacheFileName = originFileName;
}
if (isCompressFile) { //判断是否使用特定压缩包符号
cacheFileName = "_decompression" + cacheFileName;
}
return cacheFileName;
}
|
/**
* @return 已转换过的视频文件集合(缓存)
*/
public Map<String, String> listConvertedMedias() {
return cacheService.getMediaConvertCache();
}
/**
* 添加转换后的视频文件缓存
*
* @param fileName
* @param value
*/
public void addConvertedMedias(String fileName, String value) {
cacheService.putMediaConvertCache(fileName, value);
}
/**
* @return 已转换视频文件缓存,根据文件名获取
*/
public String getConvertedMedias(String key) {
return cacheService.getMediaConvertCache(key);
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\service\FileHandlerService.java
| 2
|
请完成以下Java代码
|
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Override
public Object getPersistentState() {
return new HashMap<>();
}
@Override
public String toString() {
|
return (
"IntegrationContext[ " +
"executionId='" +
executionId +
'\'' +
", processInstanceId='" +
processInstanceId +
'\'' +
", flowNodeId='" +
flowNodeId +
'\'' +
" ]"
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\integration\IntegrationContextEntityImpl.java
| 1
|
请完成以下Java代码
|
public void setK_Comment_ID (int K_Comment_ID)
{
if (K_Comment_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Comment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Comment_ID, Integer.valueOf(K_Comment_ID));
}
/** Get Entry Comment.
@return Knowledge Entry Comment
*/
public int getK_Comment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Comment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_Comment_ID()));
}
public I_K_Entry getK_Entry() throws RuntimeException
{
return (I_K_Entry)MTable.get(getCtx(), I_K_Entry.Table_Name)
.getPO(getK_Entry_ID(), get_TrxName()); }
/** Set Entry.
@param K_Entry_ID
Knowledge Entry
*/
public void setK_Entry_ID (int K_Entry_ID)
{
if (K_Entry_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID));
}
/** Get Entry.
@return Knowledge Entry
|
*/
public int getK_Entry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Comment.java
| 1
|
请完成以下Java代码
|
public void connectEnd(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol) {
logTimedEvent("connectEnd");
}
@Override
public void connectFailed(Call call, InetSocketAddress inetSocketAddress, Proxy proxy, Protocol protocol, IOException ioe) {
logTimedEvent("connectFailed");
}
@Override
public void connectionAcquired(Call call, Connection connection) {
logTimedEvent("connectionAcquired");
}
@Override
public void connectionReleased(Call call, Connection connection) {
logTimedEvent("connectionReleased");
}
@Override
public void requestHeadersStart(Call call) {
logTimedEvent("requestHeadersStart");
}
@Override
public void requestHeadersEnd(Call call, Request request) {
logTimedEvent("requestHeadersEnd");
}
@Override
public void requestBodyStart(Call call) {
logTimedEvent("requestBodyStart");
}
@Override
public void requestBodyEnd(Call call, long byteCount) {
logTimedEvent("requestBodyEnd");
}
@Override
public void requestFailed(Call call, IOException ioe) {
logTimedEvent("requestFailed");
}
@Override
public void responseHeadersStart(Call call) {
logTimedEvent("responseHeadersStart");
}
|
@Override
public void responseHeadersEnd(Call call, Response response) {
logTimedEvent("responseHeadersEnd");
}
@Override
public void responseBodyStart(Call call) {
logTimedEvent("responseBodyStart");
}
@Override
public void responseBodyEnd(Call call, long byteCount) {
logTimedEvent("responseBodyEnd");
}
@Override
public void responseFailed(Call call, IOException ioe) {
logTimedEvent("responseFailed");
}
@Override
public void callEnd(Call call) {
logTimedEvent("callEnd");
}
@Override
public void callFailed(Call call, IOException ioe) {
logTimedEvent("callFailed");
}
@Override
public void canceled(Call call) {
logTimedEvent("canceled");
}
}
|
repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\okhttp\events\EventTimer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isLogConditionEvaluationDelta() {
return this.logConditionEvaluationDelta;
}
public void setLogConditionEvaluationDelta(boolean logConditionEvaluationDelta) {
this.logConditionEvaluationDelta = logConditionEvaluationDelta;
}
}
/**
* LiveReload properties.
*/
public static class Livereload {
/**
* Whether to enable a livereload.com-compatible server.
*/
private boolean enabled;
/**
* Server port.
*/
private int port = 35729;
|
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPhone() {
return phone;
}
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public String getZipCode() {
return zipCode;
}
@Override
public void update(final String quote) {
// user got updated with a new quote
|
}
@Override
public void subscribe(final Subject subject) {
subject.attach(this);
}
@Override
public void unsubscribe(final Subject subject) {
subject.detach(this);
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
}
|
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\lapsedlistener\User.java
| 1
|
请完成以下Java代码
|
public String getProcessDefinitionName() {
return processDefinitionName;
}
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public Integer getProcessDefinitionVersion() {
return processDefinitionVersion;
}
public void setProcessDefinitionVersion(Integer processDefinitionVersion) {
this.processDefinitionVersion = processDefinitionVersion;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<String, Object>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
|
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
public HistoricVariableInstanceResource variableInstanceResource(String variableId) {
return new HistoricVariableInstanceResourceImpl(variableId, processEngine);
}
@Override
public List<HistoricVariableInstanceDto> getHistoricVariableInstances(UriInfo uriInfo, Integer firstResult,
Integer maxResults, boolean deserializeObjectValues) {
HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricVariableInstances(queryDto, firstResult, maxResults, deserializeObjectValues);
}
@Override
public List<HistoricVariableInstanceDto> queryHistoricVariableInstances(HistoricVariableInstanceQueryDto queryDto,
Integer firstResult, Integer maxResults, boolean deserializeObjectValues) {
queryDto.setObjectMapper(objectMapper);
HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine);
query.disableBinaryFetching();
if (!deserializeObjectValues) {
query.disableCustomObjectDeserialization();
}
List<HistoricVariableInstance> matchingHistoricVariableInstances = QueryUtil.list(query, firstResult, maxResults);
List<HistoricVariableInstanceDto> historicVariableInstanceDtoResults = new ArrayList<HistoricVariableInstanceDto>();
for (HistoricVariableInstance historicVariableInstance : matchingHistoricVariableInstances) {
HistoricVariableInstanceDto resultHistoricVariableInstance = HistoricVariableInstanceDto.fromHistoricVariableInstance(historicVariableInstance);
historicVariableInstanceDtoResults.add(resultHistoricVariableInstance);
}
return historicVariableInstanceDtoResults;
|
}
@Override
public CountResultDto getHistoricVariableInstancesCount(UriInfo uriInfo) {
HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricVariableInstancesCount(queryDto);
}
@Override
public CountResultDto queryHistoricVariableInstancesCount(HistoricVariableInstanceQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricVariableInstanceRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute> getTrie()
{
return trie;
}
public void setTrie(AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute> trie)
{
this.trie = trie;
}
public AhoCorasickDoubleArrayTrieSegment loadDictionary(String... pathArray)
{
trie = new AhoCorasickDoubleArrayTrie<CoreDictionary.Attribute>();
TreeMap<String, CoreDictionary.Attribute> map = null;
try
|
{
map = IOUtil.loadDictionary(pathArray);
}
catch (IOException e)
{
logger.warning("加载词典失败\n" + TextUtility.exceptionToString(e));
return this;
}
if (map != null && !map.isEmpty())
{
trie.build(map);
}
return this;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\Other\AhoCorasickDoubleArrayTrieSegment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class FooService extends AbstractService<Foo> implements IFooService {
@Autowired
private IFooDao dao;
public FooService() {
super();
}
// API
@Override
protected JpaRepository<Foo, Long> getDao() {
return dao;
}
|
// custom methods
@Override
public Page<Foo> findPaginated(Pageable pageable) {
return dao.findAll(pageable);
}
// overridden to be secured
@Override
@Transactional(readOnly = true)
public List<Foo> findAll() {
return Lists.newArrayList(getDao().findAll());
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\persistence\service\impl\FooService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public Integer getUserState() {
return userState;
}
public void setUserState(Integer userState) {
this.userState = userState;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRegisterTimeStart() {
return registerTimeStart;
}
public void setRegisterTimeStart(String registerTimeStart) {
this.registerTimeStart = registerTimeStart;
}
public String getRegisterTimeEnd() {
return registerTimeEnd;
}
public void setRegisterTimeEnd(String registerTimeEnd) {
this.registerTimeEnd = registerTimeEnd;
}
public Integer getOrderByRegisterTime() {
return orderByRegisterTime;
}
public void setOrderByRegisterTime(Integer orderByRegisterTime) {
this.orderByRegisterTime = orderByRegisterTime;
|
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserQueryReq{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", registerTimeStart='" + registerTimeStart + '\'' +
", registerTimeEnd='" + registerTimeEnd + '\'' +
", userType=" + userType +
", userState=" + userState +
", roleId='" + roleId + '\'' +
", orderByRegisterTime=" + orderByRegisterTime +
", page=" + page +
", numPerPage=" + numPerPage +
'}';
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\UserQueryReq.java
| 2
|
请完成以下Java代码
|
private static void setOfferValidDate(I_C_Order order)
{
if (order.isProcessed())
return;
final Timestamp dateOrdered = order.getDateOrdered();
if (dateOrdered != null && isOffer(order))
{
final int days = order.getOfferValidDays();
if (days < 0)
throw new AdempiereException("@"+I_C_Order.COLUMNNAME_OfferValidDays+"@ < 0");
final Timestamp offerValidDate = TimeUtil.addDays(dateOrdered, days);
order.setOfferValidDate(offerValidDate);
}
else
{
order.setOfferValidDays(0);
order.setOfferValidDate(null);
|
}
}
private static boolean isOffer(final I_C_Order order)
{
DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(order.getC_DocType_ID());
if (docTypeId == null)
{
docTypeId = DocTypeId.ofRepoIdOrNull(order.getC_DocTypeTarget_ID());
}
if (docTypeId == null)
{
return false;
}
return Services.get(IDocTypeBL.class).isSalesProposalOrQuotation(docTypeId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\OrderOffer.java
| 1
|
请完成以下Java代码
|
public class CustomHUQRCode implements IHUQRCode
{
@NonNull private final ParsedScannedCode parsedScannedCode;
private CustomHUQRCode(@NonNull final ParsedScannedCode parsedScannedCode)
{
this.parsedScannedCode = parsedScannedCode;
}
public static CustomHUQRCode ofParsedScannedCode(@NonNull final ParsedScannedCode parsedScannedCode)
{
return new CustomHUQRCode(parsedScannedCode);
}
@Override
@Deprecated
public String toString() {return getAsString();}
@Override
public String getAsString() {return parsedScannedCode.getAsString();}
public Optional<String> getProductNo() {return Optional.ofNullable(parsedScannedCode.getProductNo());}
@Override
public Optional<BigDecimal> getWeightInKg()
|
{
return Optional.ofNullable(parsedScannedCode.getWeightKg());
}
@Override
public Optional<LocalDate> getBestBeforeDate()
{
return Optional.ofNullable(parsedScannedCode.getBestBeforeDate());
}
@Override
public Optional<LocalDate> getProductionDate()
{
return Optional.ofNullable(parsedScannedCode.getProductionDate());
}
@Override
public Optional<String> getLotNumber()
{
return Optional.ofNullable(parsedScannedCode.getLotNo());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\custom\CustomHUQRCode.java
| 1
|
请完成以下Java代码
|
protected @NonNull ObjectMapper getObjectMapper() {
return this.objectMapper;
}
/**
* Converts the given {@link String JSON} containing multiple objects into an array of {@link PdxInstance} objects.
*
* @param json {@link String JSON} data to convert.
* @return an array of {@link PdxInstance} objects from the given {@link String JSON}.
* @throws IllegalStateException if the {@link String JSON} does not start with
* either a JSON array or a JSON object.
* @see org.apache.geode.pdx.PdxInstance
*/
@Nullable @Override
public PdxInstance[] convert(String json) {
try {
JsonNode jsonNode = getObjectMapper().readTree(json);
List<PdxInstance> pdxList = new ArrayList<>();
if (isArray(jsonNode)) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
JsonToPdxConverter converter = getJsonToPdxConverter();
for (JsonNode object : asIterable(CollectionUtils.nullSafeIterator(arrayNode.elements()))) {
pdxList.add(converter.convert(object.toString()));
}
}
else if (isObject(jsonNode)) {
ObjectNode objectNode = (ObjectNode) jsonNode;
|
pdxList.add(getJsonToPdxConverter().convert(objectNode.toString()));
}
else {
String message = String.format("Unable to process JSON node of type [%s];"
+ " expected either an [%s] or an [%s]", jsonNode.getNodeType(),
JsonNodeType.OBJECT, JsonNodeType.ARRAY);
throw new IllegalStateException(message);
}
return pdxList.toArray(new PdxInstance[0]);
}
catch (JsonProcessingException cause) {
throw new DataRetrievalFailureException("Failed to read JSON content", cause);
}
}
private boolean isArray(@Nullable JsonNode node) {
return node != null && (node.isArray() || JsonNodeType.ARRAY.equals(node.getNodeType()));
}
private boolean isObject(@Nullable JsonNode node) {
return node != null && (node.isObject() || JsonNodeType.OBJECT.equals(node.getNodeType()));
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToPdxConverter.java
| 1
|
请完成以下Java代码
|
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Collection<EventPayloadInstance> getParameterInstances() {
return parameterInstances;
}
public void setParameterInstances(Collection<EventPayloadInstance> parameterInstances) {
this.parameterInstances = parameterInstances;
}
@Override
public boolean equals(Object o) {
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CorrelationKey that = (CorrelationKey) o;
return Objects.equals(value, that.value) && Objects.equals(parameterInstances, that.parameterInstances);
}
@Override
public int hashCode() {
return value.hashCode(); // The value is determined by the parameterInstance, so no need to use them in the hashcode
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\consumer\CorrelationKey.java
| 1
|
请完成以下Java代码
|
public void updateDiscount(final MOrderLine ol)
{
BigDecimal list = ol.getPriceList();
// No List Price
if (BigDecimal.ZERO.compareTo(list) == 0)
return;
// final int precision = getPrecision();
final int precision = 1; // metas
// TODO: metas: why we are using precision=1 instead of getPrecision()?
BigDecimal discount = list.subtract(ol.getPriceActual())
.multiply(new BigDecimal(100))
.divide(list, precision, BigDecimal.ROUND_HALF_UP);
ol.setDiscount(discount);
} // setDiscount
/**
* Get and validate Project
* @param ctx context
* @param C_Project_ID id
|
* @return valid project
* @param trxName transaction
*/
static protected MProject getProject (Properties ctx, int C_Project_ID, String trxName)
{
MProject fromProject = new MProject (ctx, C_Project_ID, trxName);
if (fromProject.getC_Project_ID() == 0)
throw new IllegalArgumentException("Project not found C_Project_ID=" + C_Project_ID);
if (fromProject.getM_PriceList_Version_ID() == 0)
throw new IllegalArgumentException("Project has no Price List");
if (fromProject.getM_Warehouse_ID() == 0)
throw new IllegalArgumentException("Project has no Warehouse");
if (fromProject.getC_BPartner_ID() == 0 || fromProject.getC_BPartner_Location_ID() == 0)
throw new IllegalArgumentException("Project has no Business Partner/Location");
return fromProject;
} // getProject
} // ProjectGenOrder
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectGenOrder.java
| 1
|
请完成以下Java代码
|
public class Library {
@DatabaseField(generatedId = true)
private long libraryId;
@DatabaseField(canBeNull = false)
private String name;
@DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true)
private Address address;
@ForeignCollectionField(eager = false)
private ForeignCollection<Book> books;
public Library() {
}
public long getLibraryId() {
return libraryId;
}
public void setLibraryId(long libraryId) {
this.libraryId = libraryId;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ForeignCollection<Book> getBooks() {
return books;
}
public void setBooks(ForeignCollection<Book> books) {
this.books = books;
}
}
|
repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\ormlite\Library.java
| 1
|
请完成以下Java代码
|
public PageData<Edge> findEdgesByTenantIdAndEntityId(UUID tenantId, UUID entityId, EntityType entityType, PageLink pageLink) {
log.debug("Try to find edges by tenantId [{}], entityId [{}], entityType [{}], pageLink [{}]", tenantId, entityId, entityType, pageLink);
return DaoUtil.toPageData(
edgeRepository.findByTenantIdAndEntityId(
tenantId,
entityId,
entityType.name(),
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<EdgeId> findEdgeIdsByTenantIdAndEntityId(UUID tenantId, UUID entityId, EntityType entityType, PageLink pageLink) {
log.debug("Try to find edge ids by tenantId [{}], entityId [{}], entityType [{}], pageLink [{}]", tenantId, entityId, entityType, pageLink);
return DaoUtil.pageToPageData(
edgeRepository.findIdsByTenantIdAndEntityId(
tenantId,
entityId,
entityType.name(),
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink))).mapData(EdgeId::fromUUID);
}
@Override
public PageData<Edge> findEdgesByTenantProfileId(UUID tenantProfileId, PageLink pageLink) {
log.debug("Try to find edges by tenantProfileId [{}], pageLink [{}]", tenantProfileId, pageLink);
return DaoUtil.toPageData(
edgeRepository.findByTenantProfileId(
tenantProfileId,
DaoUtil.toPageable(pageLink)));
}
|
@Override
public Long countByTenantId(TenantId tenantId) {
return edgeRepository.countByTenantId(tenantId.getId());
}
@Override
public PageData<Edge> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findEdgesByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<EdgeFields> findNextBatch(UUID id, int batchSize) {
return edgeRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.EDGE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\JpaEdgeDao.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JobBaseResource {
@Autowired
protected CmmnManagementService managementService;
@Autowired(required=false)
protected CmmnRestApiInterceptor restApiInterceptor;
protected Job getJobById(String jobId) {
Job job = managementService.createJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected Job getTimerJobById(String jobId) {
Job job = managementService.createTimerJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected Job getSuspendedJobById(String jobId) {
Job job = managementService.createSuspendedJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected Job getDeadLetterJobById(String jobId) {
Job job = managementService.createDeadLetterJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected HistoryJob getHistoryJobById(String jobId) {
HistoryJob job = managementService.createHistoryJobQuery().jobId(jobId).singleResult();
validateHistoryJob(job, jobId);
|
return job;
}
protected void validateJob(Job job, String jobId) {
if (job == null) {
throw new FlowableObjectNotFoundException("Could not find a job with id '" + jobId + "'.", Job.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessJobInfoById(job);
}
}
protected void validateHistoryJob(HistoryJob job, String jobId) {
if (job == null) {
throw new FlowableObjectNotFoundException("Could not find a history job with id '" + jobId + "'.", HistoryJob.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessHistoryJobInfoById(job);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobBaseResource.java
| 2
|
请完成以下Java代码
|
public String[] getWhereClauses(List<Object> params)
{
final SponsorNoObject sno = getSponsorNoObject();
final String searchText = getText();
if (sno == null && !Check.isEmpty(searchText, true))
return new String[]{"1=2"};
if (sno == null)
return null;
final Timestamp date = TimeUtil.trunc(Env.getContextAsDate(Env.getCtx(), "#Date"), TimeUtil.TRUNC_DAY);
//
final String whereClause = "EXISTS (SELECT 1 FROM C_Sponsor_Salesrep ssr"
+ " JOIN C_Sponsor sp ON (ssr.C_Sponsor_ID = sp.C_Sponsor_ID)"
+ " WHERE " + bpartnerTableAlias + ".C_BPartner_ID = sp.C_BPartner_ID"
+ " AND ssr.C_Sponsor_Parent_ID = ?"
+ ")"
|
+ " AND ? BETWEEN ssr.Validfrom AND Validto"
+ " AND ssr.C_BPartner_ID > 0";
params.add(sno.getSponsorID());
params.add(date);
return new String[]{whereClause};
}
public IInfoSimple getParent()
{
return parent;
}
protected abstract SponsorNoObject getSponsorNoObject();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPSonsorAbstract.java
| 1
|
请完成以下Java代码
|
protected TenantProfileConfiguration getTenantProfileConfiguration() {
return systemContext.getTenantProfileCache().get(tenantId).getProfileData().getConfiguration();
}
public abstract String getComponentName();
public abstract void start(TbActorCtx context) throws Exception;
public abstract void stop(TbActorCtx context) throws Exception;
public abstract void onPartitionChangeMsg(PartitionChangeMsg msg) throws Exception;
public void onCreated(TbActorCtx context) throws Exception {
start(context);
}
public void onUpdate(TbActorCtx context) throws Exception {
restart(context);
}
public void onActivate(TbActorCtx context) throws Exception {
restart(context);
}
public void onSuspend(TbActorCtx context) throws Exception {
stop(context);
}
public void onStop(TbActorCtx context) throws Exception {
stop(context);
}
private void restart(TbActorCtx context) throws Exception {
stop(context);
start(context);
}
public ScheduledFuture<?> scheduleStatsPersistTick(TbActorCtx context, long statsPersistFrequency) {
return schedulePeriodicMsgWithDelay(context, StatsPersistTick.INSTANCE, statsPersistFrequency, statsPersistFrequency);
}
protected boolean checkMsgValid(TbMsg tbMsg) {
var valid = tbMsg.isValid();
|
if (!valid) {
if (log.isTraceEnabled()) {
log.trace("Skip processing of message: {} because it is no longer valid!", tbMsg);
}
}
return valid;
}
protected void checkComponentStateActive(TbMsg tbMsg) throws RuleNodeException {
if (state != ComponentLifecycleState.ACTIVE) {
log.debug("Component is not active. Current state [{}] for processor [{}][{}] tenant [{}]", state, entityId.getEntityType(), entityId, tenantId);
RuleNodeException ruleNodeException = getInactiveException();
if (tbMsg != null) {
tbMsg.getCallback().onFailure(ruleNodeException);
}
throw ruleNodeException;
}
}
abstract protected RuleNodeException getInactiveException();
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\shared\ComponentMsgProcessor.java
| 1
|
请完成以下Java代码
|
public SetMultimap<TableRecordReference, ExistingLockInfo> getLockInfosByRecordIds(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
return ImmutableSetMultimap.of();
}
final ImmutableSetMultimap.Builder<TableRecordReference, ExistingLockInfo> result = ImmutableSetMultimap.builder();
try (final CloseableReentrantLock ignored = mainLock.open())
{
for (final TableRecordReference recordRef : recordRefs)
{
final LockKey lockKey = LockKey.ofTableRecordReference(recordRef);
final RecordLocks recordLocks = locks.get(lockKey);
if (recordLocks == null)
{
continue;
}
for (final LockInfo lockInfo : recordLocks.getLocks())
|
{
result.put(recordRef, toExistingLockInfo(lockInfo, recordRef));
}
}
return result.build();
}
}
@Value(staticConstructor = "of")
public static class LockKey
{
int adTableId;
int recordId;
public static LockKey ofTableRecordReference(@NonNull final TableRecordReference recordRef) {return of(recordRef.getAD_Table_ID(), recordRef.getRecord_ID());}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\spi\impl\PlainLockDatabase.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CCM_Bundle_Result[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Bundle Result.
@param CCM_Bundle_Result_ID Bundle Result */
public void setCCM_Bundle_Result_ID (int CCM_Bundle_Result_ID)
{
if (CCM_Bundle_Result_ID < 1)
set_ValueNoCheck (COLUMNNAME_CCM_Bundle_Result_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CCM_Bundle_Result_ID, Integer.valueOf(CCM_Bundle_Result_ID));
}
/** Get Bundle Result.
@return Bundle Result */
public int getCCM_Bundle_Result_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CCM_Bundle_Result_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** CCM_Success AD_Reference_ID=319 */
public static final int CCM_SUCCESS_AD_Reference_ID=319;
/** Yes = Y */
public static final String CCM_SUCCESS_Yes = "Y";
/** No = N */
public static final String CCM_SUCCESS_No = "N";
/** Set Is Success.
@param CCM_Success Is Success */
public void setCCM_Success (String CCM_Success)
{
set_Value (COLUMNNAME_CCM_Success, CCM_Success);
}
/** Get Is Success.
@return Is Success */
public String getCCM_Success ()
{
return (String)get_Value(COLUMNNAME_CCM_Success);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
|
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\callcenter\model\X_CCM_Bundle_Result.java
| 1
|
请完成以下Java代码
|
public int getPostingError_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
@Override
public org.compiere.model.I_M_Inventory getReversal()
{
return get_ValueAsPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_M_Inventory.class);
}
@Override
public void setReversal(final org.compiere.model.I_M_Inventory Reversal)
{
set_ValueFromPO(COLUMNNAME_Reversal_ID, org.compiere.model.I_M_Inventory.class, Reversal);
}
@Override
public void setReversal_ID (final int Reversal_ID)
{
if (Reversal_ID < 1)
set_Value (COLUMNNAME_Reversal_ID, null);
else
set_Value (COLUMNNAME_Reversal_ID, Reversal_ID);
}
@Override
public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
@Override
public void setUpdateQty (final @Nullable java.lang.String UpdateQty)
{
set_Value (COLUMNNAME_UpdateQty, UpdateQty);
}
@Override
public java.lang.String getUpdateQty()
{
return get_ValueAsString(COLUMNNAME_UpdateQty);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Inventory.java
| 1
|
请完成以下Java代码
|
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", username=").append(username).append(", password=").append(password).append(", privileges=").append(privileges).append(", organization=").append(organization).append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
result = (prime * result) + ((organization == null) ? 0 : organization.hashCode());
result = (prime * result) + ((password == null) ? 0 : password.hashCode());
result = (prime * result) + ((privileges == null) ? 0 : privileges.hashCode());
result = (prime * result) + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final User other = (User) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (organization == null) {
if (other.organization != null) {
return false;
}
} else if (!organization.equals(other.organization)) {
return false;
}
if (password == null) {
if (other.password != null) {
return false;
|
}
} else if (!password.equals(other.password)) {
return false;
}
if (privileges == null) {
if (other.privileges != null) {
return false;
}
} else if (!privileges.equals(other.privileges)) {
return false;
}
if (username == null) {
if (other.username != null) {
return false;
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\User.java
| 1
|
请完成以下Java代码
|
public void addActionListener(ActionListener listener)
{
// m_text.addActionListener(listener);
} // addActionListener
/**
* Action Listener - start dialog
* @param e Event
*/
@Override
public void actionPerformed(ActionEvent e)
{
if (!m_button.isEnabled())
return;
throw new AdempiereException("legacy feature removed");
}
/**
* Property Change Listener
* @param evt event
*/
@Override
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
|
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
@Override
public boolean isAutoCommit()
{
return true;
}
} // VAssignment
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAssignment.java
| 1
|
请完成以下Java代码
|
public FileStore getFileStore(Path path) throws IOException {
NestedPath nestedPath = NestedPath.cast(path);
nestedPath.assertExists();
return new NestedFileStore(nestedPath.getFileSystem());
}
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException {
Path jarPath = getJarPath(path);
jarPath.getFileSystem().provider().checkAccess(jarPath, modes);
}
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().getFileAttributeView(jarPath, type, options);
}
@Override
public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options)
throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, type, options);
}
|
@Override
public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException {
Path jarPath = getJarPath(path);
return jarPath.getFileSystem().provider().readAttributes(jarPath, attributes, options);
}
protected Path getJarPath(Path path) {
return NestedPath.cast(path).getJarPath();
}
@Override
public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException {
throw new ReadOnlyFileSystemException();
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileSystemProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public FlywayBookProperties firstFlywayProperties() {
return new FlywayBookProperties();
}
@Primary
@Bean(name = "dataSourceBooksDb")
@ConfigurationProperties("app.datasource.ds1")
public HikariDataSource firstDataSource(@Qualifier("configBooksDb") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@Primary
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway firstFlyway(@Qualifier("configFlywayBooksDb") FlywayBookProperties properties,
@Qualifier("dataSourceBooksDb") HikariDataSource dataSource) {
return Flyway.configure()
.dataSource(dataSource)
.locations(properties.getLocation())
.load();
}
// second database, authorsdb
@Bean(name = "configAuthorsDb")
@ConfigurationProperties("app.datasource.ds2")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "configFlywayAuthorsDb")
|
public FlywayAuthorProperties secondFlywayProperties() {
return new FlywayAuthorProperties();
}
@Bean(name = "dataSourceAuthorsDb")
@ConfigurationProperties("app.datasource.ds2")
public HikariDataSource secondDataSource(@Qualifier("configAuthorsDb") DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().type(HikariDataSource.class)
.build();
}
@FlywayDataSource
@Bean(initMethod = "migrate")
public Flyway secondFlyway(@Qualifier("configFlywayAuthorsDb") FlywayAuthorProperties properties,
@Qualifier("dataSourceAuthorsDb") HikariDataSource dataSource) {
return Flyway.configure()
.dataSource(dataSource)
.locations(properties.getLocation())
.load();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayMySQLTwoDatabases\src\main\java\com\bookstore\config\ConfigureDataSources.java
| 2
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDocumentation() {
return documentation;
}
public void setDocumentation(String documentation) {
this.documentation = documentation;
}
public List<ActivitiListener> getExecutionListeners() {
return executionListeners;
}
public void setExecutionListeners(List<ActivitiListener> executionListeners) {
this.executionListeners = executionListeners;
}
@JsonIgnore
public FlowElementsContainer getParentContainer() {
return parentContainer;
}
@JsonIgnore
public SubProcess getSubProcess() {
|
SubProcess subProcess = null;
if (parentContainer instanceof SubProcess) {
subProcess = (SubProcess) parentContainer;
}
return subProcess;
}
public void setParentContainer(FlowElementsContainer parentContainer) {
this.parentContainer = parentContainer;
}
public abstract FlowElement clone();
public void setValues(FlowElement otherElement) {
super.setValues(otherElement);
setName(otherElement.getName());
setDocumentation(otherElement.getDocumentation());
executionListeners = new ArrayList<ActivitiListener>();
if (otherElement.getExecutionListeners() != null && !otherElement.getExecutionListeners().isEmpty()) {
for (ActivitiListener listener : otherElement.getExecutionListeners()) {
executionListeners.add(listener.clone());
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FlowElement.java
| 1
|
请完成以下Java代码
|
protected final ProcessPreconditionsResolution acceptIfOrderLinesNotInGroup(final IProcessPreconditionsContext context)
{
final Set<OrderLineId> orderLineIds = getSelectedOrderLineIds(context);
if (orderLineIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Select some order lines");
}
final Set<GroupId> groupIds = groupsRepo.extractGroupIdsFromOrderLineIds(orderLineIds);
if (!groupIds.isEmpty())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Select lines which are not already grouped");
}
return ProcessPreconditionsResolution.accept();
}
private static final Set<OrderLineId> getSelectedOrderLineIds(final IProcessPreconditionsContext context)
{
return context.getSelectedIncludedRecords()
.stream()
.filter(recordRef -> I_C_OrderLine.Table_Name.equals(recordRef.getTableName()))
|
.map(recordRef -> OrderLineId.ofRepoId(recordRef.getRecord_ID()))
.collect(ImmutableSet.toImmutableSet());
}
protected final Set<OrderLineId> getSelectedOrderLineIds()
{
return getSelectedIncludedRecordIds(I_C_OrderLine.class)
.stream()
.map(OrderLineId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
protected final List<I_C_OrderLine> getSelectedOrderLines()
{
return getSelectedIncludedRecords(I_C_OrderLine.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\process\OrderCompensationGroupProcess.java
| 1
|
请完成以下Java代码
|
public void setCompleted(Boolean completed) {
this.completed = completed;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class)
public void setTenantIdIn(List<String> tenantIds) {
this.tenantIds = tenantIds;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
protected HistoricBatchQuery createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricBatchQuery();
}
protected void applyFilters(HistoricBatchQuery query) {
if (batchId != null) {
query.batchId(batchId);
}
if (type != null) {
query.type(type);
}
if (completed != null) {
query.completed(completed);
}
if (Boolean.TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
|
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
}
protected void applySortBy(HistoricBatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) {
query.orderById();
}
if (sortBy.equals(SORT_BY_BATCH_START_TIME_VALUE)) {
query.orderByStartTime();
}
if (sortBy.equals(SORT_BY_BATCH_END_TIME_VALUE)) {
query.orderByEndTime();
}
if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\HistoricBatchQueryDto.java
| 1
|
请完成以下Java代码
|
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(USER_NOTIFICATIONS_TOPIC);
}
private UserId getNotificationRecipientUserId(final I_M_Movement movement)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofCode(movement.getDocStatus());
if (docStatus.isReversedOrVoided())
{
final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user
if (currentUserId > 0)
{
return UserId.ofRepoId(currentUserId);
|
}
return UserId.ofRepoId(movement.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(movement.getCreatedBy());
}
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\movement\event\MovementUserNotificationsProducer.java
| 1
|
请完成以下Java代码
|
public final String toString(String codeset)
{
StringBuffer sb = new StringBuffer();
if (doctype != null)
sb.append (doctype.toString(getCodeset()));
sb.append (html.toString(getCodeset()));
return(sb.toString());
}
/**
Allows the document to be cloned.
Doesn't return an instance of document returns instance of html.
|
NOTE: If you have a doctype set, then it will be lost. Feel free
to submit a patch to fix this. It isn't trivial.
*/
public Object clone()
{
return(html.clone());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlDocument.java
| 1
|
请完成以下Java代码
|
public static void downloadWithApacheCommons(String url, String localFilename) {
int CONNECT_TIMEOUT = 10000;
int READ_TIMEOUT = 10000;
try {
FileUtils.copyURLToFile(new URI(url).toURL(), new File(localFilename), CONNECT_TIMEOUT, READ_TIMEOUT);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
public static void downloadWithAHC(String url, String localFilename) throws ExecutionException, InterruptedException, IOException {
FileOutputStream stream = new FileOutputStream(localFilename);
AsyncHttpClient client = Dsl.asyncHttpClient();
client.prepareGet(url)
.execute(new AsyncCompletionHandler<FileOutputStream>() {
@Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
stream.getChannel()
.write(bodyPart.getBodyByteBuffer());
return State.CONTINUE;
}
@Override
public FileOutputStream onCompleted(Response response) throws Exception {
return stream;
}
})
|
.get();
stream.getChannel().close();
client.close();
}
public static void downloadWithApacheHttpClient(String url, String localFileName) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(url);
httpClient.execute(httpGet, classicHttpResponse -> {
int code = classicHttpResponse.getCode();
if (code == 200) {
HttpEntity entity = classicHttpResponse.getEntity();
if (entity != null) {
try (InputStream inputStream = entity.getContent();
FileOutputStream fileOutputStream = new FileOutputStream(localFileName)) {
byte[] dataBuffer = new byte[1024];
int bytesRead;
while((bytesRead = inputStream.read(dataBuffer)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
}
}
EntityUtils.consume(entity);
}
return classicHttpResponse;
});
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking\src\main\java\com\baeldung\download\FileDownload.java
| 1
|
请完成以下Java代码
|
private ProcessDefinition getProcessDefinitionByProcessDefinitionId(
String processDefinitionId,
DeploymentManager deploymentCache
) {
ProcessDefinition processDefinition = null;
if (processDefinitionId != null) {
processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
}
return processDefinition;
}
private ProcessDefinition getProcessDefinitionByProcessDefinitionKey(
String processDefinitionKey,
DeploymentManager deploymentCache
) {
ProcessDefinition processDefinition = null;
processDefinition = deploymentCache.findDeployedLatestProcessDefinitionByKey(processDefinitionKey);
if (processDefinition == null) {
throw new ActivitiObjectNotFoundException(
"No process definition found for key '" + processDefinitionKey + "'",
ProcessDefinition.class
);
}
return processDefinition;
}
private ProcessDefinition getProcessDefinitionByProcessDefinitionKeyAndTenantId(
String processDefinitionKey,
String tenantId,
DeploymentManager deploymentCache
) {
|
ProcessDefinition processDefinition = null;
if (
processDefinitionKey != null &&
tenantId != null &&
!ProcessEngineConfiguration.NO_TENANT_ID.equals(tenantId)
) {
processDefinition = deploymentCache.findDeployedLatestProcessDefinitionByKeyAndTenantId(
processDefinitionKey,
tenantId
);
}
return processDefinition;
}
private boolean hasNoTenant(String tenantId) {
return tenantId == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(tenantId);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ProcessDefinitionRetriever.java
| 1
|
请完成以下Java代码
|
public int getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(int state) {
this.suspensionState = state;
}
public Long getOverridingJobPriority() {
return jobPriority;
}
public void setJobPriority(Long jobPriority) {
this.jobPriority = jobPriority;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getDeploymentId() {
return deploymentId;
}
|
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
return referenceIdAndClass;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobDefinitionEntity.java
| 1
|
请完成以下Java代码
|
public class SenderServiceGuava<T extends Sender> {
TypeToken<T> typeToken;
TypeToken<T> typeTokenAnonymous = new TypeToken<T>(getClass()) {
};
public SenderServiceGuava() {
}
public SenderServiceGuava(Class<T> clazz) {
this.typeToken = TypeToken.of(clazz);
}
public T createInstance() {
try {
return (T) typeToken.getRawType()
.getDeclaredConstructor()
.newInstance();
|
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public T createInstanceAnonymous() {
try {
return (T) typeTokenAnonymous.getRawType()
.getDeclaredConstructor()
.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-syntax-3\src\main\java\com\baeldung\generics\SenderServiceGuava.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EntityService {
private final IFooRepo foos;
private final IBarRepo bars;
private final IRooRepo roos;
@Autowired
public EntityService(IFooRepo foos, IBarRepo bars, IRooRepo roos) {
this.foos = foos;
this.bars = bars;
this.roos = roos;
}
public void create(final Foo entity) {
foos.save(entity);
}
public void create(final Roo entity) {
roos.save(entity);
}
public List<Foo> findAll() {
return foos.findAll();
}
|
public Bar findOneBar(long id) {
return bars.findById(id)
.orElseThrow();
}
public Foo findOneFoo(final long id) {
return foos.findById(id)
.orElseThrow();
}
public Roo findOneRoo(final long id) {
return roos.findById(id)
.orElseThrow();
}
}
|
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\service\EntityService.java
| 2
|
请完成以下Java代码
|
public Set<Object> keySet() {
throw new FlowableException("unsupported operation on configuration beans");
// List<String> beanNames =
// Arrays.asList(beanFactory.getBeanDefinitionNames());
// return new HashSet<Object>(beanNames);
}
@Override
public void clear() {
throw new FlowableException("can't clear configuration beans");
}
@Override
public boolean containsValue(Object value) {
throw new FlowableException("can't search values in configuration beans");
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public boolean isEmpty() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Object put(Object key, Object value) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
|
public void putAll(Map<? extends Object, ? extends Object> m) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Object remove(Object key) {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public int size() {
throw new FlowableException("unsupported operation on configuration beans");
}
@Override
public Collection<Object> values() {
throw new FlowableException("unsupported operation on configuration beans");
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\SpringBeanFactoryProxyMap.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<com.bookstore.transform.dto.AuthorDto> fetchAuthorsWithBooksViaArrayOfObjectsAndTransformToDto() {
List<Object[]> authors = authorRepository.findByViaArrayOfObjectsWithIds();
List<com.bookstore.transform.dto.AuthorDto> authorsDto = authorTransformer.transform(authors);
System.out.println("\nResult set:");
authors.forEach(a -> System.out.println(Arrays.toString(a)));
briefOverviewOfPersistentContextContent();
return authorsDto;
}
@Transactional(readOnly = true)
public List<com.bookstore.jdbcTemplate.dto.AuthorDto> fetchAuthorsWithBooksViaJdbcTemplateToDto() {
List<com.bookstore.jdbcTemplate.dto.AuthorDto> authors = authorExtractor.extract();
System.out.println("\nResult set:");
authors.forEach(a -> {
System.out.println("\n\n" + a.getName() + ", " + a.getGenre());
a.getBooks().forEach(b -> System.out.print(b.getTitle() + ", "));
});
briefOverviewOfPersistentContextContent();
return authors;
}
private void briefOverviewOfPersistentContextContent() {
org.hibernate.engine.spi.PersistenceContext persistenceContext = getPersistenceContext();
int managedEntities = persistenceContext.getNumberOfManagedEntities();
int collectionEntriesSize = persistenceContext.getCollectionEntriesSize();
|
System.out.println("\n-----------------------------------");
System.out.println("Total number of managed entities: " + managedEntities);
System.out.println("Total number of collection entries: " + collectionEntriesSize + "\n");
// getEntitiesByKey() will be removed and probably replaced with #iterateEntities()
Map<EntityKey, Object> entitiesByKey = persistenceContext.getEntitiesByKey();
entitiesByKey.forEach((key, value) -> System.out.println(key + ":" + value));
for (Object entry : entitiesByKey.values()) {
EntityEntry ee = persistenceContext.getEntry(entry);
System.out.println(
"Entity name: " + ee.getEntityName()
+ " | Status: " + ee.getStatus()
+ " | State: " + Arrays.toString(ee.getLoadedState()));
};
System.out.println("\n-----------------------------------\n");
}
private org.hibernate.engine.spi.PersistenceContext getPersistenceContext() {
SharedSessionContractImplementor sharedSession = entityManager.unwrap(
SharedSessionContractImplementor.class
);
return sharedSession.getPersistenceContext();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootProjectionAndCollections\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getBlockIfFullTimeout() {
return this.blockIfFullTimeout;
}
public void setBlockIfFullTimeout(Duration blockIfFullTimeout) {
this.blockIfFullTimeout = blockIfFullTimeout;
}
public Duration getIdleTimeout() {
return this.idleTimeout;
}
public void setIdleTimeout(Duration idleTimeout) {
this.idleTimeout = idleTimeout;
}
public int getMaxConnections() {
return this.maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public int getMaxSessionsPerConnection() {
return this.maxSessionsPerConnection;
}
public void setMaxSessionsPerConnection(int maxSessionsPerConnection) {
this.maxSessionsPerConnection = maxSessionsPerConnection;
}
|
public Duration getTimeBetweenExpirationCheck() {
return this.timeBetweenExpirationCheck;
}
public void setTimeBetweenExpirationCheck(Duration timeBetweenExpirationCheck) {
this.timeBetweenExpirationCheck = timeBetweenExpirationCheck;
}
public boolean isUseAnonymousProducers() {
return this.useAnonymousProducers;
}
public void setUseAnonymousProducers(boolean useAnonymousProducers) {
this.useAnonymousProducers = useAnonymousProducers;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\JmsPoolConnectionFactoryProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class MainApplication {
private final BookstoreService bookstoreService;
public MainApplication(BookstoreService bookstoreService) {
this.bookstoreService = bookstoreService;
}
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
|
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("Register new author ...");
bookstoreService.registerAuthor();
Thread.sleep(5000);
System.out.println("Update an author ...");
bookstoreService.updateAuthor();
Thread.sleep(5000);
System.out.println("Update books of an author ...");
bookstoreService.updateBooks();
};
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\MainApplication.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public PaymentStatusResponse getPaymentStatus(String paymentNumber) throws Exception
{
PaymentResponse paymentResponse = new PaymentResponse();
paymentResponse.setRegPayNum(paymentNumber);
paymentResponse.setShopToken(shopToken);
StringBuilder requestBody = new StringBuilder(paymentResponse.getRegPayNum() + '&');
requestBody.append(paymentResponse.getShopToken()).append('&');
requestBody.append(secKey);
paymentResponse.setSign(MD5(MD5(requestBody.toString()).toUpperCase()).toUpperCase());
return new Gson().fromJson(cKassaApi.call("check/payment/state", new Gson().toJson(paymentResponse)), PaymentStatusResponse.class);
}
private String MD5(String str){
MessageDigest md5;
StringBuffer nextString = new StringBuffer();
try {
md5 = MessageDigest.getInstance("md5");
|
md5.reset();
md5.update(str.getBytes());
byte messageDigest[] = md5.digest();
for(int i=0; i< messageDigest.length; i++){
nextString.append(Integer.toHexString(0xFF & messageDigest[i] | 0x100).substring(1, 3).toUpperCase());
}
}
catch (NoSuchAlgorithmException e){
return e.toString();
}
return nextString.toString();
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\order\payment\PaymentService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
@Override
public int getDatabase() {
return database;
}
};
}
}
/**
* Redis sentinel configuration.
*/
interface Sentinel {
/**
* Database index used by the connection factory.
* @return the database index used by the connection factory
*/
int getDatabase();
/**
* Name of the Redis server.
* @return the name of the Redis server
*/
String getMaster();
/**
* List of nodes.
* @return the list of nodes
*/
List<Node> getNodes();
/**
* Login username for authenticating with sentinel(s).
* @return the login username for authenticating with sentinel(s) or {@code null}
*/
@Nullable String getUsername();
/**
* Password for authenticating with sentinel(s).
* @return the password for authenticating with sentinel(s) or {@code null}
*/
@Nullable String getPassword();
}
/**
* Redis cluster configuration.
*/
|
interface Cluster {
/**
* Nodes to bootstrap from. This represents an "initial" list of cluster nodes and
* is required to have at least one entry.
* @return nodes to bootstrap from
*/
List<Node> getNodes();
}
/**
* Redis master replica configuration.
*/
interface MasterReplica {
/**
* Static nodes to use. This represents the full list of cluster nodes and is
* required to have at least one entry.
* @return the nodes to use
*/
List<Node> getNodes();
}
/**
* A node in a sentinel or cluster configuration.
*
* @param host the hostname of the node
* @param port the port of the node
*/
record Node(String host, int port) {
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionDetails.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 setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsToleranceExceeded (final boolean IsToleranceExceeded)
{
set_Value (COLUMNNAME_IsToleranceExceeded, IsToleranceExceeded);
}
@Override
public boolean isToleranceExceeded()
{
return get_ValueAsBoolean(COLUMNNAME_IsToleranceExceeded);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setPP_Order_Weighting_RunCheck_ID (final int PP_Order_Weighting_RunCheck_ID)
{
if (PP_Order_Weighting_RunCheck_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, PP_Order_Weighting_RunCheck_ID);
}
@Override
public int getPP_Order_Weighting_RunCheck_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_RunCheck_ID);
}
@Override
public org.eevolution.model.I_PP_Order_Weighting_Run getPP_Order_Weighting_Run()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class);
}
@Override
|
public void setPP_Order_Weighting_Run(final org.eevolution.model.I_PP_Order_Weighting_Run PP_Order_Weighting_Run)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class, PP_Order_Weighting_Run);
}
@Override
public void setPP_Order_Weighting_Run_ID (final int PP_Order_Weighting_Run_ID)
{
if (PP_Order_Weighting_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, PP_Order_Weighting_Run_ID);
}
@Override
public int getPP_Order_Weighting_Run_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID);
}
@Override
public void setWeight (final BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_RunCheck.java
| 1
|
请完成以下Java代码
|
public void save(final Collection<IQualityInspectionLine> qiLines)
{
if (qiLines == null || qiLines.isEmpty())
{
return;
}
final List<IQualityInspectionLine> qiLinesToSave = new ArrayList<>(qiLines);
//
// Discard not accepted lines and then sort them
if (reportLinesSorter != null)
{
reportLinesSorter.filterAndSort(qiLinesToSave);
}
//
// Iterate lines and save one by one
for (final IQualityInspectionLine qiLine : qiLinesToSave)
{
save(qiLine);
}
}
/**
* Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} line).
*
* @param qiLine
*/
private void save(final IQualityInspectionLine qiLine)
{
Check.assumeNotNull(qiLine, "qiLine not null");
final I_PP_Order ppOrder = getPP_Order();
final int seqNo = _seqNoNext;
|
BigDecimal qty = qiLine.getQty();
if (qty != null && qiLine.isNegateQtyInReport())
{
qty = qty.negate();
}
//
// Create report line
final I_PP_Order_Report reportLine = InterfaceWrapperHelper.newInstance(I_PP_Order_Report.class, getContext());
reportLine.setPP_Order(ppOrder);
reportLine.setAD_Org_ID(ppOrder.getAD_Org_ID());
reportLine.setSeqNo(seqNo);
reportLine.setIsActive(true);
// reportLine.setQualityInspectionLineType(qiLine.getQualityInspectionLineType());
reportLine.setProductionMaterialType(qiLine.getProductionMaterialType());
reportLine.setM_Product(qiLine.getM_Product());
reportLine.setName(qiLine.getName());
reportLine.setQty(qty);
reportLine.setC_UOM(qiLine.getC_UOM());
reportLine.setPercentage(qiLine.getPercentage());
reportLine.setQtyProjected(qiLine.getQtyProjected());
reportLine.setComponentType(qiLine.getComponentType());
reportLine.setVariantGroup(qiLine.getVariantGroup());
//
// Save report line
InterfaceWrapperHelper.save(reportLine);
_createdReportLines.add(reportLine);
_seqNoNext += 10;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderReportWriter.java
| 1
|
请完成以下Java代码
|
public Integer getAge() {
return age;
}
public void setAge(final Integer age) {
this.age = age;
}
String getColor() {
return color;
}
public void setColor(final String color) {
this.color = color;
}
Integer getHealty() {
return healty;
}
void setHealty(final Integer healty) {
this.healty = healty;
}
public void turnOnPc() {
System.out.println("Computer turned on");
}
public void turnOffPc() {
System.out.println("Computer turned off");
}
public Double calculateValue(Double initialValue) {
return initialValue / 1.50;
}
@Override
public String toString() {
return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
|
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Computer computer = (Computer) o;
return (age != null ? age.equals(computer.age) : computer.age == null) && (color != null ? color.equals(computer.color) : computer.color == null);
}
@Override
public int hashCode() {
int result = age != null ? age.hashCode() : 0;
result = 31 * result + (color != null ? color.hashCode() : 0);
return result;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\doublecolon\Computer.java
| 1
|
请完成以下Java代码
|
public class InvoiceCandidatesTableModel extends AnnotatedTableModel<IInvoiceCandidateRow>
{
private static final long serialVersionUID = 1L;
private static final Predicate<IInvoiceCandidateRow> PREDICATE_Selected = new Predicate<IInvoiceCandidateRow>()
{
@Override
public boolean apply(IInvoiceCandidateRow row)
{
return row.isSelected();
}
};
public InvoiceCandidatesTableModel()
{
super(IInvoiceCandidateRow.class);
}
public final List<IInvoiceCandidateRow> getRowsSelected()
{
return FluentIterable.from(getRowsInnerList())
.filter(PREDICATE_Selected)
.toList();
}
public final Set<Integer> getSelectedInvoiceCandidateIds()
{
final Set<Integer> invoiceCandidateIds = new HashSet<>();
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final int invoiceCandidateId = row.getC_Invoice_Candidate_ID();
if (invoiceCandidateId <= 0)
{
continue;
}
invoiceCandidateIds.add(invoiceCandidateId);
}
return invoiceCandidateIds;
}
public final void selectRowsByInvoiceCandidateIds(final Collection<Integer> invoiceCandidateIds)
{
if (invoiceCandidateIds == null || invoiceCandidateIds.isEmpty())
{
return;
}
final List<IInvoiceCandidateRow> rowsChanged = new ArrayList<>();
for (final IInvoiceCandidateRow row : getRowsInnerList())
{
// Skip if already selected
if (row.isSelected())
{
continue;
}
if (invoiceCandidateIds.contains(row.getC_Invoice_Candidate_ID()))
{
row.setSelected(true);
rowsChanged.add(row);
}
|
}
fireTableRowsUpdated(rowsChanged);
}
/** @return latest {@link IInvoiceCandidateRow#getDocumentDate()} of selected rows */
public final Date getLatestDocumentDateOfSelectedRows()
{
Date latestDocumentDate = null;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final Date documentDate = row.getDocumentDate();
latestDocumentDate = TimeUtil.max(latestDocumentDate, documentDate);
}
return latestDocumentDate;
}
/**
* @return latest {@link IInvoiceCandidateRow#getDateAcct()} of selected rows
*/
public final Date getLatestDateAcctOfSelectedRows()
{
Date latestDateAcct = null;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final Date dateAcct = row.getDateAcct();
latestDateAcct = TimeUtil.max(latestDateAcct, dateAcct);
}
return latestDateAcct;
}
public final BigDecimal getTotalNetAmtToInvoiceOfSelectedRows()
{
BigDecimal totalNetAmtToInvoiced = BigDecimal.ZERO;
for (final IInvoiceCandidateRow row : getRowsSelected())
{
final BigDecimal netAmtToInvoice = row.getNetAmtToInvoice();
totalNetAmtToInvoiced = totalNetAmtToInvoiced.add(netAmtToInvoice);
}
return totalNetAmtToInvoiced;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceCandidatesTableModel.java
| 1
|
请完成以下Java代码
|
public String getFoos2(@RequestParam(required = false) String id){
return "ID: " + id;
}
@GetMapping("/api/foosOptional")
@ResponseBody
public String getFoosOptional(@RequestParam Optional<String> id){
return "ID: " + id.orElseGet(() -> "not provided");
}
@GetMapping("/api/foos3")
@ResponseBody
public String getFoos3(@RequestParam(defaultValue = "test") String id){
return "ID: " + id;
}
@PostMapping("/api/foos1")
@ResponseBody
public String updateFoos(@RequestParam Map<String,String> allParams){
return "Parameters are " + allParams.entrySet();
}
@GetMapping("/api/foos4")
@ResponseBody
public String getFoos4(@RequestParam List<String> id){
return "IDs are " + id;
}
|
@GetMapping("/foos/{id}")
@ResponseBody
public String getFooById(@PathVariable String id){
return "ID: " + id;
}
@GetMapping("/foos")
@ResponseBody
public String getFooByIdUsingQueryParam(@RequestParam String id){
return "ID: " + id;
}
@GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"})
@ResponseBody
public String getFooByOptionalId(@PathVariable(required = false) String id){
return "ID: " + id;
}
@GetMapping("/myfoos/optionalParam")
@ResponseBody
public String getFooByOptionalIdUsingQueryParam(@RequestParam(required = false) String id){
return "ID: " + id;
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\requestparam\RequestParamController.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/javastack
username: root
password: 12345678
mybatis-
|
plus:
type-aliases-package: cn.javastack.springboot.mybatisplus.entity
|
repos\spring-boot-best-practice-master\spring-boot-mybatis-plus\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void init(FilterConfig filterConfig) {
ClassPathResource classPathResource = new ClassPathResource("web/notTrustDir.html");
try {
classPathResource.getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
this.notTrustDirView = new String(bytes, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("加载notTrustDir.html失败", e);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String url = WebUtils.getSourceUrl(request);
if (!allowPreview(url)) {
response.getWriter().write(this.notTrustDirView);
response.getWriter().close();
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
private boolean allowPreview(String urlPath) {
|
//判断URL是否合法
if(!StringUtils.hasText(urlPath) || !WebUtils.isValidUrl(urlPath)) {
return false ;
}
try {
URL url = WebUtils.normalizedURL(urlPath);
if ("file".equals(url.getProtocol().toLowerCase(Locale.ROOT))) {
String filePath = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8.name());
if (OSUtils.IS_OS_WINDOWS) {
filePath = filePath.replaceAll("/", "\\\\");
}
return filePath.startsWith(ConfigConstants.getFileDir()) || filePath.startsWith(ConfigConstants.getLocalPreviewDir());
}
return true;
} catch (IOException | GalimatiasParseException e) {
logger.error("解析URL异常,url:{}", urlPath, e);
return false;
}
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\web\filter\TrustDirFilter.java
| 1
|
请完成以下Java代码
|
public TbMsgBuilder correlationId(UUID correlationId) {
this.correlationId = correlationId;
return this;
}
public TbMsgBuilder partition(Integer partition) {
this.partition = partition;
return this;
}
public TbMsgBuilder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = new CopyOnWriteArrayList<>(previousCalculatedFieldIds);
return this;
}
public TbMsgBuilder ctx(TbMsgProcessingCtx ctx) {
this.ctx = ctx;
return this;
}
public TbMsgBuilder callback(TbMsgCallback callback) {
|
this.callback = callback;
return this;
}
public TbMsg build() {
return new TbMsg(queueName, id, ts, internalType, type, originator, customerId, metaData, dataType, data, ruleChainId, ruleNodeId, correlationId, partition, previousCalculatedFieldIds, ctx, callback);
}
public String toString() {
return "TbMsg.TbMsgBuilder(queueName=" + this.queueName + ", id=" + this.id + ", ts=" + this.ts +
", type=" + this.type + ", internalType=" + this.internalType + ", originator=" + this.originator +
", customerId=" + this.customerId + ", metaData=" + this.metaData + ", dataType=" + this.dataType +
", data=" + this.data + ", ruleChainId=" + this.ruleChainId + ", ruleNodeId=" + this.ruleNodeId +
", correlationId=" + this.correlationId + ", partition=" + this.partition + ", previousCalculatedFields=" + this.previousCalculatedFieldIds +
", ctx=" + this.ctx + ", callback=" + this.callback + ")";
}
}
}
|
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\TbMsg.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ImmutableList<CommissionShare> createCommissionShares(@NonNull final CreateCommissionSharesRequest request)
{
try
{
final ImmutableList<CommissionType> commissionTypes = CollectionUtils.extractDistinctElements(
request.getConfigs(),
CommissionConfig::getCommissionType);
final ImmutableList.Builder<CommissionShare> result = ImmutableList.builder();
for (final CommissionType commissionType : commissionTypes)
{
try (final MDCCloseable ignore = MDC.putCloseable("commissionType", commissionType.name()))
{
final CommissionAlgorithm algorithm;
algorithm = createAlgorithmInstance(commissionType);
// invoke the algorithm
final ImmutableList<CommissionShare> sharesFromAlgorithm = algorithm.createCommissionShares(request);
result.addAll(sharesFromAlgorithm);
}
}
return result.build();
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e).setParameter("request", request); // augment&rethrow
}
}
public void updateCommissionShares(@NonNull final CommissionTriggerChange change)
{
try
{
final ImmutableList<CommissionType> commissionTypes = CollectionUtils.extractDistinctElements(
change.getInstanceToUpdate().getShares(),
share -> share.getConfig().getCommissionType());
for (final CommissionType commissionType : commissionTypes)
{
try (final MDCCloseable ignore = MDC.putCloseable("commissionType", commissionType.name()))
{
final CommissionAlgorithm algorithm = createAlgorithmInstance(commissionType);
// invoke the algorithm
algorithm.applyTriggerChangeToShares(change);
}
}
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e).setParameter("change", change);
}
}
|
@NonNull
private CommissionAlgorithm createAlgorithmInstance(@NonNull final CommissionType commissionType)
{
final CommissionAlgorithmFactory commissionAlgorithmFactory = commissionType2AlgorithmFactory.get(commissionType);
if (commissionAlgorithmFactory != null)
{
return commissionAlgorithmFactory.instantiateAlgorithm();
}
final Class<? extends CommissionAlgorithm> algorithmClass = commissionType.getAlgorithmClass();
final CommissionAlgorithm algorithm;
try
{
algorithm = algorithmClass.newInstance();
}
catch (InstantiationException | IllegalAccessException e)
{
throw new AdempiereException("Unable to instantiate commission algorithm from class " + algorithmClass)
.appendParametersToMessage()
.setParameter("commissionType", commissionType);
}
return algorithm;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\CommissionAlgorithmInvoker.java
| 2
|
请完成以下Java代码
|
public static WorkflowLauncherId ofParts(
@NonNull final MobileApplicationId applicationId,
final Object... parts)
{
if (parts == null || parts.length <= 0)
{
throw new AdempiereException("more than one part is required");
}
return new WorkflowLauncherId(
applicationId,
Stream.of(parts)
.map(part -> part != null ? part.toString() : "")
.collect(ImmutableList.toImmutableList()));
}
@JsonCreator
public static WorkflowLauncherId ofString(@NonNull final String stringRepresentation)
{
MobileApplicationId applicationId = null;
final ImmutableList.Builder<String> parts = ImmutableList.builder();
for (final String part : SPLITTER.split(stringRepresentation))
{
if (applicationId == null)
{
applicationId = MobileApplicationId.ofString(part);
}
else
{
parts.add(part);
}
}
if (applicationId == null)
{
throw new AdempiereException("Invalid string: " + stringRepresentation);
}
final WorkflowLauncherId result = new WorkflowLauncherId(applicationId, parts.build());
result._stringRepresentation = stringRepresentation;
return result;
}
@Getter
private final MobileApplicationId applicationId;
private final ImmutableList<String> parts;
private String _stringRepresentation;
private WorkflowLauncherId(
@NonNull final MobileApplicationId applicationId,
@NonNull final ImmutableList<String> parts)
{
this.applicationId = applicationId;
this.parts = parts;
}
@Override
@Deprecated
|
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
String stringRepresentation = _stringRepresentation;
if (stringRepresentation == null)
{
_stringRepresentation = stringRepresentation = JOINER
.join(Iterables.concat(
ImmutableList.of(applicationId.getAsString()),
parts));
}
return stringRepresentation;
}
public String getPartAsString(final int index)
{
return parts.get(index);
}
public Integer getPartAsInt(final int index)
{
return NumberUtils.asIntegerOrNull(getPartAsString(index));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLauncherId.java
| 1
|
请完成以下Java代码
|
private static void infoOfChildProcess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
|
}
private static void infoOfExitCallback() throws IOException, InterruptedException, ExecutionException {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.pid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
log.info("Alive: " + processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.pid());
});
}
}
|
repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\java9\process\ProcessAPIEnhancements.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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 IReplicationAccessContext getDefaultIReplicationAccessContext()
{
final int limit = IQuery.NO_LIMIT;
final boolean isApplyAccessFilter = false;
return new ReplicationAccessContext(limit, isApplyAccessFilter); // TODO hardcoded
}
// metas: end
private static int getDisplayType(@NonNull final MColumn column, @NonNull final I_EXP_FormatLine formatLine)
{
if (formatLine.getAD_Reference_Override_ID() > 0)
{
return formatLine.getAD_Reference_Override_ID();
}
return column.getAD_Reference_ID();
}
private void createAttachment(@NonNull final CreateAttachmentRequest request)
{
try
{
final String documentAsString = writeDocumentToString(outDocument);
final byte[] data = documentAsString.getBytes();
final AttachmentEntryService attachmentEntryService = SpringContextHolder.instance.getBean(AttachmentEntryService.class);
attachmentEntryService.createNewAttachment(request.getTarget(), request.getAttachmentName(), data);
}
|
catch (final Exception exception)
{
throw AdempiereException.wrapIfNeeded(exception);
}
}
private static String writeDocumentToString(@NonNull final Document document) throws TransformerException
{
final TransformerFactory tranFactory = TransformerFactory.newInstance();
final Transformer aTransformer = tranFactory.newTransformer();
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
final Source src = new DOMSource(document);
final Writer writer = new StringWriter();
final Result dest2 = new StreamResult(writer);
aTransformer.transform(src, dest2);
return writer.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\process\rpl\exp\ExportHelper.java
| 1
|
请完成以下Java代码
|
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
if (this.beanFactory instanceof ListableBeanFactory && getClass() == TypeExcludeFilter.class) {
for (TypeExcludeFilter delegate : getDelegates()) {
if (delegate.match(metadataReader, metadataReaderFactory)) {
return true;
}
}
}
return false;
}
private Collection<TypeExcludeFilter> getDelegates() {
Collection<TypeExcludeFilter> delegates = this.delegates;
if (delegates == null) {
delegates = ((ListableBeanFactory) this.beanFactory).getBeansOfType(TypeExcludeFilter.class).values();
this.delegates = delegates;
|
}
return delegates;
}
@Override
public boolean equals(@Nullable Object obj) {
throw new IllegalStateException("TypeExcludeFilter " + getClass() + " has not implemented equals");
}
@Override
public int hashCode() {
throw new IllegalStateException("TypeExcludeFilter " + getClass() + " has not implemented hashCode");
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\TypeExcludeFilter.java
| 1
|
请完成以下Java代码
|
public MimeMappings getMimeMappings() {
return this.mimeMappings;
}
public @Nullable File getDocumentRoot() {
return this.documentRoot;
}
public void setDocumentRoot(@Nullable File documentRoot) {
this.documentRoot = documentRoot;
}
public List<? extends ServletContextInitializer> getInitializers() {
return this.initializers;
}
public void setJsp(Jsp jsp) {
this.jsp = jsp;
}
public Jsp getJsp() {
return this.jsp;
}
public Map<Locale, Charset> getLocaleCharsetMappings() {
return this.localeCharsetMappings;
}
public Map<String, String> getInitParameters() {
return this.initParameters;
}
public List<? extends CookieSameSiteSupplier> getCookieSameSiteSuppliers() {
return this.cookieSameSiteSuppliers;
}
public void setMimeMappings(MimeMappings mimeMappings) {
Assert.notNull(mimeMappings, "'mimeMappings' must not be null");
this.mimeMappings = new MimeMappings(mimeMappings);
}
public void addMimeMappings(MimeMappings mimeMappings) {
mimeMappings.forEach((mapping) -> this.mimeMappings.add(mapping.getExtension(), mapping.getMimeType()));
}
public void setInitializers(List<? extends ServletContextInitializer> initializers) {
Assert.notNull(initializers, "'initializers' must not be null");
this.initializers = new ArrayList<>(initializers);
}
|
public void addInitializers(ServletContextInitializer... initializers) {
Assert.notNull(initializers, "'initializers' must not be null");
this.initializers.addAll(Arrays.asList(initializers));
}
public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null");
this.localeCharsetMappings = localeCharsetMappings;
}
public void setInitParameters(Map<String, String> initParameters) {
this.initParameters = initParameters;
}
public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) {
Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null");
this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers);
}
public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) {
Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null");
this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers));
}
public void addWebListenerClassNames(String... webListenerClassNames) {
this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames));
}
public Set<String> getWebListenerClassNames() {
return this.webListenerClassNames;
}
public List<URL> getStaticResourceUrls() {
return this.staticResourceJars.getUrls();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java
| 1
|
请完成以下Java代码
|
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
|
请在Spring Boot框架中完成以下Java代码
|
private String asExternalIdentifierOrNull(@Nullable final String externalIdentifierValue)
{
if (StringUtils.isEmpty(externalIdentifierValue))
{
return null;
}
return ExternalIdentifierFormat.formatExternalId(externalIdentifierValue);
}
@Nullable
private List<String> extractTherapyTypes(@NonNull final Order order)
{
if (order.getTherapyTypeIds() == null)
{
return null;
}
return order.getTherapyTypeIds().stream()
.filter(Objects::nonNull)
.map(String::valueOf)
.collect(Collectors.toList());
}
@NonNull
private static JsonMetasfreshId extractDeliveryAddressMFId(@NonNull final JsonResponseUpsert deliveryAddressUpsertResponse)
{
final JsonResponseUpsertItem responseUpsertItem = Check.singleElement(deliveryAddressUpsertResponse.getResponseItems());
if (responseUpsertItem.getMetasfreshId() == null)
{
throw new RuntimeException("Delivery address wasn't successfully persisted! ExternalId: " + responseUpsertItem.getIdentifier());
}
return responseUpsertItem.getMetasfreshId();
}
private void computeNextImportDate(@NonNull final Exchange exchange, @NonNull final Order orderCandidate)
{
final Instant nextImportSinceDateCandidate = AlbertaUtil.asInstant(orderCandidate.getCreationDate());
if (nextImportSinceDateCandidate == null)
{
return;
}
final NextImportSinceTimestamp currentNextImportSinceDate =
|
ProcessorHelper.getPropertyOrThrowError(exchange, GetOrdersRouteConstants.ROUTE_PROPERTY_UPDATED_AFTER, NextImportSinceTimestamp.class);
if (nextImportSinceDateCandidate.isAfter(currentNextImportSinceDate.getDate()))
{
currentNextImportSinceDate.setDate(nextImportSinceDateCandidate);
}
}
@NonNull
private static Optional<JsonRequestBPartnerLocationAndContact> getBillToBPartner(@NonNull final JsonResponseComposite jsonResponseComposite)
{
final Optional<JsonResponseLocation> billingAddressLocation = jsonResponseComposite.getLocations()
.stream()
.filter(JsonResponseLocation::isBillTo)
.findFirst();
if (billingAddressLocation.isEmpty())
{
return Optional.empty();
}
return Optional.of(JsonRequestBPartnerLocationAndContact.builder()
.bPartnerIdentifier(JsonMetasfreshId.toValueStr(jsonResponseComposite.getBpartner().getMetasfreshId()))
.bPartnerLocationIdentifier(JsonMetasfreshId.toValueStr(billingAddressLocation.get().getMetasfreshId()))
.build());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\JsonOLCandCreateRequestProcessor.java
| 2
|
请完成以下Java代码
|
public Boolean getExpanded() {
return expanded;
}
public void setExpanded(Boolean expanded) {
this.expanded = expanded;
}
public BaseElement getElement() {
return element;
}
public void setElement(BaseElement element) {
this.element = element;
}
public int getXmlRowNumber() {
|
return xmlRowNumber;
}
public void setXmlRowNumber(int xmlRowNumber) {
this.xmlRowNumber = xmlRowNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\GraphicInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DatabaseConfig {
// ------------------------
// PUBLIC METHODS
// ------------------------
/**
* DataSource definition for database connection. Settings are read from
* the application.properties file (using the env object).
*/
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
return dataSource;
}
/**
* Declare the JPA entity manager factory.
*/
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory =
new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
// Classpath scanning of @Component, @Service, etc annotated class
entityManagerFactory.setPackagesToScan(
env.getProperty("entitymanager.packagesToScan"));
// Vendor adapter
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
// Hibernate properties
Properties additionalProperties = new Properties();
additionalProperties.put(
"hibernate.dialect",
env.getProperty("hibernate.dialect"));
additionalProperties.put(
"hibernate.show_sql",
env.getProperty("hibernate.show_sql"));
additionalProperties.put(
"hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
entityManagerFactory.setJpaProperties(additionalProperties);
return entityManagerFactory;
}
/**
* Declare the transaction manager.
*/
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager =
new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
entityManagerFactory.getObject());
|
return transactionManager;
}
/**
* PersistenceExceptionTranslationPostProcessor is a bean post processor
* which adds an advisor to any bean annotated with Repository so that any
* platform-specific exceptions are caught and then rethrown as one
* Spring's unchecked data access exceptions (i.e. a subclass of
* DataAccessException).
*/
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
// ------------------------
// PRIVATE FIELDS
// ------------------------
@Autowired
private Environment env;
@Autowired
private DataSource dataSource;
@Autowired
private LocalContainerEntityManagerFactoryBean entityManagerFactory;
} // class DatabaseConfig
|
repos\spring-boot-samples-master\spring-boot-mysql-jpa-hibernate\src\main\java\netgloo\configs\DatabaseConfig.java
| 2
|
请完成以下Java代码
|
private void init()
{
ColumnInfo[] s_layoutWarehouse = new ColumnInfo[] {
new ColumnInfo(" ", "M_Warehouse_ID", IDColumn.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "Warehouse"), "Warehouse", String.class),
new ColumnInfo(Msg.translate(Env.getCtx(), "QtyOnHand"), "sum(QtyOnHand)", Double.class),
};
/** From Clause */
String s_sqlFrom = " M_PRODUCT_STOCK_V ";
/** Where Clause */
String s_sqlWhere = "M_Product_ID = ?";
m_sqlWarehouse = warehouseTbl.prepareTable(s_layoutWarehouse, s_sqlFrom, s_sqlWhere, false, "M_PRODUCT_STOCK_V");
m_sqlWarehouse += " GROUP BY M_Warehouse_ID, Warehouse, documentnote ";
warehouseTbl.setMultiSelection(false);
// warehouseTbl.addMouseListener(this);
// warehouseTbl.getSelectionModel().addListSelectionListener(this);
warehouseTbl.autoSize();
}
private void refresh(int M_Product_ID)
{
// int M_Product_ID = 0;
String sql = m_sqlWarehouse;
// Add description to the query
sql = sql.replace(" FROM", ", DocumentNote FROM");
log.trace(sql);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, M_Product_ID);
rs = pstmt.executeQuery();
setDescription("");
warehouseTbl.loadTable(rs);
rs = pstmt.executeQuery();
if (rs.next())
{
if (rs.getString("DocumentNote") != null)
setDescription(rs.getString("DocumentNote"));
}
}
catch (Exception e)
{
log.warn(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
}
|
private void setDescription(String description)
{
fieldDescription.setText(description);
}
public java.awt.Component getComponent(int type)
{
if (type == PANELTYPE_Stock)
return (java.awt.Component)warehouseTbl;
else if (type == PANELTYPE_Description)
return fieldDescription;
else
throw new IllegalArgumentException("Unknown panel type " + type);
}
public int getM_Warehouse_ID()
{
if (warehouseTbl.getRowCount() <= 0)
return -1;
Integer id = warehouseTbl.getSelectedRowKey();
return id == null ? -1 : id;
}
@Override
public void refresh(final int M_Product_ID, final int M_Warehouse_ID, final int M_AttributeSetInstance_ID, final int M_PriceList_Version_ID)
{
refresh(M_Product_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoProductStock.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractServletProcessApplicationDeployer {
protected static final ProcessApplicationLogger LOG = ProcessEngineLogger.PROCESS_APPLICATION_LOGGER;
protected void onStartUp(Set<Class<?>> c, String contextPath, Class<?> servletProcessApplicationClass, Consumer<String> processApplicationClassNameConsumer) throws Exception {
if (c == null || c.isEmpty()) {
// skip deployments that do not carry a PA
return;
}
if (c.contains(ProcessApplication.class)) {
// copy into a fresh Set as we don't know if the original Set is mutable or immutable
c = new HashSet<>(c);
// and now remove the annotation itself
c.remove(ProcessApplication.class);
}
if (c.size() > 1) {
// a deployment must only contain a single PA
throw getServletException(LOG.multiplePasException(c, contextPath));
|
} else if (c.size() == 1) {
Class<?> paClass = c.iterator().next();
// validate whether it is a legal Process Application
if (!AbstractProcessApplication.class.isAssignableFrom(paClass)) {
throw getServletException(LOG.paWrongTypeException(paClass));
}
// add it as listener if it's a servlet process application
if (servletProcessApplicationClass.isAssignableFrom(paClass)) {
LOG.detectedPa(paClass);
processApplicationClassNameConsumer.accept(paClass.getName());
}
} else {
LOG.servletDeployerNoPaFound(contextPath);
}
}
protected abstract Exception getServletException(String message);
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\AbstractServletProcessApplicationDeployer.java
| 1
|
请完成以下Java代码
|
public boolean isDebug()
{
return get_ValueAsBoolean(COLUMNNAME_IsDebug);
}
@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);
}
/**
* Severity AD_Reference_ID=541949
* Reference name: Severity
*/
public static final int SEVERITY_AD_Reference_ID=541949;
/** Notice = N */
public static final String SEVERITY_Notice = "N";
/** Error = E */
public static final String SEVERITY_Error = "E";
@Override
public void setSeverity (final java.lang.String Severity)
{
set_Value (COLUMNNAME_Severity, Severity);
}
@Override
public java.lang.String getSeverity()
{
return get_ValueAsString(COLUMNNAME_Severity);
}
@Override
public org.compiere.model.I_AD_Val_Rule getValidation_Rule()
{
return get_ValueAsPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class);
}
@Override
public void setValidation_Rule(final org.compiere.model.I_AD_Val_Rule Validation_Rule)
{
set_ValueFromPO(COLUMNNAME_Validation_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, Validation_Rule);
|
}
@Override
public void setValidation_Rule_ID (final int Validation_Rule_ID)
{
if (Validation_Rule_ID < 1)
set_Value (COLUMNNAME_Validation_Rule_ID, null);
else
set_Value (COLUMNNAME_Validation_Rule_ID, Validation_Rule_ID);
}
@Override
public int getValidation_Rule_ID()
{
return get_ValueAsInt(COLUMNNAME_Validation_Rule_ID);
}
@Override
public void setWarning_Message_ID (final int Warning_Message_ID)
{
if (Warning_Message_ID < 1)
set_Value (COLUMNNAME_Warning_Message_ID, null);
else
set_Value (COLUMNNAME_Warning_Message_ID, Warning_Message_ID);
}
@Override
public int getWarning_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_Warning_Message_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public RestVariable getVariableFromRequest(boolean includeBinary, String taskId, String variableName, String scope) {
RestVariableScope variableScope = RestVariable.getScopeFromString(scope);
HistoricTaskInstanceQuery taskQuery = historyService.createHistoricTaskInstanceQuery().taskId(taskId);
if (variableScope != null) {
if (variableScope == RestVariableScope.GLOBAL) {
taskQuery.includeProcessVariables();
} else {
taskQuery.includeTaskLocalVariables();
}
} else {
taskQuery.includeTaskLocalVariables().includeProcessVariables();
}
HistoricTaskInstance taskObject = taskQuery.singleResult();
if (taskObject == null) {
throw new FlowableObjectNotFoundException("Historic task instance '" + taskId + "' couldn't be found.", HistoricTaskInstanceEntity.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessHistoryTaskInfoById(taskObject);
}
Object value = null;
if (variableScope != null) {
if (variableScope == RestVariableScope.GLOBAL) {
|
value = taskObject.getProcessVariables().get(variableName);
} else {
value = taskObject.getTaskLocalVariables().get(variableName);
}
} else {
// look for local task variables first
if (taskObject.getTaskLocalVariables().containsKey(variableName)) {
value = taskObject.getTaskLocalVariables().get(variableName);
} else {
value = taskObject.getProcessVariables().get(variableName);
}
}
if (value == null) {
throw new FlowableObjectNotFoundException("Historic task instance '" + taskId + "' variable value for " + variableName + " couldn't be found.", VariableInstanceEntity.class);
} else {
return restResponseFactory.createRestVariable(variableName, value, null, taskId, CmmnRestResponseFactory.VARIABLE_HISTORY_TASK, includeBinary);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceVariableDataResource.java
| 2
|
请完成以下Spring Boot application配置
|
server:
port: 9000
spring:
security:
user:
name: user
password: password
oauth2:
authorizationserver:
client:
oidc-client:
registration:
client-id: "mcp-client"
client-secret: "{noop}mcp-secret"
client-authentication-methods:
- "client_secret_basic"
authorization-grant-types:
- "authorization_code"
- "client_credentials"
- "refresh_token"
|
redirect-uris:
- "http://localhost:8080/authorize/oauth2/code/authserver"
scopes:
- "openid"
- "profile"
- "calc.read"
- "calc.write"
|
repos\tutorials-master\spring-ai-modules\spring-ai-mcp-oauth\oauth2-authorization-server\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class VLetterAttachment extends CPanel {
private final Dialog parentDialog;
private VTextLong fPreview = new VTextLong("Preview", false, true, false, 60, 60);
private CButton bEdit = new CButton();
private CButton bCancel = new CButton();
private BoilerPlateContext variables = BoilerPlateContext.EMPTY;
private String letterHtml = "";
private File letterPdfFile = null;
private final ActionListener editAction = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final LetterDialog d = new LetterDialog(parentDialog, Msg.translate(Env.getAD_Language(Env.getCtx()), Letters.MSG_Letter), variables);
d.setMessage(letterHtml);
AEnv.showCenterScreen(d);
if (d.isPressedOK()) {
letterHtml = d.getMessage();
letterPdfFile = d.getPDF();
updateComponentsStatus();
}
}
};
private final ActionListener cancelAction = new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
letterHtml = "";
letterPdfFile = null;
updateComponentsStatus();
}
};
public VLetterAttachment(final Dialog parentDialog) {
super();
this.parentDialog = parentDialog;
init();
}
private void init() {
fPreview.setText("");
fPreview.setPreferredSize(new Dimension (500,80)); // else the component will be displayed too small if empty (when using FlowLayout)
bEdit.setIcon(Images.getImageIcon2("Open16"));
bEdit.setText("");
|
bEdit.addActionListener(editAction);
bCancel.setIcon(Images.getImageIcon2("Cancel16"));
bCancel.setText("");
bCancel.addActionListener(cancelAction);
//
setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(fPreview);
this.add(bEdit);
this.add(bCancel);
}
private void updateComponentsStatus() {
fPreview.setText(letterHtml == null ? "" : letterHtml);
bCancel.setEnabled(!Check.isEmpty(letterHtml, false));
}
public void setVariables(final BoilerPlateContext variables) {
this.variables = variables;
}
public String getLetterHtml() {
return letterHtml;
}
public File getPDF() {
return letterPdfFile;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VLetterAttachment.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public DeployHistoryDto findById(String id) {
DeployHistory deployhistory = deployhistoryRepository.findById(id).orElseGet(DeployHistory::new);
ValidationUtil.isNull(deployhistory.getId(),"DeployHistory","id",id);
return deployhistoryMapper.toDto(deployhistory);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DeployHistory resources) {
resources.setId(IdUtil.simpleUUID());
deployhistoryRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<String> ids) {
for (String id : ids) {
deployhistoryRepository.deleteById(id);
}
}
|
@Override
public void download(List<DeployHistoryDto> queryAll, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DeployHistoryDto deployHistoryDto : queryAll) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("部署编号", deployHistoryDto.getDeployId());
map.put("应用名称", deployHistoryDto.getAppName());
map.put("部署IP", deployHistoryDto.getIp());
map.put("部署时间", deployHistoryDto.getDeployDate());
map.put("部署人员", deployHistoryDto.getDeployUser());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DeployHistoryServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop120VType getEDICctop120VType(@NonNull final EDICctop120VType source)
{
final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop120VType target = DESADV_objectFactory.createEDICctop120VType();
target.setCInvoiceID(source.getCInvoiceID());
target.setEDICctop120VID(source.getEDICctop120VID());
target.setISOCode(source.getISOCode());
target.setNetdate(source.getNetdate());
target.setNetDays(source.getNetDays());
target.setSinglevat(source.getSinglevat());
target.setTaxfree(source.getTaxfree());
return target;
}
@NonNull
private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop119VType getEDICctop119VType(@NonNull final EDICctop119VType source)
{
final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop119VType target = DESADV_objectFactory.createEDICctop119VType();
target.setAddress1(source.getAddress1());
target.setAddress2(source.getAddress2());
target.setCBPartnerLocationID(source.getCBPartnerLocationID());
target.setCInvoiceID(source.getCInvoiceID());
target.setCity(source.getCity());
target.setCountryCode(source.getCountryCode());
target.setEancomLocationtype(source.getEancomLocationtype());
target.setEDICctop119VID(source.getEDICctop119VID());
target.setFax(source.getFax());
target.setGLN(source.getGLN());
target.setMInOutID(source.getMInOutID());
target.setName(source.getName());
target.setName2(source.getName2());
target.setPhone(source.getPhone());
target.setPostal(source.getPostal());
target.setValue(source.getValue());
target.setVATaxID(source.getVATaxID());
target.setReferenceNo(source.getReferenceNo());
target.setSetupPlaceNo(source.getSetupPlaceNo());
target.setSiteName(source.getSiteName());
target.setContact(source.getContact());
return target;
}
|
@NonNull
private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop111VType getEDICctop111VType(@NonNull final EDICctop111VType source)
{
final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop111VType target = DESADV_objectFactory.createEDICctop111VType();
target.setCOrderID(source.getCOrderID());
target.setDateOrdered(source.getDateOrdered());
target.setEDICctop111VID(source.getEDICctop111VID());
target.setMInOutID(source.getMInOutID());
target.setMovementDate(source.getMovementDate());
target.setPOReference(source.getPOReference());
target.setShipmentDocumentno(source.getShipmentDocumentno());
return target;
}
@NonNull
private de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop000VType getEDICctop000V(@NonNull final EDICctop000VType source)
{
final de.metas.edi.esb.jaxb.metasfreshinhousev1.EDICctop000VType target = DESADV_objectFactory.createEDICctop000VType();
target.setCBPartnerLocationID(source.getCBPartnerLocationID());
target.setEDICctop000VID(source.getEDICctop000VID());
target.setGLN(source.getGLN());
return target;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\metasfreshinhousev1\MetasfreshInHouseV1XMLInvoicBean.java
| 2
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:h2:~/jinq;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hib
|
ernate.globally_quoted_identifiers=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
|
repos\tutorials-master\spring-jinq\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausschluß.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
@Override
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Ausschluß.
@return Exclude access to the data - if not selected Include access to the data
*/
@Override
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
|
return false;
}
/** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column_Access.java
| 1
|
请完成以下Java代码
|
private PrintFormatId getPrintFormatId(final I_C_RfQResponse rfqResponse, final RfQReportType rfqReportType)
{
final I_C_RfQ_Topic rfqTopic = rfqResponse.getC_RfQ().getC_RfQ_Topic();
if (rfqReportType == RfQReportType.Invitation)
{
return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_Invitation_PrintFormat_ID());
}
else if (rfqReportType == RfQReportType.InvitationWithoutQtyRequired)
{
return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_InvitationWithoutQty_PrintFormat_ID());
}
else if (rfqReportType == RfQReportType.Won)
{
return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_Win_PrintFormat_ID());
}
else if (rfqReportType == RfQReportType.Lost)
{
return PrintFormatId.ofRepoIdOrNull(rfqTopic.getRfQ_Lost_PrintFormat_ID());
}
else
{
throw new AdempiereException("@Invalid@ @Type@: " + rfqReportType);
}
}
private MailTextBuilder createMailTextBuilder(final I_C_RfQResponse rfqResponse, final RfQReportType rfqReportType)
{
final I_C_RfQ_Topic rfqTopic = rfqResponse.getC_RfQ().getC_RfQ_Topic();
final MailTextBuilder mailTextBuilder;
if (rfqReportType == RfQReportType.Invitation)
{
mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Invitation_MailText_ID()));
}
else if (rfqReportType == RfQReportType.InvitationWithoutQtyRequired)
|
{
mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_InvitationWithoutQty_MailText_ID()));
}
else if (rfqReportType == RfQReportType.Won)
{
mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Win_MailText_ID()));
}
else if (rfqReportType == RfQReportType.Lost)
{
mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Lost_MailText_ID()));
}
else
{
throw new AdempiereException("@Invalid@ @Type@: " + rfqReportType);
}
mailTextBuilder.bpartner(rfqResponse.getC_BPartner());
mailTextBuilder.bpartnerContact(rfqResponse.getAD_User());
mailTextBuilder.record(rfqResponse);
return mailTextBuilder;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\MailRfqResponsePublisherInstance.java
| 1
|
请完成以下Java代码
|
public static class JsonOLCandUtilException extends RuntimeException
{
private static final long serialVersionUID = -626001461757553239L;
public JsonOLCandUtilException(final String msg, final Throwable cause)
{
super(msg, cause);
}
}
public static JsonOLCandCreateBulkRequest loadJsonOLCandCreateBulkRequest(@NonNull final String resourceName)
{
return fromRessource(resourceName, JsonOLCandCreateBulkRequest.class);
}
public static JsonOLCandCreateRequest loadJsonOLCandCreateRequest(@NonNull final String resourceName)
{
return fromRessource(resourceName, JsonOLCandCreateRequest.class);
}
private static <T> T fromRessource(@NonNull final String resourceName, @NonNull final Class<T> clazz)
{
final InputStream inputStream = Check.assumeNotNull(
JsonOLCandUtil.class.getResourceAsStream(resourceName),
|
"There needs to be a loadable resource with name={}", resourceName);
final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return jsonObjectMapper.readValue(inputStream, clazz);
}
catch (final JsonParseException e)
{
throw new JsonOLCandUtilException("JsonParseException", e);
}
catch (final JsonMappingException e)
{
throw new JsonOLCandUtilException("JsonMappingException", e);
}
catch (final IOException e)
{
throw new JsonOLCandUtilException("IOException", e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\ordercandidates\impl\JsonOLCandUtil.java
| 1
|
请完成以下Java代码
|
public void setC_OrderPO_ID (final int C_OrderPO_ID)
{
if (C_OrderPO_ID < 1)
set_Value (COLUMNNAME_C_OrderPO_ID, null);
else
set_Value (COLUMNNAME_C_OrderPO_ID, C_OrderPO_ID);
}
@Override
public int getC_OrderPO_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderPO_ID);
}
@Override
public void setC_PurchaseCandidate_Alloc_ID (final int C_PurchaseCandidate_Alloc_ID)
{
if (C_PurchaseCandidate_Alloc_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_Alloc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_Alloc_ID, C_PurchaseCandidate_Alloc_ID);
}
@Override
public int getC_PurchaseCandidate_Alloc_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_Alloc_ID);
}
@Override
public de.metas.purchasecandidate.model.I_C_PurchaseCandidate getC_PurchaseCandidate()
{
return get_ValueAsPO(COLUMNNAME_C_PurchaseCandidate_ID, de.metas.purchasecandidate.model.I_C_PurchaseCandidate.class);
}
@Override
public void setC_PurchaseCandidate(final de.metas.purchasecandidate.model.I_C_PurchaseCandidate C_PurchaseCandidate)
{
set_ValueFromPO(COLUMNNAME_C_PurchaseCandidate_ID, de.metas.purchasecandidate.model.I_C_PurchaseCandidate.class, C_PurchaseCandidate);
}
@Override
public void setC_PurchaseCandidate_ID (final int C_PurchaseCandidate_ID)
{
if (C_PurchaseCandidate_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_PurchaseCandidate_ID, C_PurchaseCandidate_ID);
}
@Override
public int getC_PurchaseCandidate_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PurchaseCandidate_ID);
}
@Override
public void setDateOrdered (final @Nullable java.sql.Timestamp DateOrdered)
{
set_Value (COLUMNNAME_DateOrdered, DateOrdered);
}
@Override
public java.sql.Timestamp getDateOrdered()
{
return get_ValueAsTimestamp(COLUMNNAME_DateOrdered);
|
}
@Override
public void setDatePromised (final @Nullable java.sql.Timestamp DatePromised)
{
set_Value (COLUMNNAME_DatePromised, DatePromised);
}
@Override
public java.sql.Timestamp getDatePromised()
{
return get_ValueAsTimestamp(COLUMNNAME_DatePromised);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setRemotePurchaseOrderId (final @Nullable java.lang.String RemotePurchaseOrderId)
{
set_Value (COLUMNNAME_RemotePurchaseOrderId, RemotePurchaseOrderId);
}
@Override
public java.lang.String getRemotePurchaseOrderId()
{
return get_ValueAsString(COLUMNNAME_RemotePurchaseOrderId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java-gen\de\metas\purchasecandidate\model\X_C_PurchaseCandidate_Alloc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static final class BearerTokenRequestMatcher implements RequestMatcher {
private final BearerTokenResolver bearerTokenResolver;
BearerTokenRequestMatcher(BearerTokenResolver bearerTokenResolver) {
Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null");
this.bearerTokenResolver = bearerTokenResolver;
}
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.bearerTokenResolver.resolve(request) != null;
}
catch (OAuth2AuthenticationException ex) {
return false;
}
}
}
static final class BearerTokenAuthenticationRequestMatcher implements RequestMatcher {
private final AuthenticationConverter authenticationConverter;
|
BearerTokenAuthenticationRequestMatcher() {
this.authenticationConverter = new BearerTokenAuthenticationConverter();
}
BearerTokenAuthenticationRequestMatcher(AuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter;
}
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.authenticationConverter.convert(request) != null;
}
catch (OAuth2AuthenticationException ex) {
return false;
}
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ResourceServerBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
public org.compiere.model.I_R_MailText getRfQ_Win_MailText() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_RfQ_Win_MailText_ID, org.compiere.model.I_R_MailText.class);
}
@Override
public void setRfQ_Win_MailText(org.compiere.model.I_R_MailText RfQ_Win_MailText)
{
set_ValueFromPO(COLUMNNAME_RfQ_Win_MailText_ID, org.compiere.model.I_R_MailText.class, RfQ_Win_MailText);
}
/** Set RfQ win mail text.
@param RfQ_Win_MailText_ID RfQ win mail text */
@Override
public void setRfQ_Win_MailText_ID (int RfQ_Win_MailText_ID)
{
if (RfQ_Win_MailText_ID < 1)
set_Value (COLUMNNAME_RfQ_Win_MailText_ID, null);
else
set_Value (COLUMNNAME_RfQ_Win_MailText_ID, Integer.valueOf(RfQ_Win_MailText_ID));
}
/** Get RfQ win mail text.
@return RfQ win mail text */
@Override
public int getRfQ_Win_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_MailText_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_PrintFormat getRfQ_Win_PrintFormat() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class);
}
@Override
public void setRfQ_Win_PrintFormat(org.compiere.model.I_AD_PrintFormat RfQ_Win_PrintFormat)
{
set_ValueFromPO(COLUMNNAME_RfQ_Win_PrintFormat_ID, org.compiere.model.I_AD_PrintFormat.class, RfQ_Win_PrintFormat);
}
/** Set RfQ Won Druck - Format.
@param RfQ_Win_PrintFormat_ID RfQ Won Druck - Format */
@Override
public void setRfQ_Win_PrintFormat_ID (int RfQ_Win_PrintFormat_ID)
{
if (RfQ_Win_PrintFormat_ID < 1)
set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, null);
else
set_Value (COLUMNNAME_RfQ_Win_PrintFormat_ID, Integer.valueOf(RfQ_Win_PrintFormat_ID));
}
/** Get RfQ Won Druck - Format.
@return RfQ Won Druck - Format */
@Override
public int getRfQ_Win_PrintFormat_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RfQ_Win_PrintFormat_ID);
|
if (ii == null)
return 0;
return ii.intValue();
}
/**
* RfQType AD_Reference_ID=540661
* Reference name: RfQType
*/
public static final int RFQTYPE_AD_Reference_ID=540661;
/** Default = D */
public static final String RFQTYPE_Default = "D";
/** Procurement = P */
public static final String RFQTYPE_Procurement = "P";
/** Set Ausschreibung Art.
@param RfQType Ausschreibung Art */
@Override
public void setRfQType (java.lang.String RfQType)
{
set_Value (COLUMNNAME_RfQType, RfQType);
}
/** Get Ausschreibung Art.
@return Ausschreibung Art */
@Override
public java.lang.String getRfQType ()
{
return (java.lang.String)get_Value(COLUMNNAME_RfQType);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQ_Topic.java
| 1
|
请完成以下Java代码
|
private static Workplace fromRecord(
@NonNull final I_C_Workplace record,
@NonNull final Multimap<WorkplaceId, ProductId> productsByWorkplace,
@NonNull final Multimap<WorkplaceId, ProductCategoryId> categoriesByWorkplace,
@NonNull final Multimap<WorkplaceId, CarrierProductId> carrierProductsByWorkplace,
@NonNull final Multimap<WorkplaceId, ExternalSystemId> externalSystemsByWorkplace)
{
final WarehouseId warehouseId = WarehouseId.ofRepoId(record.getM_Warehouse_ID());
final WorkplaceId workplaceId = WorkplaceId.ofRepoId(record.getC_Workplace_ID());
return Workplace.builder()
.id(workplaceId)
.name(record.getName())
.warehouseId(warehouseId)
.pickFromLocatorId(LocatorId.ofRepoIdOrNull(warehouseId, record.getPickFrom_Locator_ID()))
.pickingSlotId(PickingSlotId.ofRepoIdOrNull(record.getM_PickingSlot_ID()))
.seqNo(SeqNo.ofInt(record.getSeqNo()))
.priorityRule(PriorityRule.ofNullableCode(record.getPriorityRule()))
.orderPickingType(OrderPickingType.ofNullableCode(record.getOrderPickingType()))
.maxPickingJobs(record.getMaxPickingJobs())
// Add child collections
.productIds(ImmutableSet.copyOf(productsByWorkplace.get(workplaceId)))
.productCategoryIds(ImmutableSet.copyOf(categoriesByWorkplace.get(workplaceId)))
.carrierProductIds(ImmutableSet.copyOf(carrierProductsByWorkplace.get(workplaceId)))
.externalSystemIds(ImmutableSet.copyOf(externalSystemsByWorkplace.get(workplaceId)))
.build();
}
//
//
//
//
//
private static class WorkplacesMap
{
private final ImmutableMap<WorkplaceId, Workplace> byId;
@Getter private final ImmutableList<Workplace> allActive;
WorkplacesMap(final List<Workplace> list)
{
this.byId = Maps.uniqueIndex(list, Workplace::getId);
this.allActive = ImmutableList.copyOf(list);
}
|
@NonNull
public Workplace getById(final WorkplaceId id)
{
final Workplace workplace = byId.get(id);
if (workplace == null)
{
throw new AdempiereException("No workplace found for " + id);
}
return workplace;
}
public Collection<Workplace> getByIds(final Collection<WorkplaceId> ids)
{
if (ids.isEmpty())
{
return ImmutableList.of();
}
return ids.stream()
.map(this::getById)
.collect(ImmutableList.toImmutableList());
}
public boolean isEmpty()
{
return byId.isEmpty();
}
public SeqNo getNextSeqNo()
{
final Workplace workplace = getAllActive().stream().max(Comparator.comparing(v -> v.getSeqNo().toInt())).orElse(null);
return workplace != null ? workplace.getSeqNo().next() : SeqNo.ofInt(10);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceRepository.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthDate() {
return birthDate;
}
|
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
@Override
public void write(Kryo kryo, Output output) {
output.writeString(name);
output.writeLong(birthDate.getTime());
output.writeInt(age);
}
@Override
public void read(Kryo kryo, Input input) {
name = input.readString();
birthDate = new Date(input.readLong());
age = input.readInt();
}
}
|
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\libraries\kryo\Person.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BPRelationRouteBuilder extends RouteBuilder
{
@VisibleForTesting
static final String ROUTE_ID = "To-MF_Upsert-BPRelation";
@Override
public void configure()
{
errorHandler(noErrorHandler());
from("{{" + ExternalSystemCamelConstants.MF_UPSERT_BPRELATION_CAMEL_URI + "}}")
.routeId(ROUTE_ID)
.streamCache("true")
.process(exchange -> {
final var lookupRequest = exchange.getIn().getBody();
if (!(lookupRequest instanceof BPRelationsCamelRequest))
{
|
throw new RuntimeCamelException("The route " + ROUTE_ID + " requires the body to be instanceof BPRelationsCamelRequest. However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName()));
}
final BPRelationsCamelRequest bpRelationsCamelRequest = (BPRelationsCamelRequest)lookupRequest;
log.info("Route invoked");
exchange.getIn().setHeader("bpartnerIdentifier", bpRelationsCamelRequest.getBpartnerIdentifier());
exchange.getIn().setBody(bpRelationsCamelRequest.getJsonRequestBPRelationsUpsert());
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonRequestBPRelationsUpsert.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.PUT))
.toD("{{metasfresh.upsert-bprelation.api.uri}}/${header.bpartnerIdentifier}");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v1\BPRelationRouteBuilder.java
| 2
|
请完成以下Java代码
|
public void setIsPassive (boolean IsPassive)
{
set_Value (COLUMNNAME_IsPassive, Boolean.valueOf(IsPassive));
}
/** Get Transfer passive.
@return FTP passive transfer
*/
public boolean isPassive ()
{
Object oo = get_Value(COLUMNNAME_IsPassive);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Password.
@param Password
Password of any length (case sensitive)
*/
public void setPassword (String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Password.
@return Password of any length (case sensitive)
*/
public String getPassword ()
{
return (String)get_Value(COLUMNNAME_Password);
}
/** Set URL.
@param URL
|
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
public void setUserName (String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
public String getUserName ()
{
return (String)get_Value(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
| 1
|
请完成以下Java代码
|
public String getAuftragsID() {
return auftragsID;
}
/**
* Sets the value of the auftragsID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuftragsID(String value) {
this.auftragsID = value;
}
/**
* Gets the value of the menge property.
*
*/
public int getMenge() {
return menge;
}
|
/**
* Sets the value of the menge property.
*
*/
public void setMenge(int value) {
this.menge = value;
}
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfragenAntwort.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.