instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final Logger log = LoggerFactory.getLogger(EntityManagerFilter.class);
public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER";
private final EntityManagerFactory emf;
@Context
private HttpServletRequest httpRequest;
public EntityManagerFilter(EntityManagerFactory emf) {
this.emf = emf;
}
@Override
public void filter(ContainerRequestContext ctx) {
log.info("[I60] >>> filter");
EntityManager em = this.emf.createEntityManager();
httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, em);
// Start a new transaction unless we have a simple GET
if (!"GET".equalsIgnoreCase(ctx.getMethod())) {
em.getTransaction()
.begin();
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
log.info("[I68] <<< filter");
EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE);
|
if (!"GET".equalsIgnoreCase(requestContext.getMethod())) {
EntityTransaction t = em.getTransaction();
if (t.isActive()) {
if (!t.getRollbackOnly()) {
t.commit();
}
}
}
em.close();
}
}
@Path("/")
public static class CarsRootLocator extends ODataRootLocator {
private CarsODataJPAServiceFactory serviceFactory;
public CarsRootLocator(CarsODataJPAServiceFactory serviceFactory) {
this.serviceFactory = serviceFactory;
}
@Override
public ODataServiceFactory getServiceFactory() {
return this.serviceFactory;
}
}
}
|
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\JerseyConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
OtelTracer micrometerOtelTracer(Tracer tracer, EventPublisher eventPublisher,
OtelCurrentTraceContext otelCurrentTraceContext) {
List<String> remoteFields = this.tracingProperties.getBaggage().getRemoteFields();
List<String> tagFields = this.tracingProperties.getBaggage().getTagFields();
return new OtelTracer(tracer, otelCurrentTraceContext, eventPublisher,
new OtelBaggageManager(otelCurrentTraceContext, remoteFields, tagFields));
}
@Bean
@ConditionalOnMissingBean
OtelPropagator otelPropagator(ContextPropagators contextPropagators, Tracer tracer) {
return new OtelPropagator(contextPropagators, tracer);
}
@Bean
@ConditionalOnMissingBean
EventPublisher otelTracerEventPublisher(List<EventListener> eventListeners) {
return new OTelEventPublisher(eventListeners);
}
@Bean
@ConditionalOnMissingBean
OtelCurrentTraceContext otelCurrentTraceContext() {
return new OtelCurrentTraceContext();
}
@Bean
@ConditionalOnMissingBean
Slf4JEventListener otelSlf4JEventListener() {
|
return new Slf4JEventListener();
}
@Bean
@ConditionalOnMissingBean(SpanCustomizer.class)
OtelSpanCustomizer otelSpanCustomizer() {
return new OtelSpanCustomizer();
}
static class OTelEventPublisher implements EventPublisher {
private final List<EventListener> listeners;
OTelEventPublisher(List<EventListener> listeners) {
this.listeners = listeners;
}
@Override
public void publishEvent(Object event) {
for (EventListener listener : this.listeners) {
listener.onEvent(event);
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing-opentelemetry\src\main\java\org\springframework\boot\micrometer\tracing\opentelemetry\autoconfigure\OpenTelemetryTracingAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public PickingSlotRow getRootRowWhichIncludes(@NonNull final PickingSlotRowId rowId)
{
final PickingSlotRow rootRow = getRowsIndex().getRootRow(rowId);
if (rootRow == null)
{
throw new AdempiereException("No root row found which includes " + rowId);
}
return rootRow;
}
public PickingSlotRowId getRootRowIdWhichIncludes(@NonNull final PickingSlotRowId rowId)
{
return getRowsIndex().getRootRowId(rowId);
}
private static final PickingSlotRow assertRowNotNull(final PickingSlotRowId pickingSlotRowId, final PickingSlotRow pickingSlotRow)
{
if (pickingSlotRow == null)
{
throw new EntityNotFoundException("Row not found").setParameter("pickingSlotRowId", pickingSlotRowId);
}
return pickingSlotRow;
}
public Stream<PickingSlotRow> streamByIds(final DocumentIdsSelection rowIds)
{
if (rowIds.isAll())
{
return getRowsIndex().stream();
}
else
{
return rowIds.stream().map(this::getById);
}
}
@ToString
private static final class PickingSlotRowsIndex
{
private final ImmutableMap<PickingSlotRowId, PickingSlotRow> rowsById;
private final ImmutableMap<PickingSlotRowId, PickingSlotRowId> rowId2rootRowId;
private PickingSlotRowsIndex(final List<PickingSlotRow> rows)
{
rowsById = Maps.uniqueIndex(rows, PickingSlotRow::getPickingSlotRowId);
rowId2rootRowId = rows.stream()
.flatMap(rootRow -> streamChild2RootRowIdsRecursivelly(rootRow))
.collect(GuavaCollectors.toImmutableMap());
}
private static Stream<Map.Entry<PickingSlotRowId, PickingSlotRowId>> streamChild2RootRowIdsRecursivelly(final PickingSlotRow row)
{
final PickingSlotRowId rootRowId = row.getPickingSlotRowId();
return row.streamThisRowAndIncludedRowsRecursivelly()
.map(PickingSlotRow::getPickingSlotRowId)
.map(includedRowId -> GuavaCollectors.entry(includedRowId, rootRowId));
}
|
public PickingSlotRow getRow(final PickingSlotRowId rowId)
{
return rowsById.get(rowId);
}
@Nullable
public PickingSlotRow getRootRow(final PickingSlotRowId rowId)
{
final PickingSlotRowId rootRowId = getRootRowId(rowId);
if (rootRowId == null)
{
return null;
}
return getRow(rootRowId);
}
public PickingSlotRowId getRootRowId(final PickingSlotRowId rowId)
{
return rowId2rootRowId.get(rowId);
}
public long size()
{
return rowsById.size();
}
public Stream<PickingSlotRow> stream()
{
return rowsById.values().stream();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRowsCollection.java
| 1
|
请完成以下Java代码
|
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
}
public String getJobDefinitionType() {
return jobDefinitionType;
}
public void setJobDefinitionType(String jobDefinitionType) {
this.jobDefinitionType = jobDefinitionType;
}
public String getJobDefinitionConfiguration() {
return jobDefinitionConfiguration;
}
public void setJobDefinitionConfiguration(String jobDefinitionConfiguration) {
this.jobDefinitionConfiguration = jobDefinitionConfiguration;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
|
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public boolean isCreationLog() {
return state == JobState.CREATED.getStateCode();
}
public boolean isFailureLog() {
return state == JobState.FAILED.getStateCode();
}
public boolean isSuccessLog() {
return state == JobState.SUCCESSFUL.getStateCode();
}
public boolean isDeletionLog() {
return state == JobState.DELETED.getStateCode();
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricJobLogEvent.java
| 1
|
请完成以下Java代码
|
public Map<String, String> evaluate(String task) {
return loop(task, new HashMap<>(), "");
}
private Map<String, String> loop(String task, Map<String, String> latestSuggestions, String evaluation) {
latestSuggestions = generate(task, latestSuggestions, evaluation);
Map<String, String> evaluationResponse = evaluate(latestSuggestions, task);
String outcome = evaluationResponse.keySet().iterator().next();
evaluation = evaluationResponse.values().iterator().next();
if ("PASS".equals(outcome)) {
System.out.println("Accepted RE Review Suggestions:\n" + latestSuggestions);
return latestSuggestions;
}
return loop(task, latestSuggestions, evaluation);
}
private Map<String, String> generate(String task, Map<String, String> previousSuggestions, String evaluation) {
String request = CODE_REVIEW_PROMPT +
"\n PR: " + task +
"\n previous suggestions: " + previousSuggestions +
"\n evaluation on previous suggestions: " + evaluation;
System.out.println("PR REVIEW PROMPT: " + request);
ChatClient.ChatClientRequestSpec requestSpec = codeReviewClient.prompt(request);
ChatClient.CallResponseSpec responseSpec = requestSpec.call();
|
Map<String, String> response = responseSpec.entity(mapClass);
System.out.println("PR REVIEW OUTCOME: " + response);
return response;
}
private Map<String, String> evaluate(Map<String, String> latestSuggestions, String task) {
String request = EVALUATE_PROPOSED_IMPROVEMENTS_PROMPT +
"\n PR: " + task +
"\n proposed suggestions: " + latestSuggestions;
System.out.println("EVALUATION PROMPT: " + request);
ChatClient.ChatClientRequestSpec requestSpec = codeReviewClient.prompt(request);
ChatClient.CallResponseSpec responseSpec = requestSpec.call();
Map<String, String> response = responseSpec.entity(mapClass);
System.out.println("EVALUATION OUTCOME: " + response);
return response;
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai-agentic-patterns\src\main\java\com\baeldung\springai\agenticpatterns\workflows\evaluator\EvaluatorOptimizerWorkflow.java
| 1
|
请完成以下Java代码
|
public static HistoricCaseInstanceMigrationDocument convertFromJson(String jsonCaseInstanceMigrationDocument) {
try {
JsonNode rootNode = objectMapper.readTree(jsonCaseInstanceMigrationDocument);
HistoricCaseInstanceMigrationDocumentBuilderImpl documentBuilder = new HistoricCaseInstanceMigrationDocumentBuilderImpl();
documentBuilder.setCaseDefinitionToMigrateTo(getJsonProperty(TO_CASE_DEFINITION_ID_JSON_PROPERTY, rootNode));
String caseDefinitionKey = getJsonProperty(TO_CASE_DEFINITION_KEY_JSON_PROPERTY, rootNode);
Integer caseDefinitionVersion = getJsonPropertyAsInteger(TO_CASE_DEFINITION_VERSION_JSON_PROPERTY, rootNode);
documentBuilder.setCaseDefinitionToMigrateTo(caseDefinitionKey, caseDefinitionVersion);
documentBuilder.setTenantId(getJsonProperty(TO_CASE_DEFINITION_TENANT_ID_JSON_PROPERTY, rootNode));
return documentBuilder.build();
} catch (JacksonException e) {
throw new FlowableException("Error parsing Historic Case Instance Migration Document", e);
}
}
protected static String getJsonProperty(String propertyName, JsonNode jsonNode) {
|
if (jsonNode.has(propertyName) && !jsonNode.get(propertyName).isNull()) {
return jsonNode.get(propertyName).asString();
}
return null;
}
protected static Integer getJsonPropertyAsInteger(String propertyName, JsonNode jsonNode) {
if (jsonNode.has(propertyName) && !jsonNode.get(propertyName).isNull()) {
return jsonNode.get(propertyName).asInt();
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\migration\HistoricCaseInstanceMigrationDocumentConverter.java
| 1
|
请完成以下Java代码
|
public void setParent_HU_Trx_Line_ID (final int Parent_HU_Trx_Line_ID)
{
if (Parent_HU_Trx_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_Parent_HU_Trx_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Parent_HU_Trx_Line_ID, Parent_HU_Trx_Line_ID);
}
@Override
public int getParent_HU_Trx_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_Parent_HU_Trx_Line_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 setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@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 de.metas.handlingunits.model.I_M_HU_Trx_Line getReversalLine()
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class);
}
@Override
public void setReversalLine(final de.metas.handlingunits.model.I_M_HU_Trx_Line ReversalLine)
{
|
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, de.metas.handlingunits.model.I_M_HU_Trx_Line.class, ReversalLine);
}
@Override
public void setReversalLine_ID (final int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, ReversalLine_ID);
}
@Override
public int getReversalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_ReversalLine_ID);
}
@Override
public de.metas.handlingunits.model.I_M_HU_Item getVHU_Item()
{
return get_ValueAsPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class);
}
@Override
public void setVHU_Item(final de.metas.handlingunits.model.I_M_HU_Item VHU_Item)
{
set_ValueFromPO(COLUMNNAME_VHU_Item_ID, de.metas.handlingunits.model.I_M_HU_Item.class, VHU_Item);
}
@Override
public void setVHU_Item_ID (final int VHU_Item_ID)
{
if (VHU_Item_ID < 1)
set_Value (COLUMNNAME_VHU_Item_ID, null);
else
set_Value (COLUMNNAME_VHU_Item_ID, VHU_Item_ID);
}
@Override
public int getVHU_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_Item_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trx_Line.java
| 1
|
请完成以下Java代码
|
protected boolean isApproveForInvoicing()
{
return true;
}
/**
* Implementation detail: during `checkPreconditionsApplicable` `getProcessInfo` throws exception because it is not configured for the Process, so we ignore it.
*/
@Override
protected IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters)
{
final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_C_Invoice_Candidate.class);
if (includeProcessInfoFilters)
{
queryBuilder.filter(getProcessInfo().getQueryFilterOrElseFalse());
}
queryBuilder.addFilter(getSelectionFilter());
queryBuilder.addOnlyActiveRecordsFilter()
.addNotNull(I_C_Invoice_Candidate.COLUMNNAME_C_Currency_ID)
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, true) // not processed
.addNotEqualsFilter(I_C_Invoice_Candidate.COLUMN_ApprovalForInvoicing, true) // not already approved
;
// Only selected rows
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
|
if (!selectedRowIds.isAll())
{
final Set<Integer> invoiceCandidateIds = selectedRowIds.toIntSet();
if (invoiceCandidateIds.isEmpty())
{
// shall not happen
throw new AdempiereException("@NoSelection@");
}
queryBuilder.addInArrayFilter(I_C_Invoice_Candidate.COLUMN_C_Invoice_Candidate_ID, invoiceCandidateIds);
}
return queryBuilder.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_ApproveForInvoicing.java
| 1
|
请完成以下Java代码
|
public void notifyRecordsChangedAsync(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
async.execute(() -> notifyRecordsChangedNow(recordRefs));
}
@Override
public void notifyRecordsChangedNow(@NonNull final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
logger.trace("No changed records provided. Skip notifying views.");
return;
}
try (final IAutoCloseable ignored = ViewChangesCollector.currentOrNewThreadLocalCollector())
{
for (final IViewsIndexStorage viewsIndexStorage : viewsIndexStorages.values())
{
notifyRecordsChangedNow(recordRefs, viewsIndexStorage);
}
notifyRecordsChangedNow(recordRefs, defaultViewsIndexStorage);
}
}
private void notifyRecordsChangedNow(
@NonNull final TableRecordReferenceSet recordRefs,
@NonNull final IViewsIndexStorage viewsIndexStorage)
{
final ImmutableList<IView> views = viewsIndexStorage.getAllViews();
if (views.isEmpty())
{
return;
}
|
final MutableInt notifiedCount = MutableInt.zero();
for (final IView view : views)
{
try
{
final boolean watchedByFrontend = isWatchedByFrontend(view.getViewId());
view.notifyRecordsChanged(recordRefs, watchedByFrontend);
notifiedCount.incrementAndGet();
}
catch (final Exception ex)
{
logger.warn("Failed calling notifyRecordsChanged on view={} with recordRefs={}. Ignored.", view, recordRefs, ex);
}
}
logger.debug("Notified {} views in {} about changed records: {}", notifiedCount, viewsIndexStorage, recordRefs);
}
@lombok.Value(staticConstructor = "of")
private static class ViewFactoryKey
{
WindowId windowId;
JSONViewDataType viewType;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewsRepository.java
| 1
|
请完成以下Java代码
|
public class ViewChanges
{
private final ViewId viewId;
private boolean fullyChanged;
private boolean headerPropertiesChanged;
private Set<DocumentId> changedRowIds = null;
public ViewChanges(@NonNull final ViewId viewId)
{
this.viewId = viewId;
}
public void collectFrom(final ViewChanges changes)
{
if (changes.isFullyChanged())
{
fullyChanged = true;
}
if (changes.changedRowIds != null && !changes.changedRowIds.isEmpty())
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(changes.changedRowIds);
}
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("viewId", viewId)
.add("fullyChanged", fullyChanged ? Boolean.TRUE : null)
.add("headerPropertiesChanged", headerPropertiesChanged ? Boolean.TRUE : null)
.add("changedRowIds", changedRowIds)
.toString();
}
public ViewId getViewId()
{
return viewId;
}
public void setFullyChanged()
{
fullyChanged = true;
}
public boolean isHeaderPropertiesChanged()
{
return headerPropertiesChanged;
}
public void setHeaderPropertiesChanged()
{
this.headerPropertiesChanged = true;
}
public boolean isFullyChanged()
{
return fullyChanged;
}
public boolean hasChanges()
{
if (fullyChanged)
{
return true;
}
if (headerPropertiesChanged)
{
return true;
}
return changedRowIds != null && !changedRowIds.isEmpty();
}
public void addChangedRowIds(@Nullable final DocumentIdsSelection rowIds)
{
// Don't collect rowIds if this was already flagged as fully changed.
if (fullyChanged)
{
return;
|
}
if (rowIds == null || rowIds.isEmpty())
{
return;
}
else if (rowIds.isAll())
{
fullyChanged = true;
changedRowIds = null;
}
else
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds.toSet());
}
}
public void addChangedRowIds(final Collection<DocumentId> rowIds)
{
if (rowIds.isEmpty())
{
return;
}
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.addAll(rowIds);
}
public void addChangedRowId(@NonNull final DocumentId rowId)
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>();
}
changedRowIds.add(rowId);
}
public DocumentIdsSelection getChangedRowIds()
{
final boolean fullyChanged = this.fullyChanged;
final Set<DocumentId> changedRowIds = this.changedRowIds;
if (fullyChanged)
{
return DocumentIdsSelection.ALL;
}
else if (changedRowIds == null || changedRowIds.isEmpty())
{
return DocumentIdsSelection.EMPTY;
}
else
{
return DocumentIdsSelection.of(changedRowIds);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChanges.java
| 1
|
请完成以下Java代码
|
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean isDone) {
this.isDone = isDone;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
|
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Todo other = (Todo) obj;
if (id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return String.format(
"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id,
user, desc, targetDate, isDone);
}
}
|
repos\SpringBootForBeginners-master\02.Spring-Boot-Web-Application\src\main\java\com\in28minutes\springboot\web\model\Todo.java
| 1
|
请完成以下Java代码
|
public String getBusinessKey() {
return businessKey;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public Map<String, Object> getVariables() {
return modificationBuilder.getProcessVariables();
}
public String getTenantId() {
return tenantId;
}
public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isProcessDefinitionTenantIdSet() {
return isProcessDefinitionTenantIdSet;
}
public void setModificationBuilder(ProcessInstanceModificationBuilderImpl modificationBuilder) {
this.modificationBuilder = modificationBuilder;
}
|
public void setRestartedProcessInstanceId(String restartedProcessInstanceId){
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
public String getRestartedProcessInstanceId(){
return restartedProcessInstanceId;
}
public static ProcessInstantiationBuilder createProcessInstanceById(CommandExecutor commandExecutor, String processDefinitionId) {
ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor);
builder.processDefinitionId = processDefinitionId;
return builder;
}
public static ProcessInstantiationBuilder createProcessInstanceByKey(CommandExecutor commandExecutor, String processDefinitionKey) {
ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor);
builder.processDefinitionKey = processDefinitionKey;
return builder;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstantiationBuilderImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int getFailedAttempts() {
return failedAttempts;
}
public void setFailedAttempts(int failedAttempts) {
this.failedAttempts = failedAttempts;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getSubscriptionsPerConnection() {
return subscriptionsPerConnection;
}
public void setSubscriptionsPerConnection(int subscriptionsPerConnection) {
this.subscriptionsPerConnection = subscriptionsPerConnection;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public int getSubscriptionConnectionMinimumIdleSize() {
return subscriptionConnectionMinimumIdleSize;
}
public void setSubscriptionConnectionMinimumIdleSize(int subscriptionConnectionMinimumIdleSize) {
this.subscriptionConnectionMinimumIdleSize = subscriptionConnectionMinimumIdleSize;
}
public int getSubscriptionConnectionPoolSize() {
return subscriptionConnectionPoolSize;
}
public void setSubscriptionConnectionPoolSize(int subscriptionConnectionPoolSize) {
this.subscriptionConnectionPoolSize = subscriptionConnectionPoolSize;
}
public int getConnectionMinimumIdleSize() {
return connectionMinimumIdleSize;
}
public void setConnectionMinimumIdleSize(int connectionMinimumIdleSize) {
this.connectionMinimumIdleSize = connectionMinimumIdleSize;
|
}
public int getConnectionPoolSize() {
return connectionPoolSize;
}
public void setConnectionPoolSize(int connectionPoolSize) {
this.connectionPoolSize = connectionPoolSize;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public boolean isDnsMonitoring() {
return dnsMonitoring;
}
public void setDnsMonitoring(boolean dnsMonitoring) {
this.dnsMonitoring = dnsMonitoring;
}
public int getDnsMonitoringInterval() {
return dnsMonitoringInterval;
}
public void setDnsMonitoringInterval(int dnsMonitoringInterval) {
this.dnsMonitoringInterval = dnsMonitoringInterval;
}
public String getCodec() {
return codec;
}
public void setCodec(String codec) {
this.codec = codec;
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\config\RedissonConfig.java
| 2
|
请完成以下Java代码
|
public final void setJwtDecoderFactory(JwtDecoderFactory<ClientRegistration> jwtDecoderFactory) {
Assert.notNull(jwtDecoderFactory, "jwtDecoderFactory cannot be null");
this.jwtDecoderFactory = jwtDecoderFactory;
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for mapping
* {@link OidcUser#getAuthorities()}} to a new set of authorities which will be
* associated to the {@link OAuth2LoginAuthenticationToken}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
*/
public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
this.authoritiesMapper = authoritiesMapper;
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication);
}
private OidcIdToken createOidcToken(ClientRegistration clientRegistration,
OAuth2AccessTokenResponse accessTokenResponse) {
JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
Jwt jwt = getJwt(accessTokenResponse, jwtDecoder);
OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(),
jwt.getClaims());
return idToken;
}
|
private Jwt getJwt(OAuth2AccessTokenResponse accessTokenResponse, JwtDecoder jwtDecoder) {
try {
Map<String, Object> parameters = accessTokenResponse.getAdditionalParameters();
return jwtDecoder.decode((String) parameters.get(OidcParameterNames.ID_TOKEN));
}
catch (JwtException ex) {
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, ex.getMessage(), null);
throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), ex);
}
}
static String createHash(String nonce) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
public void login() {
Credential credential = new UsernamePasswordCredential(username, new Password(password));
AuthenticationStatus status = securityContext.authenticate(
getHttpRequestFromFacesContext(),
getHttpResponseFromFacesContext(),
withParams().credential(credential));
if (status.equals(SEND_CONTINUE)) {
facesContext.responseComplete();
} else if (status.equals(SEND_FAILURE)) {
facesContext.addMessage(null,
new FacesMessage(SEVERITY_ERROR, "Authentication failed", null));
}
}
private HttpServletRequest getHttpRequestFromFacesContext() {
return (HttpServletRequest) facesContext
.getExternalContext()
.getRequest();
}
private HttpServletResponse getHttpResponseFromFacesContext() {
return (HttpServletResponse) facesContext
.getExternalContext()
|
.getResponse();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
repos\tutorials-master\security-modules\java-ee-8-security-api\app-auth-custom-form-store-custom\src\main\java\com\baeldung\javaee\security\LoginBean.java
| 1
|
请完成以下Java代码
|
public class X_M_Product_Relationship extends org.compiere.model.PO implements I_M_Product_Relationship, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1246567907L;
/** Standard Constructor */
public X_M_Product_Relationship (final Properties ctx, final int M_Product_Relationship_ID, @Nullable final String trxName)
{
super (ctx, M_Product_Relationship_ID, trxName);
}
/** Load Constructor */
public X_M_Product_Relationship (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* AD_RelationType_ID AD_Reference_ID=541357
* Reference name: Product Relation Types
*/
public static final int AD_RELATIONTYPE_ID_AD_Reference_ID=541357;
/** Parent Product = Parent */
public static final String AD_RELATIONTYPE_ID_ParentProduct = "Parent";
@Override
public void setAD_RelationType_ID (final java.lang.String AD_RelationType_ID)
{
set_Value (COLUMNNAME_AD_RelationType_ID, AD_RelationType_ID);
}
@Override
public java.lang.String getAD_RelationType_ID()
{
return get_ValueAsString(COLUMNNAME_AD_RelationType_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setM_Product_Relationship_ID (final int M_Product_Relationship_ID)
{
if (M_Product_Relationship_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_Relationship_ID, M_Product_Relationship_ID);
}
@Override
public int getM_Product_Relationship_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Relationship_ID);
}
@Override
public void setRelatedProduct_ID (final int RelatedProduct_ID)
{
if (RelatedProduct_ID < 1)
set_Value (COLUMNNAME_RelatedProduct_ID, null);
else
set_Value (COLUMNNAME_RelatedProduct_ID, RelatedProduct_ID);
}
@Override
public int getRelatedProduct_ID()
{
return get_ValueAsInt(COLUMNNAME_RelatedProduct_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Relationship.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Comment {
@Id
@GeneratedValue private Long id;
private String country;
private String description;
@JdbcTypeCode(SqlTypes.VECTOR)
@Array(length = 5) private float[] embedding;
public Comment() {}
public Comment(String country, String description, float[] embedding) {
this.country = country;
this.description = description;
this.embedding = embedding;
}
public static Comment of(Comment source) {
return new Comment(source.getCountry(), source.getDescription(), source.getEmbedding());
}
public long getId() {
return id;
}
|
public String getCountry() {
return country;
}
public String getDescription() {
return description;
}
public float[] getEmbedding() {
return embedding;
}
@Override
public String toString() {
return "%s (%s)".formatted(getDescription(), getCountry());
}
}
|
repos\spring-data-examples-main\jpa\vector-search\src\main\java\example\springdata\vector\Comment.java
| 2
|
请完成以下Java代码
|
public boolean isImmutable(@NonNull final Class<?> clazz)
{
// Primitive types are always immutable
if (clazz.isPrimitive())
{
return true;
}
// Assume IDs are immutable
if (RepoIdAware.class.isAssignableFrom(clazz))
{
return true;
}
for (final Class<?> immutableClass : immutableClasses)
{
if (immutableClass.isAssignableFrom(clazz))
{
return true;
|
}
}
return false;
}
/**
* Register a new immutable class.
*
* WARNING: to be used only if it's really needed because this is kind of dirty hack which could affect our caching system.
*
* @param immutableClass
*/
public void registerImmutableClass(@NonNull final Class<?> immutableClass)
{
immutableClasses.add(immutableClass);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheImmutableClassesIndex.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException{
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(()-> new ResourceNotFoundException("Employee not found for this id: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/emp1")
public Employee createEmployee(@Valid @RequestBody Employee employee){
return employeeRepository.save(employee);
}
@PostMapping("/emp")
public ResponseEntity<Employee> updateEmployee(@PathVariable (value="id") Long empId, @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException{
Employee employee = employeeRepository.findById(empId)
.orElseThrow(()-> new ResourceNotFoundException("Employee not found for this id::" + empId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
|
final Employee updateEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updateEmployee);
}
@DeleteMapping("/emp/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(()-> new ResourceNotFoundException("Employee not found for this id::" + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringRestDB\src\main\java\spring\restdb\controller\EmployeeController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private static void addSuperTypesForClass(ResolvableType resolvableType, Set<Class<?>> supertypesToAdd,
Set<Class<?>> genericsToAdd) {
ResolvableType superType = resolvableType.getSuperType();
if (!ResolvableType.NONE.equals(superType)) {
addGenericsForClass(genericsToAdd, superType);
supertypesToAdd.add(superType.toClass());
addSuperTypesForClass(superType, supertypesToAdd, genericsToAdd);
}
}
@SuppressWarnings({ "rawtypes" })
private static Set<Class<?>> getClassesToAdd() {
Set<Class<?>> classesToAdd = new HashSet<>();
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Configurable.class));
Set<BeanDefinition> components = provider.findCandidateComponents(ROOT_GATEWAY_PACKAGE_NAME);
for (BeanDefinition component : components) {
Class clazz;
try {
clazz = Class.forName(component.getBeanClassName());
if (shouldRegisterClass(clazz)) {
classesToAdd.add(clazz);
}
}
catch (NoClassDefFoundError | ClassNotFoundException exception) {
if (LOG.isDebugEnabled()) {
LOG.debug(exception);
|
}
}
}
return classesToAdd;
}
private static boolean shouldRegisterClass(Class<?> clazz) {
Set<String> conditionClasses = beansConditionalOnClasses.getOrDefault(clazz, Collections.emptySet());
for (String conditionClass : conditionClasses) {
try {
ConfigurableHintsRegistrationProcessor.class.getClassLoader().loadClass(conditionClass);
}
catch (ClassNotFoundException e) {
return false;
}
}
return true;
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\ConfigurableHintsRegistrationProcessor.java
| 2
|
请完成以下Java代码
|
public boolean recomputeIsDocumentAcknowledged()
{
final boolean isDocumentAcknowledged_refreshedValue = lines.stream().allMatch(RemittanceAdviceLine::isReadyForCompletion);
final boolean hasAcknowledgedStatusChanged = isDocumentAcknowledged != isDocumentAcknowledged_refreshedValue;
this.isDocumentAcknowledged = isDocumentAcknowledged_refreshedValue;
return hasAcknowledgedStatusChanged;
}
/**
* @return true, if read only currencies flag changed, false otherwise
*/
public boolean recomputeCurrenciesReadOnlyFlag()
{
|
final boolean currenciesReadOnlyFlag_refreshedValue = lines.stream().anyMatch(RemittanceAdviceLine::isInvoiceResolved);
final boolean currenciesReadOnlyFlagChanged = currenciesReadOnlyFlag != currenciesReadOnlyFlag_refreshedValue;
this.currenciesReadOnlyFlag = currenciesReadOnlyFlag_refreshedValue;
return currenciesReadOnlyFlagChanged;
}
public void setProcessedFlag(final boolean processed)
{
this.processed = processed;
getLines().forEach(line -> line.setProcessed(processed));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\RemittanceAdvice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private SecretKey getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
return Keys.hmacShaKeyFor(keyBytes);
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(authToken);
return true;
|
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\jwtconfig\JwtUtils.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
|
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootCloneEntity\src\main\java\com\bookstore\entity\Book.java
| 1
|
请完成以下Java代码
|
public class DateUtil {
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd-M月-y hh.mm.ss.S a", Locale.CHINA);
private static final SimpleDateFormat sdf2 = new SimpleDateFormat("dd-M月 -y hh.mm.ss.S a", Locale.CHINA);
public static synchronized Date parseDatetime(String dateStr) {
try {
return sdf.parse(dateStr);
} catch (ParseException e) {
return new Date();
}
}
public static synchronized Timestamp parseTimestamp(String dateStr) {
try {
return new Timestamp(sdf.parse(dateStr).getTime());
} catch (ParseException e) {
try {
|
return new Timestamp(sdf2.parse(dateStr).getTime());
} catch (ParseException ee) {
return new Timestamp(System.currentTimeMillis());
}
}
}
public static synchronized String formatTimestamp(Timestamp date) {
return sdf.format(date);
}
public static void main(String[] args) {
Timestamp t = parseTimestamp("08-12月-17 05.38.07.859000 下午");
System.out.println(t);
System.out.println(formatTimestamp(t));
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\DateUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class ThreadPoolTaskSchedulerBuilderConfiguration {
@Bean
@ConditionalOnMissingBean
ThreadPoolTaskSchedulerBuilder threadPoolTaskSchedulerBuilder(TaskSchedulingProperties properties,
ObjectProvider<TaskDecorator> taskDecorator,
ObjectProvider<ThreadPoolTaskSchedulerCustomizer> threadPoolTaskSchedulerCustomizers) {
TaskSchedulingProperties.Shutdown shutdown = properties.getShutdown();
ThreadPoolTaskSchedulerBuilder builder = new ThreadPoolTaskSchedulerBuilder();
builder = builder.poolSize(properties.getPool().getSize());
builder = builder.awaitTermination(shutdown.isAwaitTermination());
builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
builder = builder.taskDecorator(getTaskDecorator(taskDecorator));
builder = builder.customizers(threadPoolTaskSchedulerCustomizers);
return builder;
}
}
@Configuration(proxyBeanMethods = false)
static class SimpleAsyncTaskSchedulerBuilderConfiguration {
private final TaskSchedulingProperties properties;
private final ObjectProvider<TaskDecorator> taskDecorator;
private final ObjectProvider<SimpleAsyncTaskSchedulerCustomizer> taskSchedulerCustomizers;
SimpleAsyncTaskSchedulerBuilderConfiguration(TaskSchedulingProperties properties,
ObjectProvider<TaskDecorator> taskDecorator,
ObjectProvider<SimpleAsyncTaskSchedulerCustomizer> taskSchedulerCustomizers) {
this.properties = properties;
this.taskDecorator = taskDecorator;
|
this.taskSchedulerCustomizers = taskSchedulerCustomizers;
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnThreading(Threading.PLATFORM)
SimpleAsyncTaskSchedulerBuilder simpleAsyncTaskSchedulerBuilder() {
return builder();
}
@Bean(name = "simpleAsyncTaskSchedulerBuilder")
@ConditionalOnMissingBean
@ConditionalOnThreading(Threading.VIRTUAL)
SimpleAsyncTaskSchedulerBuilder simpleAsyncTaskSchedulerBuilderVirtualThreads() {
return builder().virtualThreads(true);
}
private SimpleAsyncTaskSchedulerBuilder builder() {
SimpleAsyncTaskSchedulerBuilder builder = new SimpleAsyncTaskSchedulerBuilder();
builder = builder.threadNamePrefix(this.properties.getThreadNamePrefix());
builder = builder.taskDecorator(getTaskDecorator(this.taskDecorator));
builder = builder.customizers(this.taskSchedulerCustomizers.orderedStream()::iterator);
TaskSchedulingProperties.Simple simple = this.properties.getSimple();
builder = builder.concurrencyLimit(simple.getConcurrencyLimit());
TaskSchedulingProperties.Shutdown shutdown = this.properties.getShutdown();
if (shutdown.isAwaitTermination()) {
builder = builder.taskTerminationTimeout(shutdown.getAwaitTerminationPeriod());
}
return builder;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskSchedulingConfigurations.java
| 2
|
请完成以下Java代码
|
public class MaterialTrackingInvoiceCandidateListener implements IInvoiceCandidateListener
{
public static final MaterialTrackingInvoiceCandidateListener instance = new MaterialTrackingInvoiceCandidateListener();
private MaterialTrackingInvoiceCandidateListener()
{
}
@Override
public void onBeforeInvoiceLineCreated(final I_C_InvoiceLine invoiceLine, final IInvoiceLineRW fromInvoiceLine, final List<I_C_Invoice_Candidate> fromCandidates)
{
//
// Get material tracking of those invoice candidates
final I_M_Material_Tracking materialTracking = retrieveMaterialTracking(fromCandidates);
if (materialTracking == null)
{
return;
}
//
// Assign the invoice to material tracking
final I_C_Invoice invoice = invoiceLine.getC_Invoice();
final IMaterialTrackingBL materialTrackingBL = Services.get(IMaterialTrackingBL.class);
materialTrackingBL.linkModelToMaterialTracking(
MTLinkRequest.builder()
.model(invoice)
.materialTrackingRecord(materialTracking)
.ifModelAlreadyLinked(IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS)
.build()
);
}
private I_M_Material_Tracking retrieveMaterialTracking(final List<I_C_Invoice_Candidate> invoiceCandidates)
{
// no candidates => nothing to do (shall not happen)
if (invoiceCandidates == null || invoiceCandidates.isEmpty())
{
|
return null;
}
final I_M_Material_Tracking materialTracking = InterfaceWrapperHelper.create(invoiceCandidates.get(0), de.metas.materialtracking.model.I_C_Invoice_Candidate.class).getM_Material_Tracking();
for (final I_C_Invoice_Candidate fromInvoiceCandidate : invoiceCandidates)
{
final de.metas.materialtracking.model.I_C_Invoice_Candidate invoicecandExt = InterfaceWrapperHelper.create(fromInvoiceCandidate,
de.metas.materialtracking.model.I_C_Invoice_Candidate.class);
final int materialTrackingID = materialTracking == null ? 0 : materialTracking.getM_Material_Tracking_ID();
Check.assume(materialTrackingID == invoicecandExt.getM_Material_Tracking_ID(),
"All I_C_InvoiceCandidates from the list have the same M_Material_Tracking_ID: {}", invoiceCandidates);
}
return materialTracking;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\ic\spi\impl\MaterialTrackingInvoiceCandidateListener.java
| 1
|
请完成以下Java代码
|
public HUAttributeQueryFilterVO assertAttributeValueType(@NonNull final String attributeValueType)
{
Check.assume(
Objects.equals(this.attributeValueType, attributeValueType),
"Invalid attributeValueType for {}. Expected: {}",
this, attributeValueType);
return this;
}
private ModelColumn<I_M_HU_Attribute, Object> getHUAttributeValueColumn()
{
return huAttributeValueColumn;
}
private Set<Object> getValues()
{
return _values;
}
private Set<Object> getValuesAndSubstitutes()
{
if (_valuesAndSubstitutes != null)
{
return _valuesAndSubstitutes;
}
final ModelColumn<I_M_HU_Attribute, Object> valueColumn = getHUAttributeValueColumn();
final boolean isStringValueColumn = I_M_HU_Attribute.COLUMNNAME_Value.equals(valueColumn.getColumnName());
|
final Set<Object> valuesAndSubstitutes = new HashSet<>();
//
// Iterate current values
for (final Object value : getValues())
{
// Append current value to result
valuesAndSubstitutes.add(value);
// Search and append it's substitutes too, if found
if (isStringValueColumn && value instanceof String)
{
final String valueStr = value.toString();
final I_M_Attribute attribute = getM_Attribute();
final Set<String> valueSubstitutes = attributeDAO.retrieveAttributeValueSubstitutes(attribute, valueStr);
valuesAndSubstitutes.addAll(valueSubstitutes);
}
}
_valuesAndSubstitutes = valuesAndSubstitutes;
return _valuesAndSubstitutes;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAttributeQueryFilterVO.java
| 1
|
请完成以下Java代码
|
public Set<ConvertiblePair> getConvertibleTypes() {
Set<ConvertiblePair> convertibleTypes = new LinkedHashSet<>();
convertibleTypes.add(new ConvertiblePair(Object.class, List.class));
convertibleTypes.add(new ConvertiblePair(Object.class, Collection.class));
return convertibleTypes;
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
TypeDescriptor typeDescriptor = targetType.getElementTypeDescriptor();
return typeDescriptor == null || typeDescriptor.getType().equals(String.class) || sourceType == null
|| ClassUtils.isAssignable(sourceType.getType(), typeDescriptor.getType());
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
if (source == null) {
return null;
}
if (source instanceof Collection) {
Collection<String> results = new ArrayList<>();
for (Object object : ((Collection<?>) source)) {
if (object != null) {
results.add(object.toString());
}
}
return results;
}
return Collections.singletonList(source.toString());
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\converter\ObjectToListStringConverter.java
| 1
|
请完成以下Java代码
|
protected void doClose() {
if (isActive()) {
AvailabilityChangeEvent.publish(this, ReadinessState.REFUSING_TRAFFIC);
}
super.doClose();
WebServer webServer = getWebServer();
if (webServer != null) {
webServer.destroy();
}
}
/**
* Returns the {@link WebServer} that was created by the context or {@code null} if
* the server has not yet been created.
* @return the web server
*/
@Override
|
public @Nullable WebServer getWebServer() {
WebServerManager serverManager = this.serverManager;
return (serverManager != null) ? serverManager.getWebServer() : null;
}
@Override
public @Nullable String getServerNamespace() {
return this.serverNamespace;
}
@Override
public void setServerNamespace(@Nullable String serverNamespace) {
this.serverNamespace = serverNamespace;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\ReactiveWebServerApplicationContext.java
| 1
|
请完成以下Java代码
|
public class LexicalAnalyzerPipe implements Pipe<List<IWord>, List<IWord>>
{
/**
* 代理的词法分析器
*/
protected LexicalAnalyzer analyzer;
public LexicalAnalyzerPipe(LexicalAnalyzer analyzer)
{
this.analyzer = analyzer;
}
@Override
public List<IWord> flow(List<IWord> input)
{
ListIterator<IWord> listIterator = input.listIterator();
|
while (listIterator.hasNext())
{
IWord wordOrSentence = listIterator.next();
if (wordOrSentence.getLabel() != null)
continue; // 这是别的管道已经处理过的单词,跳过
listIterator.remove(); // 否则是句子
String sentence = wordOrSentence.getValue();
for (IWord word : analyzer.analyze(sentence))
{
listIterator.add(word);
}
}
return input;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\LexicalAnalyzerPipe.java
| 1
|
请完成以下Java代码
|
public class PoiUtils {
private PoiUtils() {
}
private static void newCell(Row row, String value) {
short cellNum = row.getLastCellNum();
if (cellNum == -1)
cellNum = 0;
Cell cell = row.createCell(cellNum);
cell.setCellValue(value);
}
public static Row newRow(Sheet sheet, String... rowValues) {
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
for (String value : rowValues) {
newCell(row, value);
}
return row;
}
|
public static CellStyle boldFontStyle(Workbook workbook) {
Font boldFont = workbook.createFont();
boldFont.setBold(true);
CellStyle boldStyle = workbook.createCellStyle();
boldStyle.setFont(boldFont);
return boldStyle;
}
public static void write(Workbook workbook, Path path) throws IOException {
try (FileOutputStream fileOut = new FileOutputStream(path.toFile())) {
workbook.write(fileOut);
}
}
}
|
repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\poi\rowstyle\PoiUtils.java
| 1
|
请完成以下Java代码
|
public int idOf(String string)
{
return dat.get(string);
}
@Override
public int size()
{
return dat.size();
}
@Override
public Set<Map.Entry<String, Integer>> entrySet()
{
return dat.entrySet();
}
|
@Override
public void save(DataOutputStream out) throws IOException
{
tagSet.save(out);
dat.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
loadTagSet(byteArray);
return dat.load(byteArray);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\feature\ImmutableFeatureMDatMap.java
| 1
|
请完成以下Java代码
|
public void setCol_8 (BigDecimal Col_8)
{
set_Value (COLUMNNAME_Col_8, Col_8);
}
/** Get Col_8.
@return Col_8 */
public BigDecimal getCol_8 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Col_8);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Payroll List Line.
@param HR_ListLine_ID Payroll List Line */
public void setHR_ListLine_ID (int HR_ListLine_ID)
{
if (HR_ListLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListLine_ID, Integer.valueOf(HR_ListLine_ID));
}
/** Get Payroll List Line.
@return Payroll List Line */
public int getHR_ListLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.eevolution.model.I_HR_ListVersion getHR_ListVersion() throws RuntimeException
{
return (org.eevolution.model.I_HR_ListVersion)MTable.get(getCtx(), org.eevolution.model.I_HR_ListVersion.Table_Name)
.getPO(getHR_ListVersion_ID(), get_TrxName()); }
/** Set Payroll List Version.
@param HR_ListVersion_ID Payroll List Version */
public void setHR_ListVersion_ID (int HR_ListVersion_ID)
{
if (HR_ListVersion_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, Integer.valueOf(HR_ListVersion_ID));
}
/** Get Payroll List Version.
@return Payroll List Version */
public int getHR_ListVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Max Value.
@param MaxValue Max Value */
public void setMaxValue (BigDecimal MaxValue)
{
set_Value (COLUMNNAME_MaxValue, MaxValue);
}
/** Get Max Value.
@return Max Value */
|
public BigDecimal getMaxValue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxValue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Min Value.
@param MinValue Min Value */
public void setMinValue (BigDecimal MinValue)
{
set_Value (COLUMNNAME_MinValue, MinValue);
}
/** Get Min Value.
@return Min Value */
public BigDecimal getMinValue ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinValue);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListLine.java
| 1
|
请完成以下Java代码
|
public SubProcessBuilder builder() {
return new SubProcessBuilder((BpmnModelInstance) modelInstance, this);
}
public boolean triggeredByEvent() {
return triggeredByEventAttribute.getValue(this);
}
public void setTriggeredByEvent(boolean triggeredByEvent) {
triggeredByEventAttribute.setValue(this, triggeredByEvent);
}
public Collection<LaneSet> getLaneSets() {
return laneSetCollection.get(this);
}
public Collection<FlowElement> getFlowElements() {
return flowElementCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
|
return artifactCollection.get(this);
}
/** camunda extensions */
/**
* @deprecated use isCamundaAsyncBefore() instead.
*/
@Deprecated
public boolean isCamundaAsync() {
return camundaAsyncAttribute.getValue(this);
}
/**
* @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead.
*/
@Deprecated
public void setCamundaAsync(boolean isCamundaAsync) {
camundaAsyncAttribute.setValue(this, isCamundaAsync);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SubProcessImpl.java
| 1
|
请完成以下Java代码
|
class DiscoveredWebEndpoint extends AbstractDiscoveredEndpoint<WebOperation> implements ExposableWebEndpoint {
private final String rootPath;
private Collection<AdditionalPathsMapper> additionalPathsMappers;
DiscoveredWebEndpoint(EndpointDiscoverer<?, ?> discoverer, Object endpointBean, EndpointId id, String rootPath,
Access defaultAccess, Collection<WebOperation> operations,
Collection<AdditionalPathsMapper> additionalPathsMappers) {
super(discoverer, endpointBean, id, defaultAccess, operations);
this.rootPath = rootPath;
this.additionalPathsMappers = additionalPathsMappers;
}
@Override
public String getRootPath() {
return this.rootPath;
|
}
@Override
public List<String> getAdditionalPaths(WebServerNamespace webServerNamespace) {
return this.additionalPathsMappers.stream()
.flatMap((mapper) -> getAdditionalPaths(webServerNamespace, mapper))
.toList();
}
private Stream<String> getAdditionalPaths(WebServerNamespace webServerNamespace, AdditionalPathsMapper mapper) {
List<String> additionalPaths = mapper.getAdditionalPaths(getEndpointId(), webServerNamespace);
return (additionalPaths != null) ? additionalPaths.stream() : Stream.empty();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\web\annotation\DiscoveredWebEndpoint.java
| 1
|
请完成以下Java代码
|
public class Person {
private String name;
private int age;
Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
|
repos\tutorials-master\vavr-modules\vavr\src\main\java\com\baeldung\vavr\Person.java
| 1
|
请完成以下Java代码
|
public java.lang.String getapplicationID()
{
return get_ValueAsString(COLUMNNAME_applicationID);
}
@Override
public void setApplicationToken (final @Nullable java.lang.String ApplicationToken)
{
set_Value (COLUMNNAME_ApplicationToken, ApplicationToken);
}
@Override
public java.lang.String getApplicationToken()
{
return get_ValueAsString(COLUMNNAME_ApplicationToken);
}
@Override
public void setdhl_api_url (final @Nullable java.lang.String dhl_api_url)
{
set_Value (COLUMNNAME_dhl_api_url, dhl_api_url);
}
@Override
public java.lang.String getdhl_api_url()
{
return get_ValueAsString(COLUMNNAME_dhl_api_url);
}
@Override
public void setDhl_LenghtUOM_ID (final int Dhl_LenghtUOM_ID)
{
if (Dhl_LenghtUOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_Dhl_LenghtUOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Dhl_LenghtUOM_ID, Dhl_LenghtUOM_ID);
}
@Override
public int getDhl_LenghtUOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Dhl_LenghtUOM_ID);
}
@Override
public void setDHL_Shipper_Config_ID (final int DHL_Shipper_Config_ID)
{
if (DHL_Shipper_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DHL_Shipper_Config_ID, DHL_Shipper_Config_ID);
}
@Override
public int getDHL_Shipper_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_DHL_Shipper_Config_ID);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper()
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
|
@Override
public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setSignature (final @Nullable java.lang.String Signature)
{
set_Value (COLUMNNAME_Signature, Signature);
}
@Override
public java.lang.String getSignature()
{
return get_ValueAsString(COLUMNNAME_Signature);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_Shipper_Config.java
| 1
|
请完成以下Java代码
|
public ExecutionDto getExecution() {
RuntimeService runtimeService = engine.getRuntimeService();
Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
if (execution == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Execution with id " + executionId + " does not exist");
}
return ExecutionDto.fromExecution(execution);
}
@Override
public void signalExecution(ExecutionTriggerDto triggerDto) {
RuntimeService runtimeService = engine.getRuntimeService();
try {
VariableMap variables = VariableValueDto.toMap(triggerDto.getVariables(), engine, objectMapper);
runtimeService.signal(executionId, variables);
} catch (RestException e) {
String errorMessage = String.format("Cannot signal execution %s: %s", executionId, e.getMessage());
throw new InvalidRequestException(e.getStatus(), e, errorMessage);
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Cannot signal execution " + executionId + ": " + e.getMessage());
}
}
@Override
public VariableResource getLocalVariables() {
return new LocalExecutionVariablesResource(engine, executionId, objectMapper);
|
}
@Override
public EventSubscriptionResource getMessageEventSubscription(String messageName) {
return new MessageEventSubscriptionResource(engine, executionId, messageName, objectMapper);
}
@Override
public IncidentDto createIncident(CreateIncidentDto createIncidentDto) {
Incident newIncident = null;
try {
newIncident = engine.getRuntimeService()
.createIncident(createIncidentDto.getIncidentType(), executionId, createIncidentDto.getConfiguration(), createIncidentDto.getMessage());
} catch (BadUserRequestException e) {
throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage());
}
return IncidentDto.fromIncident(newIncident);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\ExecutionResourceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CounterController {
private static final String HEADER_ONE = "<h1>%s</h1>";
private final CounterService counterService;
public CounterController(CounterService counterService) {
Assert.notNull(counterService, "CounterService is required");
this.counterService = counterService;
}
@GetMapping("/")
public String home() {
return String.format(HEADER_ONE, "Look-Aside Caching Example");
}
@GetMapping("/ping")
public String ping() {
return String.format(HEADER_ONE, "PONG");
}
@GetMapping("counter/{name}")
public String getCount(@PathVariable("name") String counterName) {
|
return String.format(HEADER_ONE, this.counterService.getCount(counterName));
}
@GetMapping("counter/{name}/cached")
public String getCachedCount(@PathVariable("name") String counterName) {
return String.format(HEADER_ONE, this.counterService.getCachedCount(counterName));
}
@GetMapping("counter/{name}/reset")
public String resetCounter(@PathVariable("name") String counterName) {
this.counterService.resetCounter(counterName);
return String.format(HEADER_ONE, "0");
}
}
// end::class[]
|
repos\spring-boot-data-geode-main\spring-geode-samples\caching\look-aside\src\main\java\example\app\caching\lookaside\controller\CounterController.java
| 2
|
请完成以下Java代码
|
public SpinDataFormatException multipleProvidersForDataformat(String dataFormatName) {
return new SpinDataFormatException(exceptionMessage("008", "Multiple providers found for dataformat '{}'", dataFormatName));
}
public void logDataFormats(Collection<DataFormat<?>> formats) {
if (isInfoEnabled()) {
for (DataFormat<?> format : formats) {
logDataFormat(format);
}
}
}
protected void logDataFormat(DataFormat<?> dataFormat) {
logInfo("009", "Discovered Spin data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName());
}
public void logDataFormatProvider(DataFormatProvider provider) {
if (isInfoEnabled()) {
logInfo("010", "Discovered Spin data format provider: {}[name = {}]",
provider.getClass().getName(), provider.getDataFormatName());
}
|
}
@SuppressWarnings("rawtypes")
public void logDataFormatConfigurator(DataFormatConfigurator configurator) {
if (isInfoEnabled()) {
logInfo("011", "Discovered Spin data format configurator: {}[dataformat = {}]",
configurator.getClass(), configurator.getDataFormatClass().getName());
}
}
public SpinDataFormatException classNotFound(String classname, ClassNotFoundException cause) {
return new SpinDataFormatException(exceptionMessage("012", "Class {} not found ", classname), cause);
}
public void tryLoadingClass(String classname, ClassLoader cl) {
logDebug("013", "Try loading class '{}' using classloader '{}'.", classname, cl);
}
}
|
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\logging\SpinCoreLogger.java
| 1
|
请完成以下Java代码
|
public static <T> ExtendedMemorizingSupplier<T> of(final java.util.function.Supplier<T> supplier)
{
if (supplier instanceof ExtendedMemorizingSupplier)
{
return (ExtendedMemorizingSupplier<T>)supplier;
}
return new ExtendedMemorizingSupplier<>(supplier);
}
private final java.util.function.Supplier<T> delegate;
private transient volatile boolean initialized;
// "value" does not need to be volatile; visibility piggy-backs
// on volatile read of "initialized".
// metas-ts: Setting it to be volatile none the less, because we somehow managed to get an NPE with a delegate supplier that could not have returned null.
// See https://github.com/metasfresh/metasfresh/issues/4985
@Nullable
private transient volatile T value;
private ExtendedMemorizingSupplier(final java.util.function.Supplier<T> delegate)
{
this.delegate = delegate;
}
@Override
@Nullable
public T get()
{
// A 2-field variant of Double Checked Locking.
if (!initialized)
{
synchronized (this)
{
if (!initialized)
{
final T t = delegate.get();
value = t;
initialized = true;
return t;
}
}
}
return value;
}
@NonNull
public T getNotNull() {return Check.assumeNotNull(get(), "Supplier is expected to return non null value");}
/**
* @return memorized value or <code>null</code> if not initialized
*/
@Nullable
public T peek()
{
synchronized (this)
{
return value;
}
}
/**
* Forget memorized value
*
* @return current value if any
*/
@Nullable
public T forget()
|
{
// https://github.com/metasfresh/metasfresh-webui-api/issues/787 - similar to the code of get();
// if the instance known to not be initialized
// then don't attempt to acquire lock (and to other time consuming stuff..)
if (initialized)
{
synchronized (this)
{
if (initialized)
{
final T valueOld = this.value;
initialized = false;
value = null;
return valueOld;
}
}
}
return null;
}
/**
* @return true if this supplier has a value memorized
*/
public boolean isInitialized()
{
return initialized;
}
@Override
public String toString()
{
return "ExtendedMemorizingSupplier[" + delegate + "]";
}
private static final long serialVersionUID = 0;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\lang\ExtendedMemorizingSupplier.java
| 1
|
请完成以下Java代码
|
private class SumTask implements Callable<Long> {
private int[] numbers;
private int from;
private int to;
public SumTask(int[] numbers, int from, int to) {
this.numbers = numbers;
this.from = from;
this.to = to;
}
public Long call() throws Exception {
long total = 0L;
for (int i = from; i < to; i++) {
total += numbers[i];
}
return total;
}
}
public long sum(int[] numbers) {
int chunk = numbers.length / nThreads;
int from, to;
List<SumTask> tasks = new ArrayList<SumTask>();
for (int i = 1; i <= nThreads; i++) {
if (i == nThreads) {
from = (i - 1) * chunk;
to = numbers.length;
} else {
|
from = (i - 1) * chunk;
to = i * chunk;
}
tasks.add(new SumTask(numbers, from, to));
}
try {
List<Future<Long>> futures = pool.invokeAll(tasks);
long total = 0L;
for (Future<Long> future : futures) {
total += future.get();
}
return total;
} catch (Exception e) {
// ignore
return 0;
}
}
@Override
public void shutdown() {
pool.shutdown();
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\sum\calc\impl\MultithreadCalculator.java
| 1
|
请完成以下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 I_ExternalSystem_Config_Shopware6 getExternalSystem_Config_Shopware6()
{
return get_ValueAsPO(COLUMNNAME_ExternalSystem_Config_Shopware6_ID, I_ExternalSystem_Config_Shopware6.class);
}
@Override
public void setExternalSystem_Config_Shopware6(final I_ExternalSystem_Config_Shopware6 ExternalSystem_Config_Shopware6)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Config_Shopware6_ID, I_ExternalSystem_Config_Shopware6.class, ExternalSystem_Config_Shopware6);
}
@Override
public void setExternalSystem_Config_Shopware6_ID (final int ExternalSystem_Config_Shopware6_ID)
{
if (ExternalSystem_Config_Shopware6_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_Shopware6_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_Shopware6_ID, ExternalSystem_Config_Shopware6_ID);
}
|
@Override
public int getExternalSystem_Config_Shopware6_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Shopware6_ID);
}
@Override
public void setExternalSystem_Config_Shopware6_UOM_ID (final int ExternalSystem_Config_Shopware6_UOM_ID)
{
if (ExternalSystem_Config_Shopware6_UOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID, ExternalSystem_Config_Shopware6_UOM_ID);
}
@Override
public int getExternalSystem_Config_Shopware6_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_Shopware6_UOM_ID);
}
@Override
public void setShopwareCode (final String ShopwareCode)
{
set_Value (COLUMNNAME_ShopwareCode, ShopwareCode);
}
@Override
public String getShopwareCode()
{
return get_ValueAsString(COLUMNNAME_ShopwareCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_Shopware6_UOM.java
| 1
|
请完成以下Java代码
|
public static boolean getBoolean(Map<String, String> requestParams, String name, boolean defaultValue) {
boolean value = defaultValue;
if (requestParams.get(name) != null) {
value = Boolean.valueOf(requestParams.get(name));
}
return value;
}
public static int getInteger(Map<String, String> requestParams, String name, int defaultValue) {
int value = defaultValue;
if (requestParams.get(name) != null) {
value = Integer.valueOf(requestParams.get(name));
}
return value;
}
public static Date getDate(Map<String, String> requestParams, String name) {
if (requestParams != null && name != null) {
return parseLongDate(requestParams.get(name));
}
return null;
}
public static Date parseLongDate(String aDate) {
OffsetDateTime offsetDateTime = OffsetDateTime.parse(aDate, longDateFormat);
return Date.from(offsetDateTime.toInstant());
}
public static String dateToString(Date date) {
String dateString = null;
if (date != null) {
dateString = longDateFormatOutputFormater.format(date);
}
return dateString;
}
public static Integer parseToInteger(String integer) {
Integer parsedInteger = null;
try {
parsedInteger = Integer.parseInt(integer);
} catch (Exception e) {
}
|
return parsedInteger;
}
public static Date parseToDate(String date) {
Date parsedDate = null;
try {
parsedDate = shortDateFormat.parse(date);
} catch (Exception e) {
}
return parsedDate;
}
public static List<String> parseToList(String value) {
if (value == null || value.isEmpty()) {
return null;
}
String[] valueParts = value.split(",");
List<String> values = new ArrayList<>(valueParts.length);
Collections.addAll(values, valueParts);
return values;
}
public static Set<String> parseToSet(String value) {
if (value == null || value.isEmpty()) {
return null;
}
String[] valueParts = value.split(",");
Set<String> values = new HashSet<>(valueParts.length);
Collections.addAll(values, valueParts);
return values;
}
}
|
repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\RequestUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SingleHUInventoryLineAggregator implements InventoryLineAggregator
{
@VisibleForTesting
public static final SingleHUInventoryLineAggregator INSTANCE = new SingleHUInventoryLineAggregator();
private SingleHUInventoryLineAggregator()
{
}
@Override
public InventoryLineAggregationKey createAggregationKey(@NonNull final HuForInventoryLine huForInventoryLine)
{
return new SingleHUInventoryLineInventoryLineAggregationKey(huForInventoryLine.getHuId(), huForInventoryLine.getHuQRCode(), huForInventoryLine.getProductId());
}
@Override
public InventoryLineAggregationKey createAggregationKey(@NonNull final InventoryLine inventoryLine)
{
final InventoryLineHU singleLineHU = inventoryLine.getSingleLineHU();
return new SingleHUInventoryLineInventoryLineAggregationKey(singleLineHU.getHuId(), singleLineHU.getHuQRCode(), inventoryLine.getProductId());
}
@Override
public AggregationType getAggregationType()
{
|
return AggregationType.SINGLE_HU;
}
@Value
private static class SingleHUInventoryLineInventoryLineAggregationKey implements InventoryLineAggregationKey
{
@Nullable HuId huId;
@Nullable HUQRCode huQRCode;
@NonNull ProductId productId;
SingleHUInventoryLineInventoryLineAggregationKey(
@Nullable final HuId huId,
@Nullable final HUQRCode huQRCode,
@NonNull final ProductId productId)
{
if (huId == null && huQRCode == null)
{
throw new AdempiereException("At least huId or huQRCode must be set");
}
this.huId = huId;
this.huQRCode = huQRCode;
this.productId = productId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\aggregator\SingleHUInventoryLineAggregator.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Free text description of the attachment.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* The MIME type of the attachment. E.g., 'application/pdf' for PDF attachments.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getMimeType() {
return mimeType;
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
/**
* The actual attachment data as base64-encoded String.
*
* @return
* possible object is
* byte[]
*/
public byte[] getAttachmentData() {
return attachmentData;
}
/**
* Sets the value of the attachmentData property.
*
* @param value
* allowed object is
* byte[]
*/
public void setAttachmentData(byte[] value) {
this.attachmentData = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\AttachmentType.java
| 2
|
请完成以下Java代码
|
public <RecordType> void appendFilter(@NonNull final IQueryBuilder<RecordType> queryBuilder, @NonNull final String columnName)
{
map(new CaseMappingFunction<T, Void>()
{
@Override
public Void anyValue()
{
// do nothing
return null;
}
@Override
public Void valueIsNull()
{
queryBuilder.addEqualsFilter(columnName, null);
return null;
}
@Override
public Void valueIsNotNull()
{
queryBuilder.addNotNull(columnName);
return null;
}
@Override
|
public Void valueEqualsTo(@NonNull final T value)
{
queryBuilder.addEqualsFilter(columnName, value);
return null;
}
@Override
public Void valueEqualsToOrNull(@NonNull final T value)
{
//noinspection unchecked
queryBuilder.addInArrayFilter(columnName, null, value);
return null;
}
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\ValueRestriction.java
| 1
|
请完成以下Java代码
|
public void updateQtyToOrderFromQtyToOrderTU(final I_PMM_PurchaseCandidate candidate)
{
final I_M_HU_PI_Item_Product huPIItemProduct = getM_HU_PI_Item_Product_Effective(candidate);
if (huPIItemProduct != null)
{
final BigDecimal qtyToOrderTU = candidate.getQtyToOrder_TU();
final BigDecimal tuCapacity = huPIItemProduct.getQty();
final BigDecimal qtyToOrder = qtyToOrderTU.multiply(tuCapacity);
candidate.setQtyToOrder(qtyToOrder);
}
else
{
candidate.setQtyToOrder(candidate.getQtyToOrder_TU());
}
}
@Override
public void resetQtyToOrder(I_PMM_PurchaseCandidate candidate)
{
candidate.setQtyToOrder(BigDecimal.ZERO);
candidate.setQtyToOrder_TU(BigDecimal.ZERO);
}
@Override
public IPMMPricingAware asPMMPricingAware(final I_PMM_PurchaseCandidate candidate)
{
return PMMPricingAware_PurchaseCandidate.of(candidate);
}
@Override
public I_M_HU_PI_Item_Product getM_HU_PI_Item_Product_Effective(final I_PMM_PurchaseCandidate candidate)
{
final I_M_HU_PI_Item_Product hupipOverride = candidate.getM_HU_PI_Item_Product_Override();
|
if (hupipOverride != null)
{
// return M_HU_PI_Item_Product_Override if set
return hupipOverride;
}
// return M_HU_PI_Item_Product
return candidate.getM_HU_PI_Item_Product();
}
@Override
public int getM_HU_PI_Item_Product_Effective_ID(final I_PMM_PurchaseCandidate candidate)
{
final int hupipOverrideID = candidate.getM_HU_PI_Item_Product_Override_ID();
if (hupipOverrideID > 0)
{
// return M_HU_PI_Item_Product_Override if set
return hupipOverrideID;
}
// return M_HU_PI_Item_Product
return candidate.getM_HU_PI_Item_Product_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPurchaseCandidateBL.java
| 1
|
请完成以下Java代码
|
public <T> T getDynAttribute(@NonNull final Object model, @NonNull final String attributeName)
{
return getHelperThatCanHandle(model)
.getDynAttribute(model, attributeName);
}
@Override
public Object setDynAttribute(final Object model, final String attributeName, final Object value)
{
return getHelperThatCanHandle(model)
.setDynAttribute(model, attributeName, value);
}
@Nullable
@Override
public <T> T computeDynAttributeIfAbsent(@NonNull final Object model, @NonNull final String attributeName, @NonNull final Supplier<T> supplier)
{
return getHelperThatCanHandle(model).computeDynAttributeIfAbsent(model, attributeName, supplier);
}
@Override
public <T extends PO> T getPO(final Object model, final boolean strict)
{
if (model == null)
{
return null;
}
// Short-circuit: model is already a PO instance
if (model instanceof PO)
{
@SuppressWarnings("unchecked") final T po = (T)model;
return po;
}
return getHelperThatCanHandle(model)
.getPO(model, strict);
}
@Override
public Evaluatee getEvaluatee(final Object model)
|
{
if (model == null)
{
return null;
}
else if (model instanceof Evaluatee)
{
final Evaluatee evaluatee = (Evaluatee)model;
return evaluatee;
}
return getHelperThatCanHandle(model)
.getEvaluatee(model);
}
@Override
public boolean isCopy(@NonNull final Object model)
{
return getHelperThatCanHandle(model).isCopy(model);
}
@Override
public boolean isCopying(@NonNull final Object model)
{
return getHelperThatCanHandle(model).isCopying(model);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\CompositeInterfaceWrapperHelper.java
| 1
|
请完成以下Java代码
|
public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_CostElement getM_CostElement() throws RuntimeException
{
return (I_M_CostElement)MTable.get(getCtx(), I_M_CostElement.Table_Name)
.getPO(getM_CostElement_ID(), get_TrxName()); }
/** Set Cost Element.
@param M_CostElement_ID
Product Cost Element
*/
public void setM_CostElement_ID (int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID));
}
/** Get Cost Element.
@return Product Cost Element
*/
public int getM_CostElement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
|
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_LandedCostAllocation.java
| 1
|
请完成以下Java代码
|
public final class DocumentToInvalidate
{
private final TableRecordReference recordRef;
@Getter
private boolean invalidateDocument;
private final HashMap<String, IncludedDocumentToInvalidate> includedDocumentsByTableName = new HashMap<>();
public DocumentToInvalidate(@NonNull final TableRecordReference rootRecordRef)
{
recordRef = rootRecordRef;
}
public void invalidateDocument()
{
invalidateDocument = true;
}
public void invalidateAllIncludedDocuments(@NonNull final String includedTableName)
{
getIncludedDocument(includedTableName).invalidateAll();
}
public void addIncludedDocument(@NonNull final String includedTableName, final int includedRecordId)
{
getIncludedDocument(includedTableName).addRecordId(includedRecordId);
}
private IncludedDocumentToInvalidate getIncludedDocument(@NonNull final String includedTableName)
{
return includedDocumentsByTableName.computeIfAbsent(includedTableName, IncludedDocumentToInvalidate::new);
}
public String getTableName()
{
return recordRef.getTableName();
|
}
public DocumentId getDocumentId()
{
return DocumentId.of(recordRef.getRecord_ID());
}
public Collection<IncludedDocumentToInvalidate> getIncludedDocuments()
{
return includedDocumentsByTableName.values();
}
DocumentToInvalidate combine(@NonNull final DocumentToInvalidate other)
{
Check.assumeEquals(this.recordRef, other.recordRef, "recordRef");
this.invalidateDocument = this.invalidateDocument || other.invalidateDocument;
for (final Map.Entry<String, IncludedDocumentToInvalidate> e : other.includedDocumentsByTableName.entrySet())
{
this.includedDocumentsByTableName.merge(
e.getKey(),
e.getValue(),
(item1, item2) -> item1.combine(item2));
}
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\invalidation\DocumentToInvalidate.java
| 1
|
请完成以下Java代码
|
public boolean isSOTrx(@NonNull final String docBaseType)
{
return X_C_DocType.DOCBASETYPE_SalesOrder.equals(docBaseType)
|| X_C_DocType.DOCBASETYPE_MaterialDelivery.equals(docBaseType)
|| docBaseType.startsWith("AR"); // Account Receivables (Invoice, Payment Receipt)
}
@Override
public boolean isPrepay(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType docType = docTypesRepo.getById(docTypeId);
return isPrepay(docType);
}
@Override
public boolean isPrepay(final I_C_DocType dt)
{
return X_C_DocType.DOCSUBTYPE_PrepayOrder.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType());
}
@Override
public boolean hasRequestType(@NonNull final DocTypeId docTypeId)
{
return docTypesRepo.getById(docTypeId).getR_RequestType_ID() > 0;
}
@Override
public boolean isRequisition(final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return X_C_DocType.DOCSUBTYPE_Requisition.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType());
}
@Override
public boolean isMediated(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return X_C_DocType.DOCSUBTYPE_Mediated.equals(dt.getDocSubType())
&& X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType());
}
@Override
|
public boolean isCallOrder(@NonNull final DocTypeId docTypeId)
{
final I_C_DocType dt = docTypesRepo.getById(docTypeId);
return (X_C_DocType.DOCBASETYPE_SalesOrder.equals(dt.getDocBaseType()) || X_C_DocType.DOCBASETYPE_PurchaseOrder.equals(dt.getDocBaseType()))
&& X_C_DocType.DOCSUBTYPE_CallOrder.equals(dt.getDocSubType());
}
@Override
public void save(@NonNull final I_C_DocType dt)
{
docTypesRepo.save(dt);
}
@NonNull
public ImmutableList<I_C_DocType> retrieveForSelection(@NonNull final PInstanceId pinstanceId)
{
return docTypesRepo.retrieveForSelection(pinstanceId);
}
public DocTypeId cloneToOrg(@NonNull final I_C_DocType fromDocType, @NonNull final OrgId toOrgId)
{
final String newName = fromDocType.getName() + "_cloned";
final I_C_DocType newDocType = InterfaceWrapperHelper.copy()
.setFrom(fromDocType)
.setSkipCalculatedColumns(true)
.copyToNew(I_C_DocType.class);
newDocType.setAD_Org_ID(toOrgId.getRepoId());
// dev-note: unique index (ad_client_id, name)
newDocType.setName(newName);
final DocSequenceId fromDocSequenceId = DocSequenceId.ofRepoIdOrNull(fromDocType.getDocNoSequence_ID());
if (fromDocType.isDocNoControlled() && fromDocSequenceId != null)
{
final DocSequenceId clonedDocSequenceId = sequenceDAO.cloneToOrg(fromDocSequenceId, toOrgId);
newDocType.setDocNoSequence_ID(clonedDocSequenceId.getRepoId());
newDocType.setIsDocNoControlled(true);
}
save(newDocType);
return DocTypeId.ofRepoId(newDocType.getC_DocType_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\impl\DocTypeBL.java
| 1
|
请完成以下Java代码
|
public void setDate(final Timestamp date)
{
dateFField.setValue(date);
dateTField.setValue(date);
refresh();
}
/**************************************************************************
* Refresh - Create Query and refresh grid
*/
private void refresh()
{
final Object organization = orgField.getValue();
final Object locator = locatorField.getValue();
final Object product = productField.getValue();
final Object movementType = mtypeField.getValue();
final Timestamp movementDateFrom = dateFField.getValue();
final Timestamp movementDateTo = dateTField.getValue();
final Object bpartnerId = bpartnerField.getValue();
Services.get(IClientUI.class).executeLongOperation(panel, () -> refresh(organization, locator, product, movementType, movementDateFrom, movementDateTo, bpartnerId, statusBar));
} // refresh
/**
* Zoom
|
*/
@Override
public void zoom()
{
super.zoom();
// Zoom
panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
AWindow frame = new AWindow();
if (!frame.initWindow(adWindowId, query))
{
panel.setCursor(Cursor.getDefaultCursor());
return;
}
AEnv.addToWindowManager(frame);
AEnv.showCenterScreen(frame);
frame = null;
panel.setCursor(Cursor.getDefaultCursor());
} // zoom
} // VTrxMaterial
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\VTrxMaterial.java
| 1
|
请完成以下Java代码
|
public Quantity getMovementQtyInStockingUOM(final I_M_InventoryLine inventoryLine)
{
ProductId productId = ProductId.ofRepoId(inventoryLine.getM_Product_ID());
final Quantity movementQty = getMovementQty(inventoryLine);
return Services.get(IUOMConversionBL.class).convertToProductUOM(movementQty, productId);
}
@Override
public boolean isInternalUseInventory(final I_M_InventoryLine inventoryLine)
{
/*
* TODO: need to add M_Inventory.IsInternalUseInventory flag
* see FR [ 1879029 ] Added IsInternalUseInventory flag to M_Inventory table
* MInventory parent = getParent();
* return parent != null && parent.isInternalUseInventory();
*/
return inventoryLine.getQtyInternalUse().signum() != 0;
}
@Override
public boolean isSOTrx(final I_M_InventoryLine inventoryLine)
{
return getMovementQty(inventoryLine).signum() < 0;
}
@Override
public void assignToInventoryCounters(final List<I_M_InventoryLine> inventoryLines, final int numberOfCounters)
{
final Map<Integer, List<I_M_InventoryLine>> linesToLocators = new HashMap<>();
GuavaCollectors.groupByAndStream(inventoryLines.stream(), I_M_InventoryLine::getM_Locator_ID)
.forEach(
inventoryLinesPerLocator -> linesToLocators.put(inventoryLinesPerLocator.get(0).getM_Locator_ID(),
inventoryLinesPerLocator));
final List<Integer> locatorIds = linesToLocators
.keySet()
.stream()
.sorted()
.collect(ImmutableList.toImmutableList());
int i = 0;
for (int locatorId : locatorIds)
{
if (i == numberOfCounters)
{
i = 0;
}
|
final char counterIdentifier = (char)('A' + i);
assignInventoryLinesToCounterIdentifiers(linesToLocators.get(locatorId), counterIdentifier);
i++;
}
}
private void assignInventoryLinesToCounterIdentifiers(final List<I_M_InventoryLine> list, final char counterIdentifier)
{
list.forEach(inventoryLine -> {
inventoryLine.setAssignedTo(Character.toString(counterIdentifier));
save(inventoryLine);
});
}
@Override
public void setDefaultInternalChargeId(final I_M_InventoryLine inventoryLine)
{
final int defaultChargeId = getDefaultInternalChargeId();
inventoryLine.setC_Charge_ID(defaultChargeId);
}
@Override
public void markInventoryLinesAsCounted(@NonNull final InventoryId inventoryId)
{
inventoryDAO.retrieveLinesForInventoryId(inventoryId)
.forEach(this::markInventoryLineAsCounted);
}
private void markInventoryLineAsCounted(final I_M_InventoryLine inventoryLine)
{
inventoryLine.setIsCounted(true);
save(inventoryLine);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\impl\InventoryBL.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setSupplierGTINCU(String value) {
this.supplierGTINCU = value;
}
/**
* Gets the value of the invoicableQtyBasedOn property.
*
* @return
* possible object is
* {@link InvoicableQtyBasedOnEnum }
*
*/
public InvoicableQtyBasedOnEnum getInvoicableQtyBasedOn() {
return invoicableQtyBasedOn;
}
/**
* Sets the value of the invoicableQtyBasedOn property.
*
* @param value
* allowed object is
* {@link InvoicableQtyBasedOnEnum }
*
*/
public void setInvoicableQtyBasedOn(InvoicableQtyBasedOnEnum value) {
this.invoicableQtyBasedOn = value;
}
/**
* Gets the value of the cuombPartnerID property.
*
* @return
* possible object is
* {@link EDIExpCUOMType }
*
*/
public EDIExpCUOMType getCUOMBPartnerID() {
return cuombPartnerID;
}
/**
* Sets the value of the cuombPartnerID property.
*
* @param value
* allowed object is
* {@link EDIExpCUOMType }
*
*/
public void setCUOMBPartnerID(EDIExpCUOMType value) {
this.cuombPartnerID = value;
}
/**
* Gets the value of the qtyEnteredInBPartnerUOM property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getQtyEnteredInBPartnerUOM() {
return qtyEnteredInBPartnerUOM;
}
/**
|
* Sets the value of the qtyEnteredInBPartnerUOM property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setQtyEnteredInBPartnerUOM(BigDecimal value) {
this.qtyEnteredInBPartnerUOM = value;
}
/**
* Gets the value of the externalSeqNo property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getExternalSeqNo() {
return externalSeqNo;
}
/**
* Sets the value of the externalSeqNo property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setExternalSeqNo(BigInteger value) {
this.externalSeqNo = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctopInvoic500VType.java
| 2
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstance variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getSubScopeId() != null) {
variables.put(variableInstance.getVariableName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
|
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricPlanItemInstance with id: ")
.append(id);
if (getName() != null) {
sb.append(", name: ").append(getName());
}
sb.append(", definitionId: ")
.append(planItemDefinitionId)
.append(", state: ")
.append(state);
sb
.append(", caseInstanceId: ")
.append(caseInstanceId)
.append(", caseDefinitionId: ")
.append(caseDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
return sb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\HistoricPlanItemInstanceEntityImpl.java
| 1
|
请完成以下Java代码
|
default B credentials(@Nullable Object credentials) {
throw new UnsupportedOperationException(
String.format("%s does not store credentials", this.getClass().getSimpleName()));
}
/**
* Use this details object.
* <p>
* Implementations may choose to use these {@code details} in combination with any
* principal from the pre-existing {@link Authentication} instance.
* </p>
* @param details the details to use
* @return the {@link Builder} for additional configuration
* @see Authentication#getDetails
*/
B details(@Nullable Object details);
/**
* Use this principal.
* <p>
* Note that in many cases, the principal is strongly-typed. Implementations may
* choose to do a type check and are not necessarily expected to allow any object
* as a principal.
* </p>
* <p>
* Implementations may choose to use this {@code principal} in combination with
* any principal from the pre-existing {@link Authentication} instance.
* </p>
* @param principal the principal to use
* @return the {@link Builder} for additional configuration
|
* @see Authentication#getPrincipal
*/
B principal(@Nullable Object principal);
/**
* Mark this authentication as authenticated or not
* @param authenticated whether this is an authenticated {@link Authentication}
* instance
* @return the {@link Builder} for additional configuration
* @see Authentication#isAuthenticated
*/
B authenticated(boolean authenticated);
/**
* Build an {@link Authentication} instance
* @return the {@link Authentication} instance
*/
Authentication build();
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\Authentication.java
| 1
|
请完成以下Java代码
|
private Set<String> getValidDocActionsForCurrentDocStatus()
{
if (isInvalid())
{
return ImmutableSet.of(ACTION_Prepare, ACTION_Invalidate, ACTION_Unlock, ACTION_Void);
}
if (isDrafted())
{
return ImmutableSet.of(ACTION_Prepare, ACTION_Invalidate, ACTION_Complete, ACTION_Unlock, ACTION_Void);
}
if (isInProgress() || isApproved())
{
return ImmutableSet.of(ACTION_Complete, ACTION_WaitComplete, ACTION_Approve, ACTION_Reject, ACTION_Unlock, ACTION_Void, ACTION_Prepare);
}
if (isNotApproved())
{
return ImmutableSet.of(ACTION_Reject, ACTION_Prepare, ACTION_Unlock, ACTION_Void);
}
if (isWaiting())
{
return ImmutableSet.of(ACTION_Complete, ACTION_WaitComplete, ACTION_ReActivate, ACTION_Void, ACTION_Close);
}
if (isCompleted())
{
return ImmutableSet.of(ACTION_Close, ACTION_ReActivate, ACTION_Reverse_Accrual, ACTION_Reverse_Correct, ACTION_Post, ACTION_Void);
}
if (isClosed())
|
{
return ImmutableSet.of(ACTION_Post, ACTION_UnClose);
}
if (isReversed() || isVoided())
{
return ImmutableSet.of(ACTION_Post);
}
return ImmutableSet.of();
}
/**
* @return true if given docAction is valid for current docStatus.
*/
private boolean isValidDocAction(final String docAction)
{
final Set<String> availableDocActions = getValidDocActionsForCurrentDocStatus();
return availableDocActions.contains(docAction);
}
private String getDocAction()
{
return _docAction;
}
private void setDocActionIntern(final String newDocAction)
{
_docAction = newDocAction;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\DocumentEngine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
duedateSet = true;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
prioritySet = true;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
parentTaskIdSet = true;
}
public void setCategory(String category) {
this.category = category;
categorySet = true;
}
public String getCategory() {
return category;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
tenantIdSet = true;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
formKeySet = true;
}
public boolean isOwnerSet() {
return ownerSet;
}
public boolean isAssigneeSet() {
return assigneeSet;
}
|
public boolean isDelegationStateSet() {
return delegationStateSet;
}
public boolean isNameSet() {
return nameSet;
}
public boolean isDescriptionSet() {
return descriptionSet;
}
public boolean isDuedateSet() {
return duedateSet;
}
public boolean isPrioritySet() {
return prioritySet;
}
public boolean isParentTaskIdSet() {
return parentTaskIdSet;
}
public boolean isCategorySet() {
return categorySet;
}
public boolean isTenantIdSet() {
return tenantIdSet;
}
public boolean isFormKeySet() {
return formKeySet;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java
| 2
|
请完成以下Java代码
|
public String getTaskCompleterVariableName() {
return taskCompleterVariableName;
}
public void setTaskCompleterVariableName(String taskCompleterVariableName) {
this.taskCompleterVariableName = taskCompleterVariableName;
}
public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
public List<FlowableListener> getTaskListeners() {
return taskListeners;
}
|
public void setTaskListeners(List<FlowableListener> taskListeners) {
this.taskListeners = taskListeners;
}
@Override
public HumanTask clone() {
HumanTask clone = new HumanTask();
clone.setValues(this);
return clone;
}
public void setValues(HumanTask otherElement) {
super.setValues(otherElement);
setAssignee(otherElement.getAssignee());
setOwner(otherElement.getOwner());
setFormKey(otherElement.getFormKey());
setSameDeployment(otherElement.isSameDeployment());
setValidateFormFields(otherElement.getValidateFormFields());
setDueDate(otherElement.getDueDate());
setPriority(otherElement.getPriority());
setCategory(otherElement.getCategory());
setTaskIdVariableName(otherElement.getTaskIdVariableName());
setTaskCompleterVariableName(otherElement.getTaskCompleterVariableName());
setCandidateGroups(new ArrayList<>(otherElement.getCandidateGroups()));
setCandidateUsers(new ArrayList<>(otherElement.getCandidateUsers()));
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\HumanTask.java
| 1
|
请完成以下Java代码
|
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getSubjectCount() {
return subjectCount;
}
public void setSubjectCount(Integer subjectCount) {
this.subjectCount = subjectCount;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
|
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", icon=").append(icon);
sb.append(", subjectCount=").append(subjectCount);
sb.append(", showStatus=").append(showStatus);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubjectCategory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class HikariDataSourceMeterBinder implements MeterBinder {
private static final Log logger = LogFactory.getLog(HikariDataSourceMeterBinder.class);
private final ObjectProvider<DataSource> dataSources;
HikariDataSourceMeterBinder(ObjectProvider<DataSource> dataSources) {
this.dataSources = dataSources;
}
@Override
public void bindTo(MeterRegistry registry) {
this.dataSources.stream(ObjectProvider.UNFILTERED, false).forEach((dataSource) -> {
HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, HikariConfigMXBean.class,
HikariDataSource.class);
if (hikariDataSource != null) {
bindMetricsRegistryToHikariDataSource(hikariDataSource, registry);
}
|
});
}
private void bindMetricsRegistryToHikariDataSource(HikariDataSource hikari, MeterRegistry registry) {
if (hikari.getMetricRegistry() == null && hikari.getMetricsTrackerFactory() == null) {
try {
hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(registry));
}
catch (Exception ex) {
logger.warn(LogMessage.format("Failed to bind Hikari metrics: %s", ex.getMessage()));
}
}
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\metrics\DataSourcePoolMetricsAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricDecisionInstancesDto dto) {
HistoryService historyService = processEngine.getHistoryService();
HistoricDecisionInstanceQuery historicDecisionInstanceQuery = null;
if (dto.getHistoricDecisionInstanceQuery() != null) {
historicDecisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine);
}
SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder =
historyService.setRemovalTimeToHistoricDecisionInstances();
if (dto.isCalculatedRemovalTime()) {
builder.calculatedRemovalTime();
}
Date removalTime = dto.getAbsoluteRemovalTime();
if (dto.getAbsoluteRemovalTime() != null) {
builder.absoluteRemovalTime(removalTime);
|
}
if (dto.isClearedRemovalTime()) {
builder.clearedRemovalTime();
}
builder.byIds(dto.getHistoricDecisionInstanceIds());
builder.byQuery(historicDecisionInstanceQuery);
if (dto.isHierarchical()) {
builder.hierarchical();
}
Batch batch = builder.executeAsync();
return BatchDto.fromBatch(batch);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricDecisionInstanceRestServiceImpl.java
| 1
|
请完成以下Java代码
|
public class SingletonIterator<E> implements Iterator<E>
{
private final E element;
private boolean consumed = false;
public SingletonIterator(E element)
{
this.element = element;
}
@Override
public boolean hasNext()
{
return !consumed;
}
@Override
public E next()
{
if (consumed)
|
{
throw new NoSuchElementException();
}
consumed = true;
return element;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\SingletonIterator.java
| 1
|
请完成以下Java代码
|
public List<MigrationInstruction> asMigrationInstructions() {
List<MigrationInstruction> instructions = new ArrayList<MigrationInstruction>();
for (ValidatingMigrationInstruction instruction : this.instructions) {
instructions.add(instruction.toMigrationInstruction());
}
return instructions;
}
public boolean contains(ValidatingMigrationInstruction instruction) {
return instructions.contains(instruction);
}
public boolean containsInstructionForSourceScope(ScopeImpl sourceScope) {
|
return instructionsBySourceScope.containsKey(sourceScope);
}
protected boolean isValidInstruction(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, List<MigrationInstructionValidator> migrationInstructionValidators) {
return !validateInstruction(instruction, instructions, migrationInstructionValidators).hasFailures();
}
protected MigrationInstructionValidationReportImpl validateInstruction(ValidatingMigrationInstruction instruction, ValidatingMigrationInstructions instructions, List<MigrationInstructionValidator> migrationInstructionValidators) {
MigrationInstructionValidationReportImpl validationReport = new MigrationInstructionValidationReportImpl(instruction.toMigrationInstruction());
for (MigrationInstructionValidator migrationInstructionValidator : migrationInstructionValidators) {
migrationInstructionValidator.validate(instruction, instructions, validationReport);
}
return validationReport;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\ValidatingMigrationInstructions.java
| 1
|
请完成以下Spring Boot application配置
|
security:
basic:
enabled: true
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/security?useUnicode=yes&ch
|
aracterEncoding=UTF-8&useSSL=false
username: root
password: 123456
|
repos\SpringAll-master\37.Spring-Security-RememberMe\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public static class Builder extends AbstractBuilder<Builder> {
protected @Nullable Predicate<ServerWebExchange> predicate;
@Override
protected Builder getThis() {
return this;
}
@Override
public AsyncPredicate<ServerWebExchange> getPredicate() {
return ServerWebExchangeUtils.toAsyncPredicate(this.predicate);
}
public Builder and(Predicate<ServerWebExchange> predicate) {
Objects.requireNonNull(this.predicate, "can not call and() on null predicate");
this.predicate = this.predicate.and(predicate);
|
return this;
}
public Builder or(Predicate<ServerWebExchange> predicate) {
Objects.requireNonNull(this.predicate, "can not call or() on null predicate");
this.predicate = this.predicate.or(predicate);
return this;
}
public Builder negate() {
Objects.requireNonNull(this.predicate, "can not call negate() on null predicate");
this.predicate = this.predicate.negate();
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\Route.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static GrpcRequestScope grpcRequestScope() {
return new GrpcRequestScope();
}
@ConditionalOnMissingBean
@Bean
public GrpcServerProperties defaultGrpcServerProperties() {
return new GrpcServerProperties();
}
/**
* Lazily creates a {@link SelfNameResolverFactory} bean, that can be used by the client to connect to the server
* itself.
*
* @param properties The properties to derive the address from.
* @return The newly created {@link SelfNameResolverFactory} bean.
*/
@ConditionalOnMissingBean
@Bean
@Lazy
public SelfNameResolverFactory selfNameResolverFactory(final GrpcServerProperties properties) {
return new SelfNameResolverFactory(properties);
}
@ConditionalOnMissingBean
@Bean
GlobalServerInterceptorRegistry globalServerInterceptorRegistry(
final ApplicationContext applicationContext) {
return new GlobalServerInterceptorRegistry(applicationContext);
}
@Bean
@Lazy
AnnotationGlobalServerInterceptorConfigurer annotationGlobalServerInterceptorConfigurer(
final ApplicationContext applicationContext) {
return new AnnotationGlobalServerInterceptorConfigurer(applicationContext);
}
|
@ConditionalOnMissingBean
@Bean
public GrpcServiceDiscoverer defaultGrpcServiceDiscoverer() {
return new AnnotationGrpcServiceDiscoverer();
}
@ConditionalOnBean(CompressorRegistry.class)
@Bean
public GrpcServerConfigurer compressionServerConfigurer(final CompressorRegistry registry) {
return builder -> builder.compressorRegistry(registry);
}
@ConditionalOnBean(DecompressorRegistry.class)
@Bean
public GrpcServerConfigurer decompressionServerConfigurer(final DecompressorRegistry registry) {
return builder -> builder.decompressorRegistry(registry);
}
@ConditionalOnMissingBean(GrpcServerConfigurer.class)
@Bean
public List<GrpcServerConfigurer> defaultServerConfigurers() {
return Collections.emptyList();
}
@ConditionalOnMissingBean
@ConditionalOnBean(GrpcServerFactory.class)
@Bean
public GrpcServerLifecycle grpcServerLifecycle(
final GrpcServerFactory factory,
final GrpcServerProperties properties,
final ApplicationEventPublisher eventPublisher) {
return new GrpcServerLifecycle(factory, properties.getShutdownGracePeriod(), eventPublisher);
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\autoconfigure\GrpcServerAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public boolean isReadOnly()
{
return IsReadOnly;
}
public boolean isUpdateable()
{
return IsUpdateable;
}
public boolean isAlwaysUpdateable()
{
return IsAlwaysUpdateable;
}
public boolean isKey()
{
return IsKey;
}
public boolean isEncryptedField()
|
{
return IsEncryptedField;
}
public boolean isEncryptedColumn()
{
return IsEncryptedColumn;
}
public boolean isSelectionColumn()
{
return defaultFilterDescriptor != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVO.java
| 1
|
请完成以下Java代码
|
public static Builder builder() {
return new Builder();
}
public static class Builder {
private TenantId tenantId;
private EntityId entityId;
private AttributeScope scope;
private List<String> keys;
private boolean notifyDevice;
private List<CalculatedFieldId> previousCalculatedFieldIds;
private UUID tbMsgId;
private TbMsgType tbMsgType;
private FutureCallback<Void> callback;
Builder() {}
public Builder tenantId(TenantId tenantId) {
this.tenantId = tenantId;
return this;
}
public Builder entityId(EntityId entityId) {
this.entityId = entityId;
return this;
}
public Builder scope(AttributeScope scope) {
this.scope = scope;
return this;
}
@Deprecated
public Builder scope(String scope) {
try {
this.scope = AttributeScope.valueOf(scope);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid attribute scope '" + scope + "'");
}
return this;
}
public Builder keys(List<String> keys) {
this.keys = keys;
return this;
}
public Builder notifyDevice(boolean notifyDevice) {
this.notifyDevice = notifyDevice;
return this;
}
public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = previousCalculatedFieldIds;
return this;
}
public Builder tbMsgId(UUID tbMsgId) {
this.tbMsgId = tbMsgId;
return this;
|
}
public Builder tbMsgType(TbMsgType tbMsgType) {
this.tbMsgType = tbMsgType;
return this;
}
public Builder callback(FutureCallback<Void> callback) {
this.callback = callback;
return this;
}
public Builder future(SettableFuture<Void> future) {
return callback(new FutureCallback<>() {
@Override
public void onSuccess(Void result) {
future.set(result);
}
@Override
public void onFailure(Throwable t) {
future.setException(t);
}
});
}
public AttributesDeleteRequest build() {
return new AttributesDeleteRequest(
tenantId, entityId, scope, keys, notifyDevice, previousCalculatedFieldIds, tbMsgId, tbMsgType, requireNonNullElse(callback, NoOpFutureCallback.instance())
);
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\AttributesDeleteRequest.java
| 1
|
请完成以下Java代码
|
protected boolean beforeSave(final boolean newRecord)
{
final String elementType = getElementType();
// Natural Account
if (ELEMENTTYPE_UserDefined.equals(elementType) && isNaturalAccount())
{
setIsNaturalAccount(false);
}
// Tree validation
int adTreeId = getAD_Tree_ID();
if (adTreeId <= 0)
{
throw new FillMandatoryException("AD_Tree_ID");
}
final I_AD_Tree tree = InterfaceWrapperHelper.load(adTreeId, I_AD_Tree.class);
final String treeType = tree.getTreeType();
if (ELEMENTTYPE_UserDefined.equals(elementType))
{
if (X_AD_Tree.TREETYPE_User1.equals(treeType) || X_AD_Tree.TREETYPE_User2.equals(treeType))
{
;
}
|
else
{
throw new AdempiereException("@TreeType@ <> @ElementType@ (U)");
}
}
else
{
if (!X_AD_Tree.TREETYPE_ElementValue.equals(treeType))
{
throw new AdempiereException("@TreeType@ <> @ElementType@ (A)");
}
}
return true;
}
} // MElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean logout(JWToken jwToken) {
try {
String jwTokenWithoutSignature = JWTUtils.removeSignature(jwToken.getToken());
Jwt jwt = Jwts.parserBuilder().build().parse(jwTokenWithoutSignature);
DefaultClaims body = (DefaultClaims) jwt.getBody();
String subject = body.get(Claims.SUBJECT, String.class);
UserId userId = UserId.from(subject);
UserData userData = users.get(userId);
if (userData != null) {
Optional<Key> userKey = keyStoreService.getUserKey(userId);
if (userKey.isPresent()) {
try {
Jwts.parserBuilder().setSigningKey(userKey.get()).build().parseClaimsJws(jwToken.getToken());
keyStoreService.removeUserKey(userId);
UserData userDataNoJwt = UserData.cloneAndRemoveJwToken(userData);
users.put(userId, userDataNoJwt);
LOG.info("user {} logout.", userId.getId());
return true;
|
} catch (Exception e) {
LOG.warn("JWT verification failed for {} not found !", userId.getId());
}
} else {
LOG.warn("key for user {} not found !", userId.getId());
}
} else {
LOG.warn("user data for {} not found !", userId.getId());
}
} catch (Exception e) {
LOG.error("token validation failed !", e);
}
return false;
}
}
|
repos\spring-examples-java-17\spring-security-jwt\src\main\java\itx\examples\springboot\security\springsecurity\jwt\services\UserAccessServiceImpl.java
| 2
|
请完成以下Java代码
|
default void setInitializers(List<? extends ServletContextInitializer> initializers) {
getSettings().setInitializers(initializers);
}
/**
* Add {@link ServletContextInitializer}s to those that should be applied in addition
* to {@link ServletWebServerFactory#getWebServer(ServletContextInitializer...)}
* parameters.
* @param initializers the initializers to add
* @see #setInitializers
*/
default void addInitializers(ServletContextInitializer... initializers) {
getSettings().addInitializers(initializers);
}
/**
* Sets the configuration that will be applied to the server's JSP servlet.
* @param jsp the JSP servlet configuration
*/
default void setJsp(Jsp jsp) {
getSettings().setJsp(jsp);
}
/**
* Sets the Locale to Charset mappings.
* @param localeCharsetMappings the Locale to Charset mappings
*/
default void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
getSettings().setLocaleCharsetMappings(localeCharsetMappings);
}
/**
* Sets the init parameters that are applied to the container's
* {@link ServletContext}.
* @param initParameters the init parameters
|
*/
default void setInitParameters(Map<String, String> initParameters) {
getSettings().setInitParameters(initParameters);
}
/**
* Sets {@link CookieSameSiteSupplier CookieSameSiteSuppliers} that should be used to
* obtain the {@link SameSite} attribute of any added cookie. This method will replace
* any previously set or added suppliers.
* @param cookieSameSiteSuppliers the suppliers to add
* @see #addCookieSameSiteSuppliers
*/
default void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) {
getSettings().setCookieSameSiteSuppliers(cookieSameSiteSuppliers);
}
/**
* Add {@link CookieSameSiteSupplier CookieSameSiteSuppliers} to those that should be
* used to obtain the {@link SameSite} attribute of any added cookie.
* @param cookieSameSiteSuppliers the suppliers to add
* @see #setCookieSameSiteSuppliers
*/
default void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) {
getSettings().addCookieSameSiteSuppliers(cookieSameSiteSuppliers);
}
@Override
default void addWebListeners(String... webListenerClassNames) {
getSettings().addWebListenerClassNames(webListenerClassNames);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ConfigurableServletWebServerFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Config implements HasRouteId {
private @Nullable String name;
private @Nullable URI fallbackUri;
private @Nullable String routeId;
private Set<String> statusCodes = new HashSet<>();
private boolean resumeWithoutError = false;
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
public @Nullable String getRouteId() {
return routeId;
}
public @Nullable URI getFallbackUri() {
return fallbackUri;
}
public Config setFallbackUri(URI fallbackUri) {
this.fallbackUri = fallbackUri;
return this;
}
public Config setFallbackUri(String fallbackUri) {
return setFallbackUri(URI.create(fallbackUri));
}
public @Nullable String getName() {
return name;
}
public Config setName(String name) {
this.name = name;
return this;
}
public @Nullable String getId() {
if (!StringUtils.hasText(name) && StringUtils.hasText(routeId)) {
return routeId;
}
return name;
}
|
public Set<String> getStatusCodes() {
return statusCodes;
}
public Config setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes;
return this;
}
public Config addStatusCode(String statusCode) {
this.statusCodes.add(statusCode);
return this;
}
public boolean isResumeWithoutError() {
return resumeWithoutError;
}
public void setResumeWithoutError(boolean resumeWithoutError) {
this.resumeWithoutError = resumeWithoutError;
}
}
public class CircuitBreakerStatusCodeException extends HttpStatusCodeException {
public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) {
super(statusCode);
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SpringCloudCircuitBreakerFilterFactory.java
| 2
|
请完成以下Java代码
|
public void setFileName (java.lang.String FileName)
{
set_Value (COLUMNNAME_FileName, FileName);
}
/** Get File Name.
@return Name of the local file or URL
*/
@Override
public java.lang.String getFileName ()
{
return (java.lang.String)get_Value(COLUMNNAME_FileName);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Type AD_Reference_ID=540751
* Reference name: AD_AttachmentEntry_Type
*/
public static final int TYPE_AD_Reference_ID=540751;
/** Data = D */
public static final String TYPE_Data = "D";
/** URL = U */
public static final String TYPE_URL = "U";
|
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
@Override
public void setURL (java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
@Override
public java.lang.String getURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_URL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry_ReferencedRecord_v.java
| 1
|
请完成以下Java代码
|
public void createPost(String author, String title, String contents) throws ExecutionException, InterruptedException {
faunaClient.query(
Create(Collection("posts"),
Obj(
"data", Obj(
"title", Value(title),
"contents", Value(contents),
"created", Now(),
"authorRef", Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author)))))
)
)
).get();
}
public void updatePost(String id, String title, String contents) throws ExecutionException, InterruptedException {
faunaClient.query(
Update(Ref(Collection("posts"), id),
Obj(
"data", Obj(
"title", Value(title),
"contents", Value(contents))
|
)
)
).get();
}
private Post parsePost(Value entry) {
var author = entry.at("author");
var post = entry.at("post");
return new Post(
post.at("ref").to(Value.RefV.class).get().getId(),
post.at("data", "title").to(String.class).get(),
post.at("data", "contents").to(String.class).get(),
new Author(
author.at("data", "username").to(String.class).get(),
author.at("data", "name").to(String.class).get()
),
post.at("data", "created").to(Instant.class).get(),
post.at("ts").to(Long.class).get()
);
}
}
|
repos\tutorials-master\persistence-modules\fauna\src\main\java\com\baeldung\faunablog\posts\PostsService.java
| 1
|
请完成以下Java代码
|
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
// nothing
return null;
}
@Override
public String modelChange(PO po, int type) throws Exception
{
final int idxProcessed = po.get_ColumnIndex("Processed");
if (type == TYPE_AFTER_NEW)
{
if (idxProcessed < 0)
{
// if Processed column is missing create/link to referenceNo right now
referenceNoBL.linkReferenceNo(po, instance);
}
else if (po.get_ValueAsBoolean(idxProcessed))
{
// create/link to referenceNo only if is processed
referenceNoBL.linkReferenceNo(po, instance);
}
}
else if (type == TYPE_AFTER_CHANGE)
{
// consider it only if we have the Processed column, it was changed right and ...
if (idxProcessed >= 0 && po.is_ValueChanged(idxProcessed))
{
if (po.get_ValueAsBoolean(idxProcessed))
{
// ... Processed is true => we need to create/link to referenceNo
referenceNoBL.linkReferenceNo(po, instance);
}
else
{
// ... Processed is false => we need to unlink to referenceNo
referenceNoBL.unlinkReferenceNo(po, instance);
}
}
}
else if (type == TYPE_BEFORE_DELETE)
{
referenceNoBL.unlinkReferenceNo(po, instance);
}
return null;
}
@Override
public String docValidate(PO po, int timing)
{
final int clientId = instance.getType().getAD_Client_ID();
if (clientId != 0 && clientId != po.getAD_Client_ID())
{
// this validator does not applies for current tenant
return null;
}
if (timing == TIMING_AFTER_COMPLETE)
{
referenceNoBL.linkReferenceNo(po, instance);
}
else if (timing == TIMING_AFTER_VOID
|| timing == TIMING_AFTER_REACTIVATE
|| timing == TIMING_AFTER_REVERSEACCRUAL
|| timing == TIMING_AFTER_REVERSECORRECT)
{
referenceNoBL.unlinkReferenceNo(po, instance);
}
return null;
|
}
/**
* Register table doc validators. Private because it is called automatically on {@link #initialize(ModelValidationEngine, MClient)}.
*/
private void register()
{
for (int tableId : instance.getAssignedTableIds())
{
final String tableName = adTableDAO.retrieveTableName(tableId);
if (documentBL.isDocumentTable(tableName))
{
engine.addDocValidate(tableName, this);
logger.debug("Registered docValidate " + this);
}
else
{
engine.addModelChange(tableName, this);
logger.debug("Registered modelChange " + this);
}
}
}
public void unregister()
{
for (int tableId : instance.getAssignedTableIds())
{
final String tableName = adTableDAO.retrieveTableName(tableId);
engine.removeModelChange(tableName, this);
engine.removeDocValidate(tableName, this);
}
logger.debug("Unregistered " + this);
}
public IReferenceNoGeneratorInstance getInstance()
{
return instance;
}
@Override
public String toString()
{
return "ReferenceNoGeneratorInstanceValidator [instance=" + instance + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\ReferenceNoGeneratorInstanceValidator.java
| 1
|
请完成以下Java代码
|
public final class TenantProfileEntity extends BaseSqlEntity<TenantProfile> {
@Column(name = ModelConstants.TENANT_PROFILE_NAME_PROPERTY)
private String name;
@Column(name = ModelConstants.TENANT_PROFILE_DESCRIPTION_PROPERTY)
private String description;
@Column(name = ModelConstants.TENANT_PROFILE_IS_DEFAULT_PROPERTY)
private boolean isDefault;
@Column(name = ModelConstants.TENANT_PROFILE_ISOLATED_TB_RULE_ENGINE)
private boolean isolatedTbRuleEngine;
@Convert(converter = JsonConverter.class)
@JdbcType(PostgreSQLJsonPGObjectJsonbType.class)
@Column(name = ModelConstants.TENANT_PROFILE_PROFILE_DATA_PROPERTY)
private JsonNode profileData;
public TenantProfileEntity() {
super();
}
public TenantProfileEntity(TenantProfile tenantProfile) {
if (tenantProfile.getId() != null) {
|
this.setUuid(tenantProfile.getId().getId());
}
this.setCreatedTime(tenantProfile.getCreatedTime());
this.name = tenantProfile.getName();
this.description = tenantProfile.getDescription();
this.isDefault = tenantProfile.isDefault();
this.isolatedTbRuleEngine = tenantProfile.isIsolatedTbRuleEngine();
this.profileData = JacksonUtil.convertValue(tenantProfile.getProfileData(), ObjectNode.class);
}
@Override
public TenantProfile toData() {
TenantProfile tenantProfile = new TenantProfile(new TenantProfileId(this.getUuid()));
tenantProfile.setCreatedTime(createdTime);
tenantProfile.setName(name);
tenantProfile.setDescription(description);
tenantProfile.setDefault(isDefault);
tenantProfile.setIsolatedTbRuleEngine(isolatedTbRuleEngine);
tenantProfile.setProfileData(JacksonUtil.convertValue(profileData, TenantProfileData.class));
return tenantProfile;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\TenantProfileEntity.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() throws Exception {
processApplicationNameFromAnnotation(applicationContext)
.apply(springApplicationName)
.ifPresent(this::setBeanName);
if (camundaBpmProperties.getGenerateUniqueProcessApplicationName()) {
setBeanName(CamundaBpmProperties.getUniqueName(CamundaBpmProperties.UNIQUE_APPLICATION_NAME_PREFIX));
}
String processEngineName = processEngine.getName();
setDefaultDeployToEngineName(processEngineName);
RuntimeContainerDelegate.INSTANCE.get().registerProcessEngine(processEngine);
properties.put(PROP_SERVLET_CONTEXT_PATH, contextPath);
super.afterPropertiesSet();
}
@Override
public void destroy() throws Exception {
super.destroy();
RuntimeContainerDelegate.INSTANCE.get().unregisterProcessEngine(processEngine);
}
@PostDeploy
|
public void onPostDeploy(ProcessEngine processEngine) {
eventPublisher.publishEvent(new PostDeployEvent(processEngine));
}
@PreUndeploy
public void onPreUndeploy(ProcessEngine processEngine) {
eventPublisher.publishEvent(new PreUndeployEvent(processEngine));
}
@ConditionalOnWebApplication
@Configuration
class WebApplicationConfiguration implements ServletContextAware {
@Override
public void setServletContext(ServletContext servletContext) {
if (!StringUtils.isEmpty(servletContext.getContextPath())) {
contextPath = servletContext.getContextPath();
}
}
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\SpringBootProcessApplication.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(values)
.toString();
}
@Override
public int hashCode()
{
return Objects.hash(values);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!getClass().equals(obj.getClass()))
{
return false;
}
final EffectiveValuesEvaluatee other = (EffectiveValuesEvaluatee)obj;
return values.equals(other.values);
}
|
@Override
public String get_ValueAsString(final String variableName)
{
return values.get(variableName);
}
@Override
public boolean has_Variable(final String variableName)
{
return values.containsKey(variableName);
}
@Override
public String get_ValueOldAsString(final String variableName)
{
// TODO Auto-generated method stub
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CachedStringExpression.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PermissionService
{
private final IUserRolePermissionsDAO userRolePermissionsRepo = Services.get(IUserRolePermissionsDAO.class);
private final UserRolePermissionsKey userRolePermissionsKey;
@Getter
private final OrgId defaultOrgId;
private final HashSet<PermissionRequest> permissionsGranted = new HashSet<>();
@Builder
private PermissionService(
@NonNull final UserRolePermissionsKey userRolePermissionsKey,
@NonNull final OrgId defaultOrgId)
{
this.userRolePermissionsKey = userRolePermissionsKey;
this.defaultOrgId = defaultOrgId;
}
public void assertCanCreateOrUpdate(final Object record)
{
final OrgId orgId = getOrgId(record).orElse(OrgId.ANY);
final int adTableId = getModelTableId(record);
final int recordId;
if (isNew(record))
{
recordId = -1;
}
else
{
recordId = getId(record);
}
assertPermission(PermissionRequest.builder()
.orgId(orgId)
.adTableId(adTableId)
.recordId(recordId)
.build());
}
public void assertCanCreateOrUpdateRecord(final OrgId orgId, final Class<?> modelClass)
{
assertPermission(PermissionRequest.builder()
.orgId(orgId)
.adTableId(getTableId(modelClass))
.build());
}
public boolean canRunProcess(@NonNull final AdProcessId processId)
{
final PermissionRequest permissionRequest = PermissionRequest.builder()
.orgId(OrgId.ANY)
.processId(processId.getRepoId())
.build();
if (permissionsGranted.contains(permissionRequest))
{
return true;
}
final IUserRolePermissions userPermissions = userRolePermissionsRepo.getUserRolePermissions(userRolePermissionsKey);
final boolean canAccessProcess = userPermissions.checkProcessAccessRW(processId.getRepoId());
|
if (canAccessProcess)
{
permissionsGranted.add(permissionRequest);
}
return canAccessProcess;
}
private void assertPermission(@NonNull final PermissionRequest request)
{
if (permissionsGranted.contains(request))
{
return;
}
final IUserRolePermissions userPermissions = userRolePermissionsRepo.getUserRolePermissions(userRolePermissionsKey);
final BooleanWithReason allowed;
if (request.getRecordId() >= 0)
{
allowed = userPermissions.checkCanUpdate(
userPermissions.getClientId(),
request.getOrgId(),
request.getAdTableId(),
request.getRecordId());
}
else
{
allowed = userPermissions.checkCanCreateNewRecord(
userPermissions.getClientId(),
request.getOrgId(),
AdTableId.ofRepoId(request.getAdTableId()));
}
if (allowed.isFalse())
{
throw new PermissionNotGrantedException(allowed.getReason());
}
else
{
permissionsGranted.add(request);
}
}
@lombok.Value
@lombok.Builder
private static class PermissionRequest
{
@lombok.NonNull
OrgId orgId;
@lombok.Builder.Default
int adTableId = -1;
@lombok.Builder.Default
int recordId = -1;
@lombok.Builder.Default
int processId = -1;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions2\PermissionService.java
| 2
|
请完成以下Java代码
|
public class Student {
private int id;
private String firstName;
private String lastName;
public Student(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
|
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
|
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\mvc\Student.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* remove single key
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* batch delete
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* batch delete with pattern
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* hash set
* @param key
* @param hashKey
* @param value
*/
public void hashSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
* hash get
* @param key
* @param hashKey
* @return
*/
public Object hashGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}
/**
* list push
* @param k
* @param v
*/
public void push(String k,Object v){
|
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k,v);
}
/**
* list range
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> range(String k, long l, long l1){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l,l1);
}
/**
* set add
* @param key
* @param value
*/
public void setAdd(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}
/**
* set get
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* ordered set add
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}
/**
* rangeByScore
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key,double scoure,double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
|
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\java\com\neo\service\RedisService.java
| 2
|
请完成以下Java代码
|
public void run()
{
try
{
logger.debug("execute - Going to invoke command.run() within delegate thread-pool");
command.run();
logger.debug("execute - Done invoking command.run() within delegate thread-pool");
}
catch (final Throwable t)
{
logger.error("execute - Caught throwable while running command=" + command + "; -> rethrow", t);
throw t;
}
finally
{
semaphore.release();
logger.debug("Released semaphore={}", semaphore);
}
}
|
};
try
{
delegate.execute(r); // don't expect RejectedExecutionException because delegate has a small queue that can hold runnables after semaphore-release and before they can actually start
}
catch (final RejectedExecutionException e)
{
semaphore.release();
logger.error("execute - Caught RejectedExecutionException while trying to submit task=" + r + " to delegate thread-pool=" + delegate + "; -> released semaphore=" + semaphore + " and rethrow", e);
throw e;
}
}
public boolean hasAvailablePermits()
{
return semaphore.availablePermits() > 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\concurrent\BlockingExecutorWrapper.java
| 1
|
请完成以下Java代码
|
void submit(String task) {
tasksQueue.add(task);
}
Runnable batchHandling(Consumer<List<String>> executionLogic) {
return () -> {
while (!batchThread.isInterrupted()) {
long startTime = System.currentTimeMillis();
while (tasksQueue.size() < executionThreshold && (System.currentTimeMillis() - startTime) < timeoutThreshold) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return; // exit the external loop
}
}
|
List<String> tasks = new ArrayList<>(executionThreshold);
while (tasksQueue.size() > 0 && tasks.size() < executionThreshold) {
tasks.add(tasksQueue.poll());
}
working = true;
executionLogic.accept(tasks);
working = false;
}
};
}
boolean finished() {
return tasksQueue.isEmpty() && !working;
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\smartbatching\MicroBatcher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WorkplaceService
{
@NonNull private final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class);
@NonNull private final WorkplaceRepository workplaceRepository;
@NonNull private final WorkplaceUserAssignRepository workplaceUserAssignRepository;
public Workplace create(@NonNull final WorkplaceCreateRequest request) {return workplaceRepository.create(request);}
@NonNull
public Workplace getById(@NonNull final WorkplaceId id)
{
return workplaceRepository.getById(id);
}
@NonNull
public Collection<Workplace> getByIds(final Collection<WorkplaceId> ids)
{
return workplaceRepository.getByIds(ids);
}
@NonNull
public Optional<Workplace> getWorkplaceByUserId(@NonNull final UserId userId)
{
return workplaceUserAssignRepository.getWorkplaceIdByUserId(userId)
.map(workplaceRepository::getById);
}
public List<Workplace> getAllActive() {return workplaceRepository.getAllActive();}
public Optional<WarehouseId> getWarehouseIdByUserId(@NonNull final UserId userId)
{
return getWorkplaceByUserId(userId).map(Workplace::getWarehouseId);
}
public void assignWorkplace(@NonNull UserId userId, @NonNull WorkplaceId workplaceId)
{
workplaceUserAssignRepository.create(WorkplaceAssignmentCreateRequest.builder().userId(userId).workplaceId(workplaceId).build());
}
public void assignWorkplace(@NonNull final WorkplaceAssignmentCreateRequest request)
|
{
workplaceUserAssignRepository.create(request);
}
public boolean isUserAssigned(@NonNull final UserId userId, @NonNull final WorkplaceId expectedWorkplaceId)
{
final WorkplaceId workplaceId = workplaceUserAssignRepository.getWorkplaceIdByUserId(userId).orElse(null);
return WorkplaceId.equals(workplaceId, expectedWorkplaceId);
}
public boolean isAnyWorkplaceActive()
{
return workplaceRepository.isAnyWorkplaceActive();
}
public Set<LocatorId> getPickFromLocatorIds(final Workplace workplace)
{
if (workplace.getPickFromLocatorId() != null)
{
return ImmutableSet.of(workplace.getPickFromLocatorId());
}
else
{
return warehouseBL.getLocatorIdsByWarehouseId(workplace.getWarehouseId());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\WorkplaceService.java
| 2
|
请完成以下Java代码
|
public void afterUnclose(final I_PP_Order ppOrder)
{
final IMaterialTrackingPPOrderDAO materialTrackingPPOrderDAO = Services.get(IMaterialTrackingPPOrderDAO.class);
final IMaterialTrackingPPOrderBL materialTrackingPPOrderBL = Services.get(IMaterialTrackingPPOrderBL.class);
materialTrackingPPOrderDAO.deleteInvoiceDetails(ppOrder);
final IIsInvoiceCandidateAware ppOrderIsInvoiceCandidateAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(ppOrder, IIsInvoiceCandidateAware.class);
ppOrderIsInvoiceCandidateAware.setIsInvoiceCandidate(false);
final List<I_M_InOutLine> issuedInOutLines = materialTrackingPPOrderBL.retrieveIssuedInOutLines(ppOrder);
for (final I_M_InOutLine iol : issuedInOutLines)
{
final IIsInvoiceCandidateAware iolIsInvoiceCandidateAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(iol, IIsInvoiceCandidateAware.class);
iolIsInvoiceCandidateAware.setIsInvoiceCandidate(false);
InterfaceWrapperHelper.save(iol);
}
|
new PPOrderReportWriter(ppOrder).deleteReportLines();
// task 09502 IT-2: make sure that existing invoice candidates are braught up to date
final IInvoiceCandidateHandlerBL invoiceCandidateHandlerBL = Services.get(IInvoiceCandidateHandlerBL.class);
invoiceCandidateHandlerBL.invalidateCandidatesFor(ppOrder);
}
/**
* If a PP_Order is deleted, then this method deletes the candidates which directly reference that line via <code>AD_Table_ID</code> and <code>Record_ID</code>.
*/
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteC_Invoice_Candidates(final I_PP_Order ppOrder)
{
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(ppOrder);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\PP_Order.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class QuartzConfig {
@Autowired
private Job quartzJobOne;
@Autowired
private Job quartzJobTwo;
@Bean
public JobDetail job1Detail() {
return JobBuilder.newJob()
.ofType(quartzJobOne.getClass())
.withIdentity("quartzJobOne", "group1")
.storeDurably()
.build();
}
@Bean
public JobDetail job2Detail() {
return JobBuilder.newJob()
.ofType(quartzJobTwo.getClass())
.withIdentity("quartzJobTwo", "group1")
.storeDurably()
.build();
}
@Bean
public Trigger job1Trigger(JobDetail job1Detail) {
return TriggerBuilder.newTrigger()
.forJob(job1Detail)
.withIdentity("quartzJobOneTrigger", "group1")
|
.withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
.build();
}
@Bean
public Trigger job2Trigger(JobDetail job2Detail) {
return TriggerBuilder.newTrigger()
.forJob(job2Detail)
.withIdentity("quartzJobTwoTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/15 * * * * ?"))
.build();
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setJobDetails(job1Detail(), job2Detail());
schedulerFactory.setTriggers(job1Trigger(job1Detail()), job2Trigger(job2Detail()));
return schedulerFactory;
}
}
|
repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\springbatch\jobs\quartz\QuartzConfig.java
| 2
|
请完成以下Java代码
|
public void notifySalesRepChanged(@NonNull final RequestSalesRepChanged event)
{
final Set<UserId> userIdsToNotify = extractUserIdsToNotify(event);
if (userIdsToNotify.isEmpty())
{
return;
}
final List<UserNotificationRequest> notifications = new ArrayList<>();
for (final UserId userIdToNotify : userIdsToNotify)
{
notifications.add(createNotification(event, userIdToNotify));
}
notificationsService.sendAfterCommit(notifications);
}
private UserNotificationRequest createNotification(final RequestSalesRepChanged event, final UserId recipientId)
{
final UserNotificationsConfig notificationsConfig = notificationsService.getUserNotificationsConfig(recipientId);
return UserNotificationRequest.builder()
.notificationsConfig(notificationsConfig)
.topic(TOPIC_Requests)
//
// RequestActionTransfer - Request {} was transfered by {} from {} to {}
.subjectADMessage(MSG_RequestActionTransfer)
.subjectADMessageParam(event.getRequestDocumentNo())
|
.subjectADMessageParam(getUserFullname(event.getChangedById()))
.subjectADMessageParam(getUserFullname(event.getFromSalesRepId()))
.subjectADMessageParam(getUserFullname(event.getToSalesRepId()))
//
.contentADMessage(MSG_RequestActionTransfer)
.contentADMessageParam(event.getRequestDocumentNo())
.contentADMessageParam(getUserFullname(event.getChangedById()))
.contentADMessageParam(getUserFullname(event.getFromSalesRepId()))
.contentADMessageParam(getUserFullname(event.getToSalesRepId()))
//
.targetAction(TargetRecordAction.of(I_R_Request.Table_Name, event.getRequestId().getRepoId()))
.build();
}
private static Set<UserId> extractUserIdsToNotify(@NonNull final RequestSalesRepChanged event)
{
return event.getToSalesRepId() != null
? ImmutableSet.of(event.getToSalesRepId())
: ImmutableSet.of();
}
private String getUserFullname(@Nullable final UserId userId)
{
return userId != null
? usersRepo.retrieveUserFullName(userId)
: "-";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\notifications\RequestNotificationsSender.java
| 1
|
请完成以下Java代码
|
public void setB_Topic_ID (int B_Topic_ID)
{
if (B_Topic_ID < 1)
set_Value (COLUMNNAME_B_Topic_ID, null);
else
set_Value (COLUMNNAME_B_Topic_ID, Integer.valueOf(B_Topic_ID));
}
/** Get Topic.
@return Auction Topic
*/
public int getB_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_B_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Willing to commit.
@param IsWillingToCommit Willing to commit */
public void setIsWillingToCommit (boolean IsWillingToCommit)
{
set_Value (COLUMNNAME_IsWillingToCommit, Boolean.valueOf(IsWillingToCommit));
}
/** Get Willing to commit.
@return Willing to commit */
public boolean isWillingToCommit ()
{
Object oo = get_Value(COLUMNNAME_IsWillingToCommit);
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 Private Note.
@param PrivateNote
|
Private Note - not visible to the other parties
*/
public void setPrivateNote (String PrivateNote)
{
set_Value (COLUMNNAME_PrivateNote, PrivateNote);
}
/** Get Private Note.
@return Private Note - not visible to the other parties
*/
public String getPrivateNote ()
{
return (String)get_Value(COLUMNNAME_PrivateNote);
}
/** 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_B_Bid.java
| 1
|
请完成以下Java代码
|
public class M_HU_MultipleSelection_Report_Print_Label extends JavaProcess implements IProcessPrecondition
{
private final HULabelService labelService = SpringContextHolder.instance.getBean(HULabelService.class);
private final HUQRCodesService huqrCodesService = SpringContextHolder.instance.getBean(HUQRCodesService.class);
private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
@Param(mandatory = true, parameterName = "AD_Process_ID")
private AdProcessId p_AD_Process_ID;
@Param(mandatory = true, parameterName = IMassPrintingService.PARAM_PrintCopies)
private int p_PrintCopies;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
@RunOutOfTrx
protected String doIt() throws Exception
{
final List<HUToReport> topLevelHus = new ArrayList<>();
final ImmutableList<HUToReport> hus = handlingUnitsDAO.streamByQuery(retrieveSelectedRecordsQueryBuilder(I_M_HU.class), HUToReportWrapper::of)
.filter(hu -> hu.getHUUnitType() != VHU)
.peek(topLevelHus::add)
.flatMap(hu -> {
if (hu.getHUUnitType() == LU)
{
return Stream.concat(Stream.of(hu), hu.getIncludedHUs().stream());
}
else
{
return Stream.of(hu);
}
})
.filter(hu -> hu.getHUUnitType() != VHU)
.collect(ImmutableList.toImmutableList());
|
final Set<HuId> huIdSet = hus.stream().map(HUToReport::getHUId).collect(ImmutableSet.toImmutableSet());
huqrCodesService.generateForExistingHUs(huIdSet);
topLevelHus.stream()
.sorted(Comparator.comparing(hu -> hu.getHUId().getRepoId()))
.forEach(topLevelHu -> {
labelService.printNow(HULabelDirectPrintRequest.builder()
.onlyOneHUPerPrint(true)
.printCopies(PrintCopies.ofIntOrOne(p_PrintCopies))
.printFormatProcessId(p_AD_Process_ID)
.hu(topLevelHu)
.build());
if (topLevelHu.getHUUnitType() == LU && !topLevelHu.getIncludedHUs().isEmpty())
{
final List<HUToReport> sortedIncludedHUs = topLevelHu.getIncludedHUs()
.stream()
.sorted(Comparator.comparing(hu -> hu.getHUId().getRepoId()))
.collect(ImmutableList.toImmutableList());
labelService.printNow(HULabelDirectPrintRequest.builder()
.onlyOneHUPerPrint(true)
.printCopies(PrintCopies.ofIntOrOne(p_PrintCopies))
.printFormatProcessId(p_AD_Process_ID)
.hus(sortedIncludedHUs)
.build());
}
});
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_MultipleSelection_Report_Print_Label.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<ApiResponse> deleteJob(JobForm form) throws SchedulerException {
if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
}
jobService.deleteJob(form);
return new ResponseEntity<>(ApiResponse.msg("删除成功"), HttpStatus.OK);
}
/**
* 暂停定时任务
*/
@PutMapping(params = "pause")
public ResponseEntity<ApiResponse> pauseJob(JobForm form) throws SchedulerException {
if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
}
jobService.pauseJob(form);
return new ResponseEntity<>(ApiResponse.msg("暂停成功"), HttpStatus.OK);
}
/**
* 恢复定时任务
*/
@PutMapping(params = "resume")
public ResponseEntity<ApiResponse> resumeJob(JobForm form) throws SchedulerException {
if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) {
return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST);
}
jobService.resumeJob(form);
return new ResponseEntity<>(ApiResponse.msg("恢复成功"), HttpStatus.OK);
}
/**
* 修改定时任务,定时时间
*/
|
@PutMapping(params = "cron")
public ResponseEntity<ApiResponse> cronJob(@Valid JobForm form) {
try {
jobService.cronJob(form);
} catch (Exception e) {
return new ResponseEntity<>(ApiResponse.msg(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(ApiResponse.msg("修改成功"), HttpStatus.OK);
}
@GetMapping
public ResponseEntity<ApiResponse> jobList(Integer currentPage, Integer pageSize) {
if (ObjectUtil.isNull(currentPage)) {
currentPage = 1;
}
if (ObjectUtil.isNull(pageSize)) {
pageSize = 10;
}
PageInfo<JobAndTrigger> all = jobService.list(currentPage, pageSize);
return ResponseEntity.ok(ApiResponse.ok(Dict.create().set("total", all.getTotal()).set("data", all.getList())));
}
}
|
repos\spring-boot-demo-master\demo-task-quartz\src\main\java\com\xkcoding\task\quartz\controller\JobController.java
| 2
|
请完成以下Java代码
|
public class HashSetBenchmark {
@State(Scope.Thread)
public static class MyState {
private Set<Employee> employeeSet1 = new HashSet<>();
private List<Employee> employeeList1 = new ArrayList<>();
private Set<Employee> employeeSet2 = new HashSet<>();
private List<Employee> employeeList2 = new ArrayList<>();
private Set<Employee> employeeSet3 = new HashSet<>();
private Set<Employee> employeeSet4 = new HashSet<>();
private long set1Size = 60000;
private long list1Size = 50000;
private long set2Size = 50000;
private long list2Size = 60000;
private long set3Size = 50000;
private long set4Size = 60000;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < set1Size; i++) {
employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list1Size; i++) {
employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set2Size; i++) {
employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list2Size; i++) {
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set3Size; i++) {
employeeSet3.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
|
for (long i = 0; i < set4Size; i++) {
employeeSet4.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
}
}
@Benchmark
public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet1.removeAll(state.employeeList1);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
return state.employeeSet2.removeAll(state.employeeList2);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfAnotherHashSet_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet3.removeAll(state.employeeSet4);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())
.threads(1)
.forks(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server")
.build();
new Runner(options).run();
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-3\src\main\java\com\baeldung\collections\removeallperformance\HashSetBenchmark.java
| 1
|
请完成以下Java代码
|
public void afterPropertiesSet() throws ServletException {
super.afterPropertiesSet();
updateFactory();
}
private void updateFactory() {
String rolePrefix = this.rolePrefix;
this.requestFactory = createServlet3Factory(rolePrefix);
}
/**
* Sets the {@link AuthenticationTrustResolver} to be used. The default is
* {@link AuthenticationTrustResolverImpl}.
* @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
* null.
*/
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
|
Assert.notNull(trustResolver, "trustResolver cannot be null");
this.trustResolver = trustResolver;
updateFactory();
}
private HttpServletRequestFactory createServlet3Factory(String rolePrefix) {
HttpServlet3RequestFactory factory = new HttpServlet3RequestFactory(rolePrefix, this.securityContextRepository);
factory.setTrustResolver(this.trustResolver);
factory.setAuthenticationEntryPoint(this.authenticationEntryPoint);
factory.setAuthenticationManager(this.authenticationManager);
factory.setLogoutHandlers(this.logoutHandlers);
factory.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
return factory;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\servletapi\SecurityContextHolderAwareRequestFilter.java
| 1
|
请完成以下Java代码
|
public void setA_Salvage_Value (BigDecimal A_Salvage_Value)
{
set_Value (COLUMNNAME_A_Salvage_Value, A_Salvage_Value);
}
/** Get Salvage Value.
@return Salvage Value */
public BigDecimal getA_Salvage_Value ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Salvage_Value);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Split Percentage.
@param A_Split_Percent Split Percentage */
public void setA_Split_Percent (BigDecimal A_Split_Percent)
{
set_Value (COLUMNNAME_A_Split_Percent, A_Split_Percent);
}
/** Get Split Percentage.
@return Split Percentage */
public BigDecimal getA_Split_Percent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Split_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_AcctSchema getC_AcctSchema() throws RuntimeException
{
return (I_C_AcctSchema)MTable.get(getCtx(), I_C_AcctSchema.Table_Name)
.getPO(getC_AcctSchema_ID(), get_TrxName()); }
/** Set Accounting Schema.
@param C_AcctSchema_ID
Rules for accounting
*/
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_Value (COLUMNNAME_C_AcctSchema_ID, null);
else
set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Accounting Schema.
@return Rules for accounting
*/
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
|
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
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_A_Asset_Acct.java
| 1
|
请完成以下Java代码
|
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix());
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object
* @return always <code>true</code>
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if (authentication == null) {
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
|
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities();
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\RoleVoter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserService {
private static final Logger LOG = LoggerFactory.getLogger(UserService.class);
private final Map<String, User> usersCache;
private final ObjectMapper objectMapper;
public UserService(ObjectMapper objectMapper) {
this.usersCache = new HashMap<>();
this.objectMapper = objectMapper;
}
public Map<String, User> getUsers() {
return usersCache;
}
public Mono<User> findByUserIdWithDefer(String id) {
return fetchFromCache(id).switchIfEmpty(Mono.defer(() -> fetchFromFile(id)));
}
public Mono<User> findByUserIdWithoutDefer(String id) {
return fetchFromCache(id).switchIfEmpty(fetchFromFile(id));
}
private Mono<User> fetchFromCache(String id) {
User user = usersCache.get(id);
if (user != null) {
LOG.info("Fetched user {} from cache", id);
return Mono.just(user);
}
return Mono.empty();
}
private Mono<User> fetchFromFile(String id) {
|
try {
File file = new ClassPathResource("users.json").getFile();
String usersData = new String(Files.readAllBytes(file.toPath()));
List<User> users = objectMapper.readValue(usersData, new TypeReference<List<User>>() {
});
User user = users.stream()
.filter(u -> u.getId()
.equalsIgnoreCase(id))
.findFirst()
.get();
usersCache.put(user.getId(), user);
LOG.info("Fetched user {} from file", id);
return Mono.just(user);
} catch (IOException e) {
return Mono.error(e);
}
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-4\src\main\java\com\baeldung\switchIfEmpty\service\UserService.java
| 2
|
请完成以下Java代码
|
protected AgeRange computeAgeRangeForProducts(
@NonNull final Set<ProductId> productIds,
@NonNull final Set<BPartnerId> bPartnerIds)
{
if (Check.isEmpty(productIds))
{
return AgeRange.builder()
.pickingAgeTolerance_BeforeMonths(0)
.pickingAgeTolerance_AfterMonths(0)
.build();
}
int pickingAgeTolerance_BeforeMonths = Integer.MAX_VALUE;
int pickingAgeTolerance_AfterMonths = Integer.MAX_VALUE;
for (final ProductId productId : productIds)
{
final I_M_Product product = productDAO.getById(productId);
final OrgId orgId = OrgId.ofRepoId(product.getAD_Org_ID());
final AgeRange ageRange = computeAgeRangeForProduct(product, bPartnerIds, orgId);
if (ageRange.getPickingAgeTolerance_BeforeMonths() < pickingAgeTolerance_BeforeMonths)
{
pickingAgeTolerance_BeforeMonths = ageRange.getPickingAgeTolerance_BeforeMonths();
}
if (ageRange.getPickingAgeTolerance_AfterMonths() < pickingAgeTolerance_AfterMonths)
{
pickingAgeTolerance_AfterMonths = ageRange.getPickingAgeTolerance_AfterMonths();
}
}
return AgeRange.builder()
.pickingAgeTolerance_BeforeMonths(pickingAgeTolerance_BeforeMonths)
.pickingAgeTolerance_AfterMonths(pickingAgeTolerance_AfterMonths)
.build();
}
private AgeRange computeAgeRangeForProduct(
@NonNull final I_M_Product product,
@NonNull final Set<BPartnerId> bPartnerIds,
@NonNull final OrgId orgId)
{
int pickingAgeTolerance_BP_Product_BeforeMonths = Integer.MAX_VALUE;
int pickingAgeTolerance_BP_Product_AfterMonths = Integer.MAX_VALUE;
|
boolean bPartnerProductWasFound = false;
for (final BPartnerId bpartnerId : bPartnerIds)
{
if (bpartnerId == null)
{
continue;
}
final I_C_BPartner partner = partnerDAO.getById(bpartnerId);
final I_C_BPartner_Product bPartnerProduct = bpartnerProductDAO.retrieveBPProductForCustomer(partner, product, orgId);
if (bPartnerProduct != null)
{
bPartnerProductWasFound = true;
if (bPartnerProduct.getPicking_AgeTolerance_BeforeMonths() < pickingAgeTolerance_BP_Product_BeforeMonths)
{
pickingAgeTolerance_BP_Product_BeforeMonths = bPartnerProduct.getPicking_AgeTolerance_BeforeMonths();
}
if (bPartnerProduct.getPicking_AgeTolerance_AfterMonths() < pickingAgeTolerance_BP_Product_AfterMonths)
{
pickingAgeTolerance_BP_Product_AfterMonths = bPartnerProduct.getPicking_AgeTolerance_AfterMonths();
}
}
}
if (bPartnerProductWasFound)
{
return AgeRange.builder()
.pickingAgeTolerance_BeforeMonths(pickingAgeTolerance_BP_Product_BeforeMonths)
.pickingAgeTolerance_AfterMonths(pickingAgeTolerance_BP_Product_AfterMonths)
.build();
}
return AgeRange.builder()
.pickingAgeTolerance_BeforeMonths(product.getPicking_AgeTolerance_BeforeMonths())
.pickingAgeTolerance_AfterMonths(product.getPicking_AgeTolerance_AfterMonths())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\age\AgeAttributesService.java
| 1
|
请完成以下Java代码
|
private Collection<TableRecordReference> extractRecordRefs(final DataItem dataItem)
{
return adapter.extractRecordRefs(dataItem);
}
/** Convenient method to be used as {@link CacheAdditionListener} */
public void add(final CacheKey ignored, @NonNull final DataItem dataItem)
{
add(dataItem);
}
public void add(@NonNull final DataItem dataItem)
{
final DataItemId dataItemId = extractDataItemId(dataItem);
final Collection<CacheKey> cacheKeys = extractCacheKeys(dataItem);
final Collection<TableRecordReference> recordRefs = extractRecordRefs(dataItem);
add(dataItemId, cacheKeys, recordRefs);
}
private synchronized void add(
@NonNull final DataItemId dataItemId,
@NonNull final Collection<CacheKey> cacheKeys,
@NonNull final Collection<TableRecordReference> recordRefs)
{
logger.debug("Adding to index: {} -> {}", dataItemId, cacheKeys);
_dataItemId_to_cacheKey.putAll(dataItemId, cacheKeys);
logger.debug("Adding to index: {} -> {}", recordRefs, dataItemId);
recordRefs.forEach(recordRef -> _recordRef_to_dateItemId.put(recordRef, dataItemId));
}
public void remove(final CacheKey cacheKey, final DataItem dataItem)
{
final DataItemId dataItemId = extractDataItemId(dataItem);
final Collection<TableRecordReference> recordRefs = extractRecordRefs(dataItem);
|
removeDataItemId(dataItemId, cacheKey, recordRefs);
}
private synchronized void removeDataItemId(
final DataItemId dataItemId,
final CacheKey cacheKey,
final Collection<TableRecordReference> recordRefs)
{
logger.debug("Removing pair from index: {}, {}", dataItemId, cacheKey);
_dataItemId_to_cacheKey.remove(dataItemId, cacheKey);
logger.debug("Removing pairs from index: {}, {}", recordRefs, dataItemId);
recordRefs.forEach(recordRef -> _recordRef_to_dateItemId.remove(recordRef, dataItemId));
}
@Override
public boolean isResetAll(final TableRecordReference recordRef)
{
return adapter.isResetAll(recordRef);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheIndex.java
| 1
|
请完成以下Java代码
|
public class CaseDefinitionBuilder {
protected CmmnCaseDefinition caseDefinition;
protected CmmnActivity casePlanModel;
protected Deque<CmmnActivity> activityStack = new ArrayDeque<>();
protected CoreModelElement processElement = caseDefinition;
public CaseDefinitionBuilder() {
this(null);
}
public CaseDefinitionBuilder(String caseDefinitionId) {
// instantiate case definition
caseDefinition = new CmmnCaseDefinition(caseDefinitionId);
activityStack.push(caseDefinition);
// instantiate casePlanModel of case definition (ie. outermost stage)
createActivity(caseDefinitionId);
behavior(new StageActivityBehavior());
}
public CaseDefinitionBuilder createActivity(String id) {
CmmnActivity activity = activityStack.peek().createActivity(id);
activityStack.push(activity);
processElement = activity;
return this;
}
public CaseDefinitionBuilder endActivity() {
activityStack.pop();
processElement = activityStack.peek();
return this;
}
|
public CaseDefinitionBuilder behavior(CmmnActivityBehavior behavior) {
getActivity().setActivityBehavior(behavior);
return this;
}
public CaseDefinitionBuilder autoComplete(boolean autoComplete) {
getActivity().setProperty("autoComplete", autoComplete);
return this;
}
protected CmmnActivity getActivity() {
return activityStack.peek();
}
public CmmnCaseDefinition buildCaseDefinition() {
return caseDefinition;
}
public CaseDefinitionBuilder listener(String eventName, CaseExecutionListener planItemListener) {
activityStack.peek().addListener(eventName, planItemListener);
return this;
}
public CaseDefinitionBuilder property(String name, Object value) {
activityStack.peek().setProperty(name, value);
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CaseDefinitionBuilder.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.