instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getProcessInstanceBusinessStatus() {
return processInstanceBusinessStatus;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
@Override
public String getParentId() {
return parentId;
}
@Override
public String getSuperExecutionId() {
return superExecutionId;
}
@Override
public String getCurrentActivityId() {
return currentActivityId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public FlowElement getCurrentFlowElement() {
return currentFlowElement;
}
@Override
public boolean isActive() {
return active;
}
@Override
public boolean isEnded() {
return ended;
}
@Override
public boolean isConcurrent() {
return concurrent;
}
@Override
public boolean isProcessInstanceType() {
return processInstanceType;
} | @Override
public boolean isScope() {
return scope;
}
@Override
public boolean isMultiInstanceRoot() {
return multiInstanceRoot;
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("currentActivityId='" + currentActivityId + "'")
.add("processInstanceId='" + processInstanceId + "'")
.add("processDefinitionId='" + processDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\delegate\ReadOnlyDelegateExecutionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter
implements HttpMessageConverter<RelyingPartyRegistration.Builder> {
static {
OpenSamlInitializationService.initialize();
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return RelyingPartyRegistration.Builder.class.isAssignableFrom(clazz);
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public List<MediaType> getSupportedMediaTypes() { | return Arrays.asList(MediaType.APPLICATION_XML, MediaType.TEXT_XML);
}
@Override
public RelyingPartyRegistration.Builder read(Class<? extends RelyingPartyRegistration.Builder> clazz,
HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return RelyingPartyRegistrations.fromMetadata(inputMessage.getBody());
}
@Override
public void write(RelyingPartyRegistration.Builder builder, MediaType contentType, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
throw new HttpMessageNotWritableException("This converter cannot write a RelyingPartyRegistration.Builder");
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter.java | 2 |
请完成以下Java代码 | public void setBackground(final Color bg)
{
m_text.setBackground(bg);
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
// metas
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
}
@Override
public void addKeyListener(final KeyListener l)
{
m_text.addKeyListener(l);
}
public int getCaretPosition()
{
return m_text.getCaretPosition();
}
public void setCaretPosition(final int position)
{
m_text.setCaretPosition(position);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport(); | }
@Override
protected final boolean processKeyBinding(final KeyStroke ks, final KeyEvent e, final int condition, final boolean pressed)
{
// Forward all key events on this component to the text field.
// We have to do this for the case when we are embedding this editor in a JTable and the JTable is forwarding the key strokes to editing component.
// Effect of NOT doing this: when in JTable, user presses a key (e.g. a digit) to start editing but the first key he pressed gets lost here.
if (m_text != null && condition == WHEN_FOCUSED)
{
if (m_text.processKeyBinding(ks, e, condition, pressed))
{
return true;
}
}
//
// Fallback to super
return super.processKeyBinding(ks, e, condition, pressed);
}
} // VDate | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VDate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | JwtAuthenticationConverter authenticationConverter(AuthoritiesConverter authoritiesConverter) {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter
.setJwtGrantedAuthoritiesConverter(jwt -> authoritiesConverter.convert(jwt.getClaims()));
return jwtAuthenticationConverter;
}
@Bean
SecurityFilterChain resourceServerSecurityFilterChain(HttpSecurity http,
Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter) throws Exception {
http.oauth2ResourceServer(resourceServer -> {
resourceServer.jwt(jwtDecoder -> {
jwtDecoder.jwtAuthenticationConverter(jwtAuthenticationConverter);
});
}); | http.sessionManagement(sessions -> {
sessions.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}).csrf(csrf -> {
csrf.disable();
});
http.authorizeHttpRequests(requests -> {
requests.requestMatchers("/me").authenticated();
requests.anyRequest().denyAll();
});
return http.build();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-keycloak\spring-boot-resource-server\src\main\java\com\baeldung\boot\keycloak\resourceserver\SecurityConfig.java | 2 |
请完成以下Java代码 | public ValidatorSet createFlowableExecutableProcessValidatorSet() {
ValidatorSet validatorSet = new ValidatorSet(ValidatorSetNames.FLOWABLE_EXECUTABLE_PROCESS);
validatorSet.addValidator(new AssociationValidator());
validatorSet.addValidator(new SignalValidator());
validatorSet.addValidator(new OperationValidator());
validatorSet.addValidator(new ErrorValidator());
validatorSet.addValidator(new DataObjectValidator());
validatorSet.addValidator(new BpmnModelValidator());
validatorSet.addValidator(new FlowElementValidator());
validatorSet.addValidator(new StartEventValidator());
validatorSet.addValidator(new SequenceflowValidator());
validatorSet.addValidator(new UserTaskValidator());
validatorSet.addValidator(new ServiceTaskValidator());
validatorSet.addValidator(new ScriptTaskValidator());
validatorSet.addValidator(new SendTaskValidator());
validatorSet.addValidator(new ExclusiveGatewayValidator()); | validatorSet.addValidator(new EventGatewayValidator());
validatorSet.addValidator(new SubprocessValidator());
validatorSet.addValidator(new EventSubprocessValidator());
validatorSet.addValidator(new BoundaryEventValidator());
validatorSet.addValidator(new IntermediateCatchEventValidator());
validatorSet.addValidator(new IntermediateThrowEventValidator());
validatorSet.addValidator(new MessageValidator());
validatorSet.addValidator(new EventValidator());
validatorSet.addValidator(new EndEventValidator());
validatorSet.addValidator(new ExecutionListenerValidator());
validatorSet.addValidator(new FlowableEventListenerValidator());
validatorSet.addValidator(new DiagramInterchangeInfoValidator());
return validatorSet;
}
} | repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\validator\ValidatorSetFactory.java | 1 |
请完成以下Java代码 | public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public Long getFinishedProcessInstanceCount() {
return finishedProcessInstanceCount;
}
public Long getCleanableProcessInstanceCount() {
return cleanableProcessInstanceCount;
}
public String getTenantId() {
return tenantId;
}
protected CleanableHistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) {
return engine.getHistoryService().createCleanableHistoricProcessInstanceReport();
}
public static List<CleanableHistoricProcessInstanceReportResultDto> convert(List<CleanableHistoricProcessInstanceReportResult> reportResult) {
List<CleanableHistoricProcessInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricProcessInstanceReportResultDto>(); | for (CleanableHistoricProcessInstanceReportResult current : reportResult) {
CleanableHistoricProcessInstanceReportResultDto dto = new CleanableHistoricProcessInstanceReportResultDto();
dto.setProcessDefinitionId(current.getProcessDefinitionId());
dto.setProcessDefinitionKey(current.getProcessDefinitionKey());
dto.setProcessDefinitionName(current.getProcessDefinitionName());
dto.setProcessDefinitionVersion(current.getProcessDefinitionVersion());
dto.setHistoryTimeToLive(current.getHistoryTimeToLive());
dto.setFinishedProcessInstanceCount(current.getFinishedProcessInstanceCount());
dto.setCleanableProcessInstanceCount(current.getCleanableProcessInstanceCount());
dto.setTenantId(current.getTenantId());
dtos.add(dto);
}
return dtos;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricProcessInstanceReportResultDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getRepairServicePerformed_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_RepairServicePerformed_Product_ID);
}
@Override
public void setRepair_VHU_ID (final int Repair_VHU_ID)
{
if (Repair_VHU_ID < 1)
set_Value (COLUMNNAME_Repair_VHU_ID, null);
else
set_Value (COLUMNNAME_Repair_VHU_ID, Repair_VHU_ID);
}
@Override
public int getRepair_VHU_ID()
{
return get_ValueAsInt(COLUMNNAME_Repair_VHU_ID);
}
/**
* Status AD_Reference_ID=541245
* Reference name: C_Project_Repair_Task_Status
*/
public static final int STATUS_AD_Reference_ID=541245;
/** Not Started = NS */
public static final String STATUS_NotStarted = "NS";
/** In Progress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override | public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
/**
* Type AD_Reference_ID=541243
* Reference name: C_Project_Repair_Task_Type
*/
public static final int TYPE_AD_Reference_ID=541243;
/** ServiceRepairOrder = W */
public static final String TYPE_ServiceRepairOrder = "W";
/** SpareParts = P */
public static final String TYPE_SpareParts = "P";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java-gen\de\metas\servicerepair\repository\model\X_C_Project_Repair_Task.java | 2 |
请完成以下Java代码 | public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
return client.get()
.uri(config.getLanguageServiceEndpoint())
.exchange()
.flatMap(response -> {
return (response.statusCode()
.is2xxSuccessful()) ? response.bodyToMono(String.class) : Mono.just(config.getDefaultLanguage());
})
.map(LanguageRange::parse)
.map(range -> {
exchange.getRequest()
.mutate()
.headers(h -> h.setAcceptLanguage(range));
String allOutgoingRequestLanguages = exchange.getRequest()
.getHeaders()
.getAcceptLanguage()
.stream()
.map(r -> r.getRange())
.collect(Collectors.joining(","));
logger.info("Chain Request output - Request contains Accept-Language header: " + allOutgoingRequestLanguages);
return exchange;
})
.flatMap(chain::filter);
}; | }
public static class Config {
private String languageServiceEndpoint;
private String defaultLanguage;
public Config() {
}
public String getLanguageServiceEndpoint() {
return languageServiceEndpoint;
}
public void setLanguageServiceEndpoint(String languageServiceEndpoint) {
this.languageServiceEndpoint = languageServiceEndpoint;
}
public String getDefaultLanguage() {
return defaultLanguage;
}
public void setDefaultLanguage(String defaultLanguage) {
this.defaultLanguage = defaultLanguage;
}
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ChainRequestGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public boolean isPrintFunctionSymbols ()
{
Object oo = get_Value(COLUMNNAME_IsPrintFunctionSymbols);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_AD_PrintColor getLine_PrintColor() throws RuntimeException
{
return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name)
.getPO(getLine_PrintColor_ID(), get_TrxName()); }
/** Set Line Color.
@param Line_PrintColor_ID
Table line color
*/
public void setLine_PrintColor_ID (int Line_PrintColor_ID)
{
if (Line_PrintColor_ID < 1)
set_Value (COLUMNNAME_Line_PrintColor_ID, null);
else
set_Value (COLUMNNAME_Line_PrintColor_ID, Integer.valueOf(Line_PrintColor_ID));
}
/** Get Line Color.
@return Table line color
*/
public int getLine_PrintColor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line_PrintColor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Line Stroke.
@param LineStroke
Width of the Line Stroke
*/
public void setLineStroke (BigDecimal LineStroke)
{
set_Value (COLUMNNAME_LineStroke, LineStroke);
}
/** Get Line Stroke.
@return Width of the Line Stroke
*/
public BigDecimal getLineStroke ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_LineStroke);
if (bd == null)
return Env.ZERO;
return bd;
}
/** LineStrokeType AD_Reference_ID=312 */
public static final int LINESTROKETYPE_AD_Reference_ID=312;
/** Solid Line = S */
public static final String LINESTROKETYPE_SolidLine = "S";
/** Dashed Line = D */
public static final String LINESTROKETYPE_DashedLine = "D";
/** Dotted Line = d */ | public static final String LINESTROKETYPE_DottedLine = "d";
/** Dash-Dotted Line = 2 */
public static final String LINESTROKETYPE_Dash_DottedLine = "2";
/** Set Line Stroke Type.
@param LineStrokeType
Type of the Line Stroke
*/
public void setLineStrokeType (String LineStrokeType)
{
set_Value (COLUMNNAME_LineStrokeType, LineStrokeType);
}
/** Get Line Stroke Type.
@return Type of the Line Stroke
*/
public String getLineStrokeType ()
{
return (String)get_Value(COLUMNNAME_LineStrokeType);
}
/** 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\compiere\model\X_AD_PrintTableFormat.java | 1 |
请完成以下Java代码 | public void print(int parameter) {
System.out.println("Signature is: print(int)");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class
// The method signature is independent from parameter names
public void print(int anotherParameter) {
System.out.println("Signature is: print(int)");
}
*/
public void printElement(T t) {
System.out.println("Signature is: printElement(T)");
}
/*
// Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure
// Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure | public void printElement(Serializable o) {
System.out.println("Signature is: printElement(Serializable)");
}
*/
public void print(Object... parameter) {
System.out.println("Signature is: print(Object...)");
}
/*
// Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[])
// Even though the signatures appear different, after compilation they both resolve to sum(Object[])
public void print(Object[] parameter) {
System.out.println("Signature is: print(Object[])");
}
*/
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\signature\OverloadingErrors.java | 1 |
请完成以下Java代码 | public ValueNamePair[] getClickCountWeek ()
{
getMClickCount();
if (m_clickCount == null)
return new ValueNamePair[0];
return m_clickCount.getCountWeek();
} // getClickCountWeek
/**
* Get CounterCount
* @return Counter Count
*/
public MCounterCount getMCounterCount()
{
if (getW_CounterCount_ID() == 0)
return null;
if (m_counterCount == null)
m_counterCount = new MCounterCount (getCtx(), getW_CounterCount_ID(), get_TrxName());
return m_counterCount;
} // MCounterCount
/**
* Get Sales Rep ID.
* (AD_User_ID of oldest BP user) | * @return Sales Rep ID
*/
public int getSalesRep_ID()
{
if (m_SalesRep_ID == 0)
{
m_SalesRep_ID = getAD_User_ID();
if (m_SalesRep_ID == 0)
m_SalesRep_ID = DB.getSQLValue(null,
"SELECT AD_User_ID FROM AD_User "
+ "WHERE C_BPartner_ID=? AND IsActive='Y' ORDER BY AD_User_ID", getC_BPartner_ID());
}
return m_SalesRep_ID;
} // getSalesRep_ID
} // MAdvertisement | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAdvertisement.java | 1 |
请完成以下Java代码 | public Document createNewDocument(final DocumentEntityDescriptor entityDescriptor, @Nullable final Document parentDocument, final IDocumentChangesCollector changesCollector)
{
throw new UnsupportedOperationException();
}
@Override
public void refresh(final @NotNull Document document)
{
final AttributesIncludedTabDataKey key = extractKey(document);
final AttributesIncludedTabData data = attributesIncludedTabService.getData(key);
refreshDocumentFromData(document, data);
}
@Override
public SaveResult save(final @NotNull Document document)
{
final AttributesIncludedTabEntityBinding entityBinding = extractEntityBinding(document);
final AttributesIncludedTabData data = attributesIncludedTabService.updateByKey(
extractKey(document),
entityBinding.getAttributeIds(),
(attributeId, field) -> {
final String fieldName = entityBinding.getFieldNameByAttributeId(attributeId);
final IDocumentFieldView documentField = document.getFieldView(fieldName);
if (!documentField.hasChangesToSave())
{
return field;
}
final AttributesIncludedTabFieldBinding fieldBinding = extractFieldBinding(document, fieldName);
return fieldBinding.updateData(
field != null ? field : newDataField(fieldBinding),
documentField);
});
refreshDocumentFromData(document, data);
// Notify the parent document that one of its children were saved (copied from SqlDocumentsRepository)
document.getParentDocument().onChildSaved(document); | return SaveResult.SAVED;
}
private static AttributesIncludedTabDataField newDataField(final AttributesIncludedTabFieldBinding fieldBinding)
{
return AttributesIncludedTabDataField.builder()
.attributeId(fieldBinding.getAttributeId())
.valueType(fieldBinding.getAttributeValueType())
.build();
}
private void refreshDocumentFromData(@NonNull final Document document, @NonNull final AttributesIncludedTabData data)
{
document.refreshFromSupplier(new AttributesIncludedTabDataAsDocumentValuesSupplier(data));
}
@Override
public void delete(final @NotNull Document document)
{
throw new UnsupportedOperationException();
}
@Override
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) {return AttributesIncludedTabDataAsDocumentValuesSupplier.VERSION_DEFAULT;}
@Override
public int retrieveLastLineNo(final DocumentQuery query)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabDocumentsRepository.java | 1 |
请完成以下Java代码 | public String executeLocal(String cmd)
{
log.info(cmd);
if (m_task != null && m_task.isAlive())
m_task.interrupt();
m_task = new Task(cmd);
m_task.start();
StringBuffer sb = new StringBuffer();
while (true)
{
// Give it a bit of time
try
{
Thread.sleep(500);
}
catch (InterruptedException ioe)
{
log.error(cmd, ioe);
}
// Info to user
//metas: c.ghita@metas.ro : start
sb.append(m_task.getOut());
if (m_task.getOut().length() > 0)
sb.append("\n-----------\n");
sb.append(m_task.getErr());
if (m_task.getErr().length() > 0)
sb.append("\n-----------");
//metas: c.ghita@metas.ro : end
// Are we done?
if (!m_task.isAlive())
break;
}
log.info("done");
return sb.toString();
} // executeLocal
/**
* Execute Task locally and wait
* @param cmd command
* @return execution info
*/
public String executeRemote(String cmd) | {
log.info(cmd);
return "Remote:\n";
} // executeRemote
/**
* String Representation
* @return info
*/
public String toString ()
{
StringBuffer sb = new StringBuffer ("MTask[");
sb.append(get_ID())
.append("-").append(getName())
.append(";Server=").append(isServerProcess())
.append(";").append(getOS_Command())
.append ("]");
return sb.toString ();
} // toString
/*
* metas: c.ghita@metas.ro
* get Task
*/
public Task getTask()
{
return m_task;
}
} // MTask | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MTask.java | 1 |
请完成以下Java代码 | public ImmutableList<I_C_BP_SupplierApproval> retrieveBPartnerSupplierApprovals(@NonNull final BPartnerId partnerId)
{
return queryBL.createQueryBuilder(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_C_BPartner_ID, partnerId)
.addOnlyActiveRecordsFilter()
.create()
.listImmutable(I_C_BP_SupplierApproval.class);
}
public void updateBPSupplierApproval(@NonNull final BPSupplierApprovalId bpSupplierApprovalId,
@Nullable final String supplierApproval,
@Nullable final Instant supplierApprovalDateParameter)
{
final I_C_BP_SupplierApproval bpSupplierApprovalRecord = getById(bpSupplierApprovalId);
bpSupplierApprovalRecord.setSupplierApproval(supplierApproval);
final Timestamp supplierApprovalDate = supplierApproval == null ? null : TimeUtil.asTimestamp(supplierApprovalDateParameter);
bpSupplierApprovalRecord.setSupplierApproval_Date(supplierApprovalDate);
save(bpSupplierApprovalRecord);
}
public ImmutableList<I_C_BP_SupplierApproval> retrieveBPSupplierApprovalsAboutToExpire(final int maxMonthsUntilExpirationDate)
{
final LocalDate today = SystemTime.asLocalDate();
final LocalDate maxExpirationDate = today.plusMonths(maxMonthsUntilExpirationDate);
final IQueryFilter<I_C_BP_SupplierApproval> filterThreeYears =
queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval, SupplierApproval.ThreeYears)
.addCompareFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval_Date,
CompareQueryFilter.Operator.LESS_OR_EQUAL,
maxExpirationDate.minusYears(3));
final IQueryFilter<I_C_BP_SupplierApproval> filterTwoYears =
queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval, SupplierApproval.TwoYears)
.addCompareFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval_Date,
CompareQueryFilter.Operator.LESS_OR_EQUAL,
maxExpirationDate.minusYears(2)); | final IQueryFilter<I_C_BP_SupplierApproval> filterOneYear =
queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.addEqualsFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval, SupplierApproval.OneYear)
.addCompareFilter(I_C_BP_SupplierApproval.COLUMNNAME_SupplierApproval_Date,
CompareQueryFilter.Operator.LESS_OR_EQUAL,
maxExpirationDate.minusYears(1));
final IQueryFilter<I_C_BP_SupplierApproval> supplierApprovalOptionFilter
= queryBL.createCompositeQueryFilter(I_C_BP_SupplierApproval.class)
.setJoinOr()
.addFilter(filterThreeYears)
.addFilter(filterTwoYears)
.addFilter(filterOneYear);
return queryBL.createQueryBuilder(I_C_BP_SupplierApproval.class)
.filter(supplierApprovalOptionFilter)
.create()
.listImmutable(I_C_BP_SupplierApproval.class)
;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerSupplierApprovalRepository.java | 1 |
请完成以下Java代码 | public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/ | @Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ColumnCallout.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() { | return price;
}
public void setPrice(double price) {
this.price = price;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\fetchandrefresh\OrderItem.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Integer getTotal()
{
return total;
}
public void setTotal(Integer total)
{
this.total = total;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
DisputeSummaryResponse disputeSummaryResponse = (DisputeSummaryResponse)o;
return Objects.equals(this.href, disputeSummaryResponse.href) &&
Objects.equals(this.limit, disputeSummaryResponse.limit) &&
Objects.equals(this.next, disputeSummaryResponse.next) &&
Objects.equals(this.offset, disputeSummaryResponse.offset) &&
Objects.equals(this.paymentDisputeSummaries, disputeSummaryResponse.paymentDisputeSummaries) &&
Objects.equals(this.prev, disputeSummaryResponse.prev) &&
Objects.equals(this.total, disputeSummaryResponse.total);
}
@Override
public int hashCode()
{
return Objects.hash(href, limit, next, offset, paymentDisputeSummaries, prev, total);
}
@Override
public String toString()
{ | StringBuilder sb = new StringBuilder();
sb.append("class DisputeSummaryResponse {\n");
sb.append(" href: ").append(toIndentedString(href)).append("\n");
sb.append(" limit: ").append(toIndentedString(limit)).append("\n");
sb.append(" next: ").append(toIndentedString(next)).append("\n");
sb.append(" offset: ").append(toIndentedString(offset)).append("\n");
sb.append(" paymentDisputeSummaries: ").append(toIndentedString(paymentDisputeSummaries)).append("\n");
sb.append(" prev: ").append(toIndentedString(prev)).append("\n");
sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\DisputeSummaryResponse.java | 2 |
请完成以下Java代码 | public void setProcessing(ProcessingType value) {
this.processing = value;
}
/**
* Gets the value of the payload property.
*
* @return
* possible object is
* {@link PayloadType }
*
*/
public PayloadType getPayload() {
return payload;
}
/**
* Sets the value of the payload property.
*
* @param value
* allowed object is
* {@link PayloadType }
*
*/
public void setPayload(PayloadType value) {
this.payload = value;
}
/**
* Gets the value of the signature property.
*
* @return
* possible object is
* {@link SignatureType }
*
*/
public SignatureType getSignature() {
return signature;
}
/**
* Sets the value of the signature property.
*
* @param value
* allowed object is
* {@link SignatureType }
*
*/
public void setSignature(SignatureType value) {
this.signature = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/** | * Gets the value of the modus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getModus() {
if (modus == null) {
return "production";
} else {
return modus;
}
}
/**
* Sets the value of the modus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setModus(String value) {
this.modus = value;
}
/**
* Gets the value of the validationStatus property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getValidationStatus() {
return validationStatus;
}
/**
* Sets the value of the validationStatus property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setValidationStatus(Long value) {
this.validationStatus = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RequestType.java | 1 |
请完成以下Java代码 | public void onChangeCountryIsActive(final I_C_Country country)
{
setCountryAttributeAsActive(country, country.isActive());
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_Country.COLUMNNAME_Name)
public void onChangeCountryName(final I_C_Country country)
{
setCountryAttributeName(country);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void onDeleteCountry(final I_C_Country country)
{
setCountryAttributeAsActive(country, false);
}
private void setCountryAttributeAsActive(final I_C_Country country, final boolean isActive)
{
final AttributeListValue existingAttributeValue = getAttributeValue(country);
if (existingAttributeValue != null)
{
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder()
.id(existingAttributeValue.getId())
.active(isActive)
.build());
}
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = { I_C_Country.COLUMNNAME_DisplaySequence, I_C_Country.COLUMNNAME_DisplaySequenceLocal }) | public void onChangeCountryDisplaySequence(@NonNull final I_C_Country country)
{
assertValidDisplaySequences(country);
}
public void assertValidDisplaySequences(@NonNull final I_C_Country country)
{
AddressDisplaySequence.ofNullable(country.getDisplaySequence()).assertValid();
AddressDisplaySequence.ofNullable(country.getDisplaySequenceLocal()).assertValid();
}
private void setCountryAttributeName(@NonNull final I_C_Country country)
{
final AttributeListValue existingAttributeValue = getAttributeValue(country);
if (existingAttributeValue != null)
{
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
attributesRepo.changeAttributeValue(AttributeListValueChangeRequest.builder()
.id(existingAttributeValue.getId())
.name(country.getName())
.build());
}
}
private AttributeListValue getAttributeValue(final I_C_Country country)
{
return Services.get(ICountryAttributeDAO.class).retrieveAttributeValue(Env.getCtx(), country, true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\location\interceptor\C_Country.java | 1 |
请完成以下Java代码 | private static PropertyValueWithOrigin getPropertyValueWithOrigin(final String propertyName, final Environment environment)
{
final String value = environment.getProperty(propertyName);
final String origin = getPropertySourceName(propertyName, environment).orElse("?");
return PropertyValueWithOrigin.builder()
.propertyName(propertyName)
.propertyValue(value)
.origin(origin)
.build();
}
private static Optional<String> getPropertySourceName(final String propertyName, final Environment environment)
{
if (environment instanceof AbstractEnvironment)
{
final MutablePropertySources propertySources = ((AbstractEnvironment)environment).getPropertySources();
for (final PropertySource<?> propertySource : propertySources)
{
final Object propertyValue = propertySource.getProperty(propertyName);
if (propertyValue != null)
{
if (propertySource instanceof OriginLookup)
{
@SuppressWarnings({ "unchecked", "rawtypes" }) final Origin origin = ((OriginLookup)propertySource).getOrigin(propertyName);
return Optional.of(origin.toString());
}
else
{
return Optional.of(propertySource.getName());
}
}
} | }
return Optional.empty();
}
@Value
@Builder
private static class PropertyValueWithOrigin
{
@NonNull String propertyName;
String propertyValue;
String origin;
@Override
public String toString()
{
return propertyName + " = "
+ (propertyValue != null ? "'" + propertyValue + "'" : "null")
+ " (origin: " + origin + ")";
}
public boolean isBlankValue()
{
return propertyValue == null || Check.isBlank(propertyValue);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\elasticsearch\ElasticsearchConfig.java | 1 |
请完成以下Java代码 | public class Player implements Comparable<Player> {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
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 this.name;
}
@Override
public int compareTo(Player otherPlayer) {
return Integer.compare(getRanking(), otherPlayer.getRanking());
}
} | repos\tutorials-master\core-java-modules\core-java-lang\src\main\java\com\baeldung\comparable\Player.java | 1 |
请完成以下Java代码 | public String getName() {
return title;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getLink() {
String scope = (tenantId != null && tenantId.isSysTenantId()) ? "system" : "tenant"; // tenantId is null in case of export to git
if (resourceType == ResourceType.IMAGE) {
return "/api/images/" + scope + "/" + resourceKey;
} else {
return "/api/resource/" + resourceType.name().toLowerCase() + "/" + scope + "/" + resourceKey;
}
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getPublicLink() {
if (resourceType == ResourceType.IMAGE && isPublic) {
return "/api/images/public/" + getPublicResourceKey();
}
return null;
}
@JsonIgnore
public String getSearchText() { | return title;
}
@SneakyThrows
public <T> T getDescriptor(Class<T> type) {
return descriptor != null ? mapper.treeToValue(descriptor, type) : null;
}
public <T> void updateDescriptor(Class<T> type, UnaryOperator<T> updater) {
T descriptor = getDescriptor(type);
descriptor = updater.apply(descriptor);
setDescriptorValue(descriptor);
}
@JsonIgnore
public void setDescriptorValue(Object value) {
this.descriptor = value != null ? mapper.valueToTree(value) : null;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\TbResourceInfo.java | 1 |
请完成以下Java代码 | public Builder deviceCodeTimeToLive(Duration deviceCodeTimeToLive) {
Assert.notNull(deviceCodeTimeToLive, "deviceCodeTimeToLive cannot be null");
Assert.isTrue(deviceCodeTimeToLive.getSeconds() > 0,
"deviceCodeTimeToLive must be greater than Duration.ZERO");
return setting(ConfigurationSettingNames.Token.DEVICE_CODE_TIME_TO_LIVE, deviceCodeTimeToLive);
}
/**
* Set to {@code true} if refresh tokens are reused when returning the access
* token response, or {@code false} if a new refresh token is issued.
* @param reuseRefreshTokens {@code true} to reuse refresh tokens, {@code false}
* to issue new refresh tokens
* @return the {@link Builder} for further configuration
*/
public Builder reuseRefreshTokens(boolean reuseRefreshTokens) {
return setting(ConfigurationSettingNames.Token.REUSE_REFRESH_TOKENS, reuseRefreshTokens);
}
/**
* Set the time-to-live for a refresh token. Must be greater than
* {@code Duration.ZERO}.
* @param refreshTokenTimeToLive the time-to-live for a refresh token
* @return the {@link Builder} for further configuration
*/
public Builder refreshTokenTimeToLive(Duration refreshTokenTimeToLive) {
Assert.notNull(refreshTokenTimeToLive, "refreshTokenTimeToLive cannot be null");
Assert.isTrue(refreshTokenTimeToLive.getSeconds() > 0,
"refreshTokenTimeToLive must be greater than Duration.ZERO");
return setting(ConfigurationSettingNames.Token.REFRESH_TOKEN_TIME_TO_LIVE, refreshTokenTimeToLive);
}
/**
* Sets the {@link SignatureAlgorithm JWS} algorithm for signing the
* {@link OidcIdToken ID Token}.
* @param idTokenSignatureAlgorithm the {@link SignatureAlgorithm JWS} algorithm
* for signing the {@link OidcIdToken ID Token}
* @return the {@link Builder} for further configuration | */
public Builder idTokenSignatureAlgorithm(SignatureAlgorithm idTokenSignatureAlgorithm) {
Assert.notNull(idTokenSignatureAlgorithm, "idTokenSignatureAlgorithm cannot be null");
return setting(ConfigurationSettingNames.Token.ID_TOKEN_SIGNATURE_ALGORITHM, idTokenSignatureAlgorithm);
}
/**
* Set to {@code true} if access tokens must be bound to the client
* {@code X509Certificate} received during client authentication when using the
* {@code tls_client_auth} or {@code self_signed_tls_client_auth} method.
* @param x509CertificateBoundAccessTokens {@code true} if access tokens must be
* bound to the client {@code X509Certificate}, {@code false} otherwise
* @return the {@link Builder} for further configuration
*/
public Builder x509CertificateBoundAccessTokens(boolean x509CertificateBoundAccessTokens) {
return setting(ConfigurationSettingNames.Token.X509_CERTIFICATE_BOUND_ACCESS_TOKENS,
x509CertificateBoundAccessTokens);
}
/**
* Builds the {@link TokenSettings}.
* @return the {@link TokenSettings}
*/
@Override
public TokenSettings build() {
return new TokenSettings(getSettings());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\TokenSettings.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void cacheTokenKeys(Map<String, String> tokenKeys) {
this.cachedTokenKeys = Map.copyOf(tokenKeys);
}
private boolean hasValidSignature(Token token, String key) {
try {
PublicKey publicKey = getPublicKey(key);
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(publicKey);
signature.update(token.getContent());
return signature.verify(token.getSignature());
}
catch (GeneralSecurityException ex) {
return false;
}
}
private PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
key = key.replace("-----END PUBLIC KEY-----", "");
key = key.trim().replace("\n", "");
byte[] bytes = Base64.getDecoder().decode(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
return KeyFactory.getInstance("RSA").generatePublic(keySpec);
}
private Mono<Void> validateExpiry(Token token) {
long currentTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); | if (currentTime > token.getExpiry()) {
return Mono.error(new CloudFoundryAuthorizationException(Reason.TOKEN_EXPIRED, "Token expired"));
}
return Mono.empty();
}
private Mono<Void> validateIssuer(Token token) {
return this.securityService.getUaaUrl()
.map((uaaUrl) -> String.format("%s/oauth/token", uaaUrl))
.filter((issuerUri) -> issuerUri.equals(token.getIssuer()))
.switchIfEmpty(Mono
.error(new CloudFoundryAuthorizationException(Reason.INVALID_ISSUER, "Token issuer does not match")))
.then();
}
private Mono<Void> validateAudience(Token token) {
if (!token.getScope().contains("actuator.read")) {
return Mono.error(new CloudFoundryAuthorizationException(Reason.INVALID_AUDIENCE,
"Token does not have audience actuator"));
}
return Mono.empty();
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\reactive\TokenValidator.java | 2 |
请完成以下Java代码 | public class TransactionDependentTaskListenerExecutionScope {
protected final String processInstanceId;
protected final String executionId;
protected final Task task;
protected final Map<String, Object> executionVariables;
protected final Map<String, Object> customPropertiesMap;
public TransactionDependentTaskListenerExecutionScope(
String processInstanceId,
String executionId,
Task task,
Map<String, Object> executionVariables,
Map<String, Object> customPropertiesMap
) {
this.processInstanceId = processInstanceId;
this.executionId = executionId;
this.task = task;
this.executionVariables = executionVariables;
this.customPropertiesMap = customPropertiesMap;
}
public String getProcessInstanceId() {
return processInstanceId;
} | public String getExecutionId() {
return executionId;
}
public Task getTask() {
return task;
}
public Map<String, Object> getExecutionVariables() {
return executionVariables;
}
public Map<String, Object> getCustomPropertiesMap() {
return customPropertiesMap;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\TransactionDependentTaskListenerExecutionScope.java | 1 |
请完成以下Java代码 | private void expandTree()
{
if (treeExpand.isSelected())
{
for (int row = 0; row < tree.getRowCount(); row++)
{
tree.expandRow(row);
}
}
else
{
// patch: 1654055 +jgubo Changed direction of collapsing the tree nodes
for (int row = tree.getRowCount(); row > 0; row--)
{
tree.collapseRow(row);
}
}
} // expandTree
private static void setMappings(final JTree tree)
{
final ActionMap map = tree.getActionMap();
map.put(TransferHandler.getCutAction().getValue(Action.NAME), TransferHandler.getCutAction());
map.put(TransferHandler.getPasteAction().getValue(Action.NAME), TransferHandler.getPasteAction());
}
public AdempiereTreeModel getTreeModel()
{
return treeModel;
}
public void filterIds(final List<Integer> ids)
{
if (treeModel == null) | {
return; // nothing to do
}
Check.assumeNotNull(ids, "Param 'ids' is not null");
treeModel.filterIds(ids);
if (treeExpand.isSelected())
{
expandTree();
}
if (ids != null && ids.size() > 0)
{
setTreeSelectionPath(ids.get(0), true);
}
}
@Override
public void requestFocus()
{
treeSearch.requestFocus();
}
@Override
public boolean requestFocusInWindow()
{
return treeSearch.requestFocusInWindow();
}
} // VTreePanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\VTreePanel.java | 1 |
请完成以下Java代码 | public static final DaysOfWeekExploder of(final DayOfWeek... weekDays)
{
return of(ImmutableSet.copyOf(weekDays));
}
private static final ImmutableSet<DayOfWeek> ALL_DAYS_OF_WEEK_LIST = ImmutableSet.copyOf(DayOfWeek.values());
public static final DaysOfWeekExploder ALL_DAYS_OF_WEEK = new DaysOfWeekExploder(ALL_DAYS_OF_WEEK_LIST);
private final ImmutableSet<DayOfWeek> weekDays;
private final DayOfWeek firstDayOfTheWeek;
private DaysOfWeekExploder(final ImmutableSet<DayOfWeek> weekDays)
{
Check.assumeNotEmpty(weekDays, "weekDays not empty");
this.weekDays = weekDays;
this.firstDayOfTheWeek = DayOfWeek.MONDAY;
}
/**
* @return all dates which are in same week as <code>date</code> and are equal or after it
*/
@Override
public Set<LocalDateTime> explodeForward(final LocalDateTime date)
{
final DayOfWeek currentDayOfWeek = date.getDayOfWeek();
return weekDays.stream()
.filter(dayOfWeek -> dayOfWeek.getValue() >= currentDayOfWeek.getValue()) | .map(dayOfWeek -> date.with(TemporalAdjusters.nextOrSame(dayOfWeek)))
.collect(ImmutableSet.toImmutableSet());
}
/**
* @return all dates which are in one week range from <code>date</code>
*/
@Override
public Set<LocalDateTime> explodeBackward(final LocalDateTime date)
{
return weekDays.stream()
.map(dayOfWeek -> date.with(TemporalAdjusters.previousOrSame(dayOfWeek)))
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DaysOfWeekExploder.java | 1 |
请完成以下Java代码 | public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return targetType.getElementTypeDescriptor() == null
|| this.conversionService.canConvert(sourceType, targetType.getElementTypeDescriptor());
}
@Override
public @Nullable Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
return convert((String) source, sourceType, targetType);
}
private Object convert(String source, TypeDescriptor sourceType, TypeDescriptor targetType) {
Delimiter delimiter = targetType.getAnnotation(Delimiter.class);
String[] elements = getElements(source, (delimiter != null) ? delimiter.value() : ",");
TypeDescriptor elementDescriptor = targetType.getElementTypeDescriptor(); | Assert.state(elementDescriptor != null, "elementDescriptor is missing");
Object target = Array.newInstance(elementDescriptor.getType(), elements.length);
for (int i = 0; i < elements.length; i++) {
String sourceElement = elements[i];
Object targetElement = this.conversionService.convert(sourceElement.trim(), sourceType, elementDescriptor);
Array.set(target, i, targetElement);
}
return target;
}
private String[] getElements(String source, String delimiter) {
return StringUtils.delimitedListToStringArray(source, Delimiter.NONE.equals(delimiter) ? null : delimiter);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\convert\DelimitedStringToArrayConverter.java | 1 |
请完成以下Java代码 | public class AddSubtractDaysSkippingWeekendsUtils {
public static LocalDate addDaysSkippingWeekends(LocalDate date, int days) {
if (days < 1) {
return date;
}
LocalDate result = date;
int addedDays = 0;
while (addedDays < days) {
result = result.plusDays(1);
if (!(result.getDayOfWeek() == DayOfWeek.SATURDAY || result.getDayOfWeek() == DayOfWeek.SUNDAY)) {
++addedDays;
}
}
return result;
} | public static LocalDate subtractDaysSkippingWeekends(LocalDate date, int days) {
if (days < 1) {
return date;
}
LocalDate result = date;
int subtractedDays = 0;
while (subtractedDays < days) {
result = result.minusDays(1);
if (!(result.getDayOfWeek() == DayOfWeek.SATURDAY || result.getDayOfWeek() == DayOfWeek.SUNDAY)) {
++subtractedDays;
}
}
return result;
}
} | repos\tutorials-master\core-java-modules\core-java-date-operations-2\src\main\java\com\baeldung\skipweekends\AddSubtractDaysSkippingWeekendsUtils.java | 1 |
请完成以下Java代码 | private IHUProductStorage getHUProductStorage()
{
return huProductStorageSupplier.get();
}
@Override
public I_M_HU_PI getM_LU_HU_PI()
{
return null; // no LU
}
@Override
public I_M_HU_PI getM_TU_HU_PI()
{
final I_M_HU_PI tuPI = Services.get(IHandlingUnitsBL.class).getEffectivePI(aggregatedTU);
if(tuPI == null)
{
new HUException("Invalid aggregated TU. Effective PI could not be fetched; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger);
return null;
}
return tuPI;
}
@Override
public boolean isInfiniteQtyTUsPerLU()
{
return false;
}
@Override
public BigDecimal getQtyTUsPerLU()
{
final I_M_HU_Item parentHUItem = aggregatedTU.getM_HU_Item_Parent();
if (parentHUItem == null)
{
// note: shall not happen because we assume the aggregatedTU is really an aggregated TU.
new HUException("Invalid aggregated TU. Parent item is null; aggregatedTU=" + aggregatedTU).throwIfDeveloperModeOrLogWarningElse(logger);
return null;
}
return parentHUItem.getQty();
} | @Override
public boolean isInfiniteQtyCUsPerTU()
{
return false;
}
@Override
public BigDecimal getQtyCUsPerTU()
{
final IHUProductStorage huProductStorage = getHUProductStorage();
if (huProductStorage == null)
{
return null;
}
final BigDecimal qtyTUsPerLU = getQtyTUsPerLU();
if (qtyTUsPerLU == null || qtyTUsPerLU.signum() == 0)
{
return null;
}
final BigDecimal qtyCUTotal = huProductStorage.getQty().toBigDecimal();
final BigDecimal qtyCUsPerTU = qtyCUTotal.divide(qtyTUsPerLU, 0, RoundingMode.HALF_UP);
return qtyCUsPerTU;
}
@Override
public I_C_UOM getQtyCUsPerTU_UOM()
{
final IHUProductStorage huProductStorage = getHUProductStorage();
if (huProductStorage == null)
{
return null;
}
return huProductStorage.getC_UOM();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\util\AggregatedTUPackingInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
// The methods below are not relevant, as getValue() is used directly to return the value set during the transaction
@Override
public String getTextValue() {
return null;
}
@Override
public void setTextValue(String textValue) {
}
@Override
public String getTextValue2() {
return null;
} | @Override
public void setTextValue2(String textValue2) {
}
@Override
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {
}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public void setBytes(byte[] bytes) {
}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java | 2 |
请完成以下Java代码 | private Node rebalance(Node z) {
updateHeight(z);
int balance = getBalance(z);
if (balance > 1) {
if (height(z.right.right) > height(z.right.left)) {
z = rotateLeft(z);
} else {
z.right = rotateRight(z.right);
z = rotateLeft(z);
}
} else if (balance < -1) {
if (height(z.left.left) > height(z.left.right)) {
z = rotateRight(z);
} else {
z.left = rotateLeft(z.left);
z = rotateRight(z);
}
}
return z;
}
private Node rotateRight(Node y) {
Node x = y.left;
Node z = x.right;
x.right = y;
y.left = z;
updateHeight(y);
updateHeight(x); | return x;
}
private Node rotateLeft(Node y) {
Node x = y.right;
Node z = x.left;
x.left = y;
y.right = z;
updateHeight(y);
updateHeight(x);
return x;
}
private void updateHeight(Node n) {
n.height = 1 + Math.max(height(n.left), height(n.right));
}
private int height(Node n) {
return n == null ? -1 : n.height;
}
public int getBalance(Node n) {
return (n == null) ? 0 : height(n.right) - height(n.left);
}
} | repos\tutorials-master\data-structures-2\src\main\java\com\baeldung\avltree\AVLTree.java | 1 |
请完成以下Java代码 | public void save(RegisteredClient registeredClient) {
Assert.notNull(registeredClient, "registeredClient cannot be null");
if (!this.idRegistrationMap.containsKey(registeredClient.getId())) {
assertUniqueIdentifiers(registeredClient, this.idRegistrationMap);
}
this.idRegistrationMap.put(registeredClient.getId(), registeredClient);
this.clientIdRegistrationMap.put(registeredClient.getClientId(), registeredClient);
}
@Nullable
@Override
public RegisteredClient findById(String id) {
Assert.hasText(id, "id cannot be empty");
return this.idRegistrationMap.get(id);
}
@Nullable
@Override
public RegisteredClient findByClientId(String clientId) {
Assert.hasText(clientId, "clientId cannot be empty");
return this.clientIdRegistrationMap.get(clientId);
}
private void assertUniqueIdentifiers(RegisteredClient registeredClient, | Map<String, RegisteredClient> registrations) {
registrations.values().forEach((registration) -> {
if (registeredClient.getId().equals(registration.getId())) {
throw new IllegalArgumentException("Registered client must be unique. " + "Found duplicate identifier: "
+ registeredClient.getId());
}
if (registeredClient.getClientId().equals(registration.getClientId())) {
throw new IllegalArgumentException("Registered client must be unique. "
+ "Found duplicate client identifier: " + registeredClient.getClientId());
}
if (StringUtils.hasText(registeredClient.getClientSecret())
&& registeredClient.getClientSecret().equals(registration.getClientSecret())) {
throw new IllegalArgumentException("Registered client must be unique. "
+ "Found duplicate client secret for identifier: " + registeredClient.getId());
}
});
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\client\InMemoryRegisteredClientRepository.java | 1 |
请完成以下Java代码 | public int getDLM_Partition_Workqueue_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Workqueue_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Datensatz-ID.
*
* @param Record_ID
* Direct internal record ID
*/
@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, Integer.valueOf(Record_ID));
}
}
/**
* Get Datensatz-ID.
*
* @return Direct internal record ID
*/
@Override
public int getRecord_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
} | /**
* Set Name der DB-Tabelle.
*
* @param TableName Name der DB-Tabelle
*/
@Override
public void setTableName(final java.lang.String TableName)
{
throw new IllegalArgumentException("TableName is virtual column");
}
/**
* Get Name der DB-Tabelle.
*
* @return Name der DB-Tabelle
*/
@Override
public java.lang.String getTableName()
{
return (java.lang.String)get_Value(COLUMNNAME_TableName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Workqueue.java | 1 |
请完成以下Java代码 | public static SqlQueryOrderBy of(@Nullable final String orderBy)
{
final String orderByNorm = normalize(orderBy);
return orderByNorm != null
? new SqlQueryOrderBy(orderByNorm)
: NONE;
}
private static String normalize(@Nullable final String orderBy)
{
String orderByFinal = StringUtils.trimBlankToNull(orderBy);
if (orderByFinal == null)
{
return null;
}
if (orderByFinal.toUpperCase().startsWith(KEYWORD_ORDER_BY)) | {
orderByFinal = orderByFinal.substring(KEYWORD_ORDER_BY.length()).trim();
}
return orderByFinal;
}
@Override
@Deprecated
public String toString() {return getSql();}
@Override
public String getSql() {return orderBy;}
@Override
public Comparator<Object> getComparator() {throw new UnsupportedOperationException("SqlQueryOrderBy does not support Comparator");}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\SqlQueryOrderBy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ProcessApplicationStopService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
@Override
public void start(StartContext arg0) throws StartException {
provider.accept(this);
}
@Override
public void stop(StopContext arg0) {
provider.accept(null);
ManagedReference reference = null;
try {
// get the process application component
ProcessApplicationInterface processApplication = null;
if(paComponentViewSupplier != null) {
ComponentView componentView = paComponentViewSupplier.get();
reference = componentView.createInstance();
processApplication = (ProcessApplicationInterface) reference.getInstance();
} | else {
processApplication = noViewApplicationSupplier.get();
}
BpmPlatformPlugins bpmPlatformPlugins = platformPluginsSupplier.get();
List<BpmPlatformPlugin> plugins = bpmPlatformPlugins.getPlugins();
for (BpmPlatformPlugin bpmPlatformPlugin : plugins) {
bpmPlatformPlugin.postProcessApplicationUndeploy(processApplication);
}
}
catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception while invoking BpmPlatformPlugin.postProcessApplicationUndeploy", e);
}
finally {
if(reference != null) {
reference.release();
}
}
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\ProcessApplicationStopService.java | 2 |
请完成以下Java代码 | public class FallbackFlatrateTermEventListener implements IFlatrateTermEventListener
{
private static final AdMessageKey MSG_TERM_ERROR_ENTRY_ALREADY_CO_2P = AdMessageKey.of("Term_Error_Entry_Already_CO");
private final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class);
private final IUOMDAO uomDAO = Services.get(IUOMDAO.class);
@Override
@OverridingMethodsMustInvokeSuper
public void beforeFlatrateTermReactivate(final I_C_Flatrate_Term term)
{
deleteFlatrateTermDataEntriesOnReactivate(term);
deleteC_Invoice_Clearing_AllocsOnReactivate(term);
deleteInvoiceCandidates(term);
}
/**
* Deletes {@link I_C_Flatrate_DataEntry} records for given term.
*
* @throws AdempiereException if any data entry record is completed
*/
protected void deleteFlatrateTermDataEntriesOnReactivate(final I_C_Flatrate_Term term)
{
final List<I_C_Flatrate_DataEntry> entries = flatrateDAO.retrieveDataEntries(term, null, null);
for (final I_C_Flatrate_DataEntry entry : entries)
{
// note: The system will prevent the deletion of a completed entry
// However, we want to give a user-friendly explanation to the user.
if (X_C_Flatrate_DataEntry.DOCSTATUS_Completed.equals(entry.getDocStatus()))
{
final ITranslatableString uomName = uomDAO.getName(UomId.ofRepoId(entry.getC_UOM_ID()));
throw new AdempiereException(
MSG_TERM_ERROR_ENTRY_ALREADY_CO_2P,
uomName, entry.getC_Period().getName());
}
InterfaceWrapperHelper.delete(entry);
}
}
/**
* Deletes {@link I_C_Invoice_Clearing_Alloc}s for given term.
*/
protected void deleteC_Invoice_Clearing_AllocsOnReactivate(final I_C_Flatrate_Term term)
{
// note: we assume that invoice candidate validator will take care of the invoice candidate's IsToClear flag
final IFlatrateDAO flatrateDAO = Services.get(IFlatrateDAO.class); | final List<I_C_Invoice_Clearing_Alloc> icas = flatrateDAO.retrieveClearingAllocs(term);
for (final I_C_Invoice_Clearing_Alloc ica : icas)
{
InterfaceWrapperHelper.delete(ica);
}
}
/**
* When a term is reactivated, its invoice candidate needs to be deleted.
* Note that we assume the deletion will fail with a meaningful error message if the invoice candidate has already been invoiced.
*/
public void deleteInvoiceCandidates(@NonNull final I_C_Flatrate_Term term)
{
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(term);
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void afterSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void afterFlatrateTermEnded(final I_C_Flatrate_Term term)
{
// nothing
}
/**
* Does nothing; Feel free to override.
*/
@Override
public void beforeSaveOfNextTermForPredecessor(final I_C_Flatrate_Term next, final I_C_Flatrate_Term predecessor)
{
// nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\spi\FallbackFlatrateTermEventListener.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(HumanTask.class, CMMN_ELEMENT_HUMAN_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<HumanTask>() {
public HumanTask newInstance(ModelTypeInstanceContext instanceContext) {
return new HumanTaskImpl(instanceContext);
}
});
performerRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_PERFORMER_REF)
.idAttributeReference(Role.class)
.build();
/** camunda extensions */
camundaAssigneeAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ASSIGNEE)
.namespace(CAMUNDA_NS)
.build();
camundaCandidateGroupsAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_GROUPS)
.namespace(CAMUNDA_NS)
.build();
camundaCandidateUsersAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CANDIDATE_USERS)
.namespace(CAMUNDA_NS)
.build();
camundaDueDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DUE_DATE)
.namespace(CAMUNDA_NS)
.build();
camundaFollowUpDateAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FOLLOW_UP_DATE)
.namespace(CAMUNDA_NS)
.build();
camundaFormKeyAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_FORM_KEY)
.namespace(CAMUNDA_NS)
.build(); | camundaPriorityAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_PRIORITY)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
planningTableCollection = sequenceBuilder.elementCollection(PlanningTable.class)
.build();
planningTableChild = sequenceBuilder.element(PlanningTable.class)
.minOccurs(0)
.maxOccurs(1)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\HumanTaskImpl.java | 1 |
请完成以下Java代码 | public static synchronized ReladomoConnectionManager getInstance() {
if (instance == null) {
instance = new ReladomoConnectionManager();
}
return instance;
}
private ReladomoConnectionManager() {
this.createConnectionManager();
}
private XAConnectionManager createConnectionManager() {
xaConnectionManager = new XAConnectionManager();
xaConnectionManager.setDriverClassName("org.h2.Driver");
xaConnectionManager.setJdbcConnectionString("jdbc:h2:mem:" + databaseName);
xaConnectionManager.setJdbcUser("sa");
xaConnectionManager.setJdbcPassword("");
xaConnectionManager.setPoolName("My Connection Pool");
xaConnectionManager.setInitialSize(1);
xaConnectionManager.setPoolSize(10);
xaConnectionManager.initialisePool();
return xaConnectionManager;
}
@Override
public BulkLoader createBulkLoader() throws BulkLoaderException {
return null;
}
@Override
public Connection getConnection() {
return xaConnectionManager.getConnection();
} | @Override
public DatabaseType getDatabaseType() {
return H2DatabaseType.getInstance();
}
@Override
public TimeZone getDatabaseTimeZone() {
return TimeZone.getDefault();
}
@Override
public String getDatabaseIdentifier() {
return databaseName;
}
public void createTables() throws Exception {
Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI());
try (Connection conn = xaConnectionManager.getConnection(); Stream<Path> list = Files.list(ddlPath);) {
list.forEach(path -> {
try {
RunScript.execute(conn, Files.newBufferedReader(path));
} catch (SQLException | IOException exc) {
exc.printStackTrace();
}
});
}
}
} | repos\tutorials-master\libraries-data-db-2\src\main\java\com\baeldung\libraries\reladomo\ReladomoConnectionManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static final class ExternalJobRestCondition extends AnyNestedCondition {
ExternalJobRestCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(ProcessEngine.class)
private static final class ProcessEngineBeanCondition {
}
@ConditionalOnBean(CmmnEngine.class)
private static final class CmmnEngineBeanCondition {
}
}
}
@Bean
public ContentTypeResolver contentTypeResolver() {
ContentTypeResolver resolver = new DefaultContentTypeResolver();
return resolver;
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(AppRestUrls.class)
@ConditionalOnBean(AppEngine.class)
public static class AppEngineRestApiConfiguration extends BaseRestApiConfiguration {
@Bean
public ServletRegistrationBean appServlet(FlowableAppProperties properties) {
return registerServlet(properties.getServlet(), AppEngineRestConfiguration.class);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CmmnRestUrls.class)
@ConditionalOnBean(CmmnEngine.class)
public static class CmmnEngineRestApiConfiguration extends BaseRestApiConfiguration {
@Bean
public ServletRegistrationBean cmmnServlet(FlowableCmmnProperties properties) {
return registerServlet(properties.getServlet(), CmmnEngineRestConfiguration.class);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(DmnRestUrls.class)
@ConditionalOnBean(DmnEngine.class)
public static class DmnEngineRestApiConfiguration extends BaseRestApiConfiguration {
@Bean
public ServletRegistrationBean dmnServlet(FlowableDmnProperties properties) {
return registerServlet(properties.getServlet(), DmnEngineRestConfiguration.class); | }
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(EventRestUrls.class)
@ConditionalOnBean(EventRegistryEngine.class)
public static class EventRegistryRestApiConfiguration extends BaseRestApiConfiguration {
@Bean
public ServletRegistrationBean eventRegistryServlet(FlowableEventRegistryProperties properties) {
return registerServlet(properties.getServlet(), EventRegistryRestConfiguration.class);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(IdmRestResponseFactory.class)
@ConditionalOnBean(IdmEngine.class)
public static class IdmEngineRestApiConfiguration extends BaseRestApiConfiguration {
@Bean
public ServletRegistrationBean idmServlet(FlowableIdmProperties properties) {
return registerServlet(properties.getServlet(), IdmEngineRestConfiguration.class);
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\RestApiAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MainApplication {
private static final Logger log = LoggerFactory.getLogger(MainApplication.class);
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Autowired
BookRepository bookRepository;
// Run this if app.db.init.enabled = true
@Bean
@ConditionalOnProperty(prefix = "app", name = "db.init.enabled", havingValue = "true")
public CommandLineRunner demoCommandLineRunner() {
return args -> {
System.out.println("Running.....");
Book b1 = new Book("Book A",
BigDecimal.valueOf(9.99),
LocalDate.of(2023, 8, 31));
Book b2 = new Book("Book B", | BigDecimal.valueOf(19.99),
LocalDate.of(2023, 7, 31));
Book b3 = new Book("Book C",
BigDecimal.valueOf(29.99),
LocalDate.of(2023, 6, 10));
Book b4 = new Book("Book D",
BigDecimal.valueOf(39.99),
LocalDate.of(2023, 5, 5));
bookRepository.saveAll(List.of(b1, b2, b3, b4));
};
}
} | repos\spring-boot-master\spring-data-jpa-postgresql\src\main\java\com\mkyong\MainApplication.java | 2 |
请完成以下Java代码 | public static HUReservation ofEntries(@NonNull final Collection<HUReservationEntry> entries)
{
return new HUReservation(entries);
}
private static HUReservationDocRef extractSingleDocumentRefOrFail(final Collection<HUReservationEntry> entries)
{
//noinspection OptionalGetWithoutIsPresent
return entries
.stream()
.map(HUReservationEntry::getDocumentRef)
.distinct()
.reduce((documentRef1, documentRef2) -> {
throw new AdempiereException("Entries shall be for a single document reference: " + entries);
})
.get();
}
@Nullable
private static BPartnerId extractSingleCustomerIdOrNull(final Collection<HUReservationEntry> entries)
{
final ImmutableSet<BPartnerId> customerIds = entries
.stream()
.map(HUReservationEntry::getCustomerId)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
return customerIds.size() == 1 ? customerIds.iterator().next() : null;
} | private static Quantity computeReservedQtySum(final Collection<HUReservationEntry> entries)
{
//noinspection OptionalGetWithoutIsPresent
return entries
.stream()
.map(HUReservationEntry::getQtyReserved)
.reduce(Quantity::add)
.get();
}
public ImmutableSet<HuId> getVhuIds()
{
return entriesByVHUId.keySet();
}
public Quantity getReservedQtyByVhuId(@NonNull final HuId vhuId)
{
final HUReservationEntry entry = entriesByVHUId.get(vhuId);
if (entry == null)
{
throw new AdempiereException("@NotFound@ @VHU_ID@");
}
return entry.getQtyReserved();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservation.java | 1 |
请完成以下Java代码 | private void updateBPartnerAndContactFromRecord(@NonNull final Object record)
{
final BPartnerId bpartnerId = extractBPartnerId(record);
if (bpartnerId != null)
{
bpartner(bpartnerId);
}
final UserId bpartnerContactId = extractBPartnerContactId(record);
if (bpartnerContactId != null)
{
bpartnerContact(bpartnerContactId);
}
}
private BPartnerId extractBPartnerId(final Object record)
{
final Object bpartnerIdObj = InterfaceWrapperHelper.getValueOrNull(record, "C_BPartner_ID");
if (!(bpartnerIdObj instanceof Integer))
{
return null;
}
final int bpartnerRepoId = (Integer)bpartnerIdObj;
return BPartnerId.ofRepoIdOrNull(bpartnerRepoId);
}
private UserId extractBPartnerContactId(final Object record)
{
final Integer userIdObj = InterfaceWrapperHelper.getValueOrNull(record, "AD_User_ID");
if (!(userIdObj instanceof Integer))
{ | return null;
}
final int userRepoId = userIdObj.intValue();
return UserId.ofRepoIdOrNull(userRepoId);
}
private Object getRecord()
{
return _record;
}
public MailTextBuilder customVariable(@NonNull final String name, @Nullable final String value)
{
return customVariable(name, TranslatableStrings.anyLanguage(value));
}
public MailTextBuilder customVariable(@NonNull final String name, @NonNull final ITranslatableString value)
{
_customVariables.put(name, value);
invalidateCache();
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTextBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class PayScheduleConverter
{
public static PaySchedule fromRecord(@NonNull final I_C_PaySchedule record)
{
return PaySchedule.builder()
.id(extractId(record))
.percentage(Percent.of(record.getPercentage()))
.discount(Percent.of(record.getDiscount()))
.netDay(extractNetDay(record))
.netDays(record.getNetDays())
.graceDays(record.getGraceDays())
.discountDays(record.getDiscountDays())
.build();
}
@NonNull
public static PayScheduleId extractId(final @NonNull I_C_PaySchedule record)
{
return PayScheduleId.ofRepoId(record.getC_PaySchedule_ID());
}
@NonNull
public static PaymentTermId extractPaymentTermId(final @NonNull I_C_PaySchedule record)
{
return PaymentTermId.ofRepoId(record.getC_PaymentTerm_ID());
}
private static DayOfWeek extractNetDay(@NonNull final I_C_PaySchedule record)
{
final String netDayStr = StringUtils.trimBlankToNull(record.getNetDay());
if (netDayStr == null)
{
return null;
}
switch (netDayStr) | {
case X_C_PaySchedule.NETDAY_Monday:
return DayOfWeek.MONDAY;
case X_C_PaySchedule.NETDAY_Tuesday:
return DayOfWeek.TUESDAY;
case X_C_PaySchedule.NETDAY_Wednesday:
return DayOfWeek.WEDNESDAY;
case X_C_PaySchedule.NETDAY_Thursday:
return DayOfWeek.THURSDAY;
case X_C_PaySchedule.NETDAY_Friday:
return DayOfWeek.FRIDAY;
case X_C_PaySchedule.NETDAY_Saturday:
return DayOfWeek.SATURDAY;
case X_C_PaySchedule.NETDAY_Sunday:
return DayOfWeek.SUNDAY;
default:
throw new AdempiereException("Unknown net day: " + netDayStr);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\paymentterm\repository\impl\PayScheduleConverter.java | 2 |
请完成以下Java代码 | public int compareTo(@NonNull final Amount other)
{
assertSameCurrency(this, other);
return getAsBigDecimal().compareTo(other.getAsBigDecimal());
}
public boolean isEqualByComparingTo(@Nullable final Amount other)
{
if (other == null)
{
return false;
}
return other.currencyCode.equals(currencyCode)
&& other.value.compareTo(value) == 0;
}
public boolean valueComparingEqualsTo(@NonNull final BigDecimal other)
{
return getAsBigDecimal().compareTo(other) == 0;
}
public Amount min(@NonNull final Amount other)
{
return compareTo(other) <= 0 ? this : other;
}
public int signum()
{
return getAsBigDecimal().signum();
}
public boolean isZero()
{
return signum() == 0;
}
public Amount negate()
{
return isZero()
? this
: new Amount(value.negate(), currencyCode);
}
public Amount negateIf(final boolean condition)
{
return condition ? negate() : this;
}
public Amount negateIfNot(final boolean condition)
{
return !condition ? negate() : this;
}
public Amount add(@NonNull final Amount amtToAdd)
{
assertSameCurrency(this, amtToAdd);
if (amtToAdd.isZero())
{
return this;
}
else if (isZero())
{
return amtToAdd;
}
else
{
return new Amount(value.add(amtToAdd.value), currencyCode);
}
}
public Amount subtract(@NonNull final Amount amtToSubtract)
{
assertSameCurrency(this, amtToSubtract); | if (amtToSubtract.isZero())
{
return this;
}
else
{
return new Amount(value.subtract(amtToSubtract.value), currencyCode);
}
}
public Amount multiply(@NonNull final Percent percent, @NonNull final CurrencyPrecision precision)
{
final BigDecimal newValue = percent.computePercentageOf(value, precision.toInt(), precision.getRoundingMode());
return !newValue.equals(value)
? new Amount(newValue, currencyCode)
: this;
}
public Amount abs()
{
return value.signum() < 0
? new Amount(value.abs(), currencyCode)
: this;
}
public Money toMoney(@NonNull final Function<CurrencyCode, CurrencyId> currencyIdMapper)
{
return Money.of(value, currencyIdMapper.apply(currencyCode));
}
public static boolean equals(@Nullable final Amount a1, @Nullable final Amount a2) {return Objects.equals(a1, a2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\Amount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FilteringController {
@GetMapping("/filtering") //field2
@JsonView(Views.Public.class)
public String filtering() {
// SomeBean someBean = new SomeBean("value1","value2", "value3");
var someBean = new SomeBean("value1","value2", "value3");
// MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(someBean);
// SimpleBeanPropertyFilter filter =
// SimpleBeanPropertyFilter.filterOutAllExcept("field1","field3");
var filter = SimpleBeanPropertyFilter.filterOutAllExcept("field1","field3");
// FilterProvider filters =
// new SimpleFilterProvider().addFilter("SomeBeanFilter", filter );
var filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
var jsonMapper = JsonMapper.builder().build();
// mappingJacksonValue.setFilters(filters );
// return mappingJacksonValue
return jsonMapper.writer(filters).writeValueAsString(someBean); | }
@GetMapping("/filtering-list") //field2, field3
public String filteringList() {
List<SomeBean> list = Arrays.asList(new SomeBean("value1","value2", "value3"),
new SomeBean("value4","value5", "value6"));
// MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(list);
// SimpleBeanPropertyFilter filter =
// SimpleBeanPropertyFilter.filterOutAllExcept("field2","field3");
var filter = SimpleBeanPropertyFilter.filterOutAllExcept("field2", "field3");
// FilterProvider filters =
// new SimpleFilterProvider().addFilter("SomeBeanFilter", filter );
var filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);
// mappingJacksonValue.setFilters(filters );
var jsonMapper = JsonMapper.builder().build();
// return mappingJacksonValue;
return jsonMapper.writer(filters).writeValueAsString(list);
}
} | repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\filtering\FilteringController.java | 2 |
请完成以下Java代码 | public class Address {
private String street;
private String postalcode;
private String county;
public String getStreet() {
return street;
}
public Address setStreet(String street) {
this.street = street;
return this;
}
public String getPostalcode() { | return postalcode;
}
public Address setPostalcode(String postalcode) {
this.postalcode = postalcode;
return this;
}
public String getCounty() {
return county;
}
public Address setCounty(String county) {
this.county = county;
return this;
}
} | repos\tutorials-master\mapstruct\src\main\java\com\baeldung\entity\Address.java | 1 |
请完成以下Spring Boot application配置 | #
# Copyright 2015-2023 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND | , either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
logging.level.root=WARN
logging.level.sample.mybatis.groovy.mapper=TRACE | repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-groovy\src\main\resources\application.properties | 2 |
请完成以下Java代码 | private void showHideDateField()
{
final boolean showLoginDate = isShowLoginDate();
dateLabel.setVisible(showLoginDate);
dateField.setVisible(showLoginDate);
}
private boolean isShowLoginDate()
{
final Properties ctx = getCtx();
// Make sure AD_Client_ID was not set
if (Check.isEmpty(Env.getContext(ctx, Env.CTXNAME_AD_Client_ID), true))
{
return false;
}
final boolean allowLoginDateOverride = m_login.isAllowLoginDateOverride();
if (allowLoginDateOverride)
{
return true;
}
final ClientId adClientId = m_login.getCtx().getClientId();
final boolean dateAutoupdate = sysConfigBL.getBooleanValue("LOGINDATE_AUTOUPDATE", false, adClientId.getRepoId());
if (dateAutoupdate)
{
return false;
}
return true;
}
private boolean disposed = false; | @Override
public void dispose()
{
super.dispose();
if (disposed)
{
// NOTE: for some reason this method is called twice on login, so we introduced disposed flag to prevent running the code twice
return;
}
Env.clearWinContext(getCtx(), m_WindowNo);
disposed = true;
}
} // ALogin | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ALogin.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeSalaryHandler {
@Autowired
private Function<Employee, Employee> employeeSalaryFunction;
@Autowired
private FunctionCatalog functionCatalog;
@FunctionName("calculateSalary")
public HttpResponseMessage calculateSalary(
@HttpTrigger(
name="http",
methods = HttpMethod.POST,
authLevel = AuthorizationLevel.ANONYMOUS)HttpRequestMessage<Optional<Employee>> employeeHttpRequestMessage,
ExecutionContext executionContext
) {
Employee employeeRequest = employeeHttpRequestMessage.getBody().get();
executionContext.getLogger().info("Salary of " + employeeRequest.getName() + " is:" + employeeRequest.getSalary());
Employee employee = employeeSalaryFunction.apply(employeeRequest);
executionContext.getLogger().info("Final salary of " + employee.getName() + " is:" + employee.getSalary());
return employeeHttpRequestMessage.createResponseBuilder(HttpStatus.OK)
.body(employee) | .build();
}
@FunctionName("calculateSalaryWithSCF")
public HttpResponseMessage calculateSalaryWithSCF(
@HttpTrigger(
name="http",
methods = HttpMethod.POST,
authLevel = AuthorizationLevel.ANONYMOUS)HttpRequestMessage<Optional<Employee>> employeeHttpRequestMessage,
ExecutionContext executionContext
) {
Employee employeeRequest = employeeHttpRequestMessage.getBody().get();
executionContext.getLogger().info("Salary of " + employeeRequest.getName() + " is:" + employeeRequest.getSalary());
EmployeeSalaryFunctionWrapper employeeSalaryFunctionWrapper = new EmployeeSalaryFunctionWrapper(functionCatalog);
Function<Employee, Employee> cityBasedSalaryFunction = employeeSalaryFunctionWrapper.getCityBasedSalaryFunction(employeeRequest);
executionContext.getLogger().info("The class of the cityBasedSalaryFunction:" + cityBasedSalaryFunction.getClass());
Employee employee = cityBasedSalaryFunction.apply(employeeRequest);
executionContext.getLogger().info("Final salary of " + employee.getName() + " is:" + employee.getSalary());
return employeeHttpRequestMessage.createResponseBuilder(HttpStatus.OK)
.body(employee)
.build();
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-functions-azure\src\main\java\com\baeldung\azure\functions\EmployeeSalaryHandler.java | 2 |
请完成以下Java代码 | public static int toRepoId(@Nullable final HuId huId)
{
return huId != null ? huId.getRepoId() : -1;
}
public static Set<HuId> ofRepoIds(@NonNull final Collection<Integer> repoIds)
{
return repoIds.stream().map(HuId::ofRepoId).collect(ImmutableSet.toImmutableSet());
}
public static Set<Integer> toRepoIds(@NonNull final Collection<HuId> huIds)
{
return huIds.stream().map(HuId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
public static Set<HuId> fromRepoIds(@Nullable final Collection<Integer> huRepoIds)
{
if (huRepoIds == null || huRepoIds.isEmpty())
{
return ImmutableSet.of();
}
return huRepoIds.stream().map(HuId::ofRepoIdOrNull).filter(Objects::nonNull).collect(ImmutableSet.toImmutableSet());
}
public static HuId ofHUValue(@NonNull final String huValue)
{
try
{
return ofRepoId(Integer.parseInt(huValue));
}
catch (final Exception ex)
{
final AdempiereException metasfreshException = new AdempiereException("Invalid HUValue `" + huValue + "`. It cannot be converted to M_HU_ID.");
metasfreshException.addSuppressed(ex);
throw metasfreshException;
}
} | public static HuId ofHUValueOrNull(@Nullable final String huValue)
{
final String huValueNorm = StringUtils.trimBlankToNull(huValue);
if (huValueNorm == null) {return null;}
try
{
return ofRepoIdOrNull(NumberUtils.asIntOrZero(huValueNorm));
}
catch (final Exception ex)
{
return null;
}
}
public String toHUValue() {return String.valueOf(repoId);}
int repoId;
private HuId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final HuId o1, @Nullable final HuId o2)
{
return Objects.equals(o1, o2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuId.java | 1 |
请完成以下Java代码 | public void setExternalSystem_Service(final de.metas.externalsystem.model.I_ExternalSystem_Service ExternalSystem_Service)
{
set_ValueFromPO(COLUMNNAME_ExternalSystem_Service_ID, de.metas.externalsystem.model.I_ExternalSystem_Service.class, ExternalSystem_Service);
}
@Override
public void setExternalSystem_Service_ID (final int ExternalSystem_Service_ID)
{
if (ExternalSystem_Service_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Service_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Service_ID, ExternalSystem_Service_ID);
}
@Override
public int getExternalSystem_Service_ID()
{ | return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_ID);
}
@Override
public void setExternalSystem_Service_Instance_ID (final int ExternalSystem_Service_Instance_ID)
{
if (ExternalSystem_Service_Instance_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_Instance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_Instance_ID, ExternalSystem_Service_Instance_ID);
}
@Override
public int getExternalSystem_Service_Instance_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_Instance_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Service_Instance.java | 1 |
请完成以下Java代码 | private void initStartTimeAsDate() {
try {
startTimeAsDate = HistoryCleanupHelper.parseTimeConfiguration(startTime);
} catch (ParseException e) {
throw LOG.invalidPropertyValue("startTime", startTime);
}
}
private void initEndTimeAsDate() {
try {
endTimeAsDate = HistoryCleanupHelper.parseTimeConfiguration(endTime);
} catch (ParseException e) {
throw LOG.invalidPropertyValue("endTime", endTime);
}
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
initStartTimeAsDate();
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
initEndTimeAsDate();
}
public Date getStartTimeAsDate() {
return startTimeAsDate; | }
public Date getEndTimeAsDate() {
return endTimeAsDate;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
BatchWindowConfiguration that = (BatchWindowConfiguration) o;
if (startTime != null ? !startTime.equals(that.startTime) : that.startTime != null)
return false;
return endTime != null ? endTime.equals(that.endTime) : that.endTime == null;
}
@Override
public int hashCode() {
int result = startTime != null ? startTime.hashCode() : 0;
result = 31 * result + (endTime != null ? endTime.hashCode() : 0);
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\BatchWindowConfiguration.java | 1 |
请完成以下Java代码 | public class POSProductsSearchResult
{
public static final POSProductsSearchResult EMPTY = new POSProductsSearchResult(ImmutableList.of(), false);
@NonNull private final ImmutableList<POSProduct> products;
@Getter private final boolean isBarcodeMatched;
private POSProductsSearchResult(
@NonNull final ImmutableList<POSProduct> products,
final boolean isBarcodeMatched)
{
this.products = products;
this.isBarcodeMatched = isBarcodeMatched;
}
public static POSProductsSearchResult ofList(@NonNull final List<POSProduct> products) | {
return !products.isEmpty()
? new POSProductsSearchResult(ImmutableList.copyOf(products), false)
: EMPTY;
}
public static POSProductsSearchResult ofBarcodeMatchedProduct(@NonNull final POSProduct product)
{
return new POSProductsSearchResult(ImmutableList.of(product), true);
}
public Stream<POSProduct> stream() {return products.stream();}
public List<POSProduct> toList() {return products;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsSearchResult.java | 1 |
请完成以下Java代码 | public void setJobRetries(RetriesDto dto) {
try {
SetJobRetriesBuilder builder = engine.getManagementService()
.setJobRetries(dto.getRetries())
.jobDefinitionId(jobDefinitionId);
if (dto.isDueDateSet()) {
builder.dueDate(dto.getDueDate());
}
builder.execute();
} catch (AuthorizationException e) {
throw e;
} catch (ProcessEngineException e) {
throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
@Override
public void setJobPriority(JobDefinitionPriorityDto dto) {
try {
ManagementService managementService = engine.getManagementService();
if (dto.getPriority() != null) {
managementService.setOverridingJobPriorityForJobDefinition(jobDefinitionId, dto.getPriority(), dto.isIncludeJobs());
}
else {
if (dto.isIncludeJobs()) {
throw new InvalidRequestException(Status.BAD_REQUEST,
"Cannot reset priority for job definition " + jobDefinitionId + " with includeJobs=true"); | }
managementService.clearOverridingJobPriorityForJobDefinition(jobDefinitionId);
}
} catch (AuthorizationException e) {
throw e;
} catch (NotFoundException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\management\JobDefinitionResourceImpl.java | 1 |
请完成以下Java代码 | public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
} | /** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Desktop.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean verify(String arg0, String arg1) {
return true;
}
}
public static ClientKeyStore loadClientKeyStore(String keyStorePath, String keyStorePass, String privateKeyPass){
try{
return loadClientKeyStore(new FileInputStream(keyStorePath), keyStorePass, privateKeyPass);
}catch(Exception e){
logger.error("loadClientKeyFactory fail : "+e.getMessage(), e);
return null;
}
}
public static ClientKeyStore loadClientKeyStore(InputStream keyStoreStream, String keyStorePass, String privateKeyPass){
try{
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreStream, keyStorePass.toCharArray());
kmf.init(ks, privateKeyPass.toCharArray());
return new ClientKeyStore(kmf);
}catch(Exception e){
logger.error("loadClientKeyFactory fail : "+e.getMessage(), e);
return null;
}
} | public static TrustKeyStore loadTrustKeyStore(String keyStorePath, String keyStorePass){
try{
return loadTrustKeyStore(new FileInputStream(keyStorePath), keyStorePass);
}catch(Exception e){
logger.error("loadTrustCertFactory fail : "+e.getMessage(), e);
return null;
}
}
public static TrustKeyStore loadTrustKeyStore(InputStream keyStoreStream, String keyStorePass){
try{
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreStream, keyStorePass.toCharArray());
tmf.init(ks);
return new TrustKeyStore(tmf);
}catch(Exception e){
logger.error("loadTrustCertFactory fail : "+e.getMessage(), e);
return null;
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\utils\httpclient\SimpleHttpUtils.java | 2 |
请完成以下Java代码 | public void postProcessApplicationDeploy(ProcessApplicationInterface processApplication) {
ProcessApplicationInterface rawPa = processApplication.getRawObject();
if (rawPa instanceof AbstractProcessApplication) {
initializeVariableSerializers((AbstractProcessApplication) rawPa);
}
else {
LOG.logNoDataFormatsInitiailized("process application data formats", "process application is not a sub class of " + AbstractProcessApplication.class.getName());
}
}
protected void initializeVariableSerializers(AbstractProcessApplication abstractProcessApplication) {
VariableSerializers paVariableSerializers = abstractProcessApplication.getVariableSerializers();
if (paVariableSerializers == null) {
paVariableSerializers = new DefaultVariableSerializers();
abstractProcessApplication.setVariableSerializers(paVariableSerializers);
}
for (TypedValueSerializer<?> serializer : lookupSpinSerializers(abstractProcessApplication.getProcessApplicationClassloader())) {
paVariableSerializers.addSerializer(serializer);
}
}
protected List<TypedValueSerializer<?>> lookupSpinSerializers(ClassLoader classLoader) { | DataFormats paDataFormats = new DataFormats();
paDataFormats.registerDataFormats(classLoader);
// does not create PA-local serializers for native Spin values;
// this is still an open feature CAM-5246
return SpinVariableSerializers.createObjectValueSerializers(paDataFormats);
}
@Override
public void postProcessApplicationUndeploy(ProcessApplicationInterface processApplication) {
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinBpmPlatformPlugin.java | 1 |
请在Spring Boot框架中完成以下Java代码 | QueueChannel multipleofThreeChannel() {
return new QueueChannel();
}
@Bean
QueueChannel remainderIsOneChannel() {
return new QueueChannel();
}
@Bean
QueueChannel remainderIsTwoChannel() {
return new QueueChannel();
}
boolean isMultipleOfThree(Integer number) {
return number % 3 == 0;
}
boolean isRemainderOne(Integer number) {
return number % 3 == 1;
} | boolean isRemainderTwo(Integer number) {
return number % 3 == 2;
}
@Bean
public IntegrationFlow classify() {
return flow -> flow.split()
.<Integer> filter(this::isMultipleOfThree, notMultiple -> notMultiple
.discardFlow(oneflow -> oneflow
.<Integer> filter(this::isRemainderOne,
twoflow -> twoflow .discardChannel("remainderIsTwoChannel"))
.channel("remainderIsOneChannel")))
.channel("multipleofThreeChannel");
}
} | repos\tutorials-master\spring-integration\src\main\java\com\baeldung\subflows\discardflow\FilterExample.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Handler {
public Mono<ServerResponse> handleWithErrorReturn(ServerRequest request) {
return sayHello(request)
.onErrorReturn("Hello, Stranger")
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s));
}
public Mono<ServerResponse> handleWithErrorResumeAndDynamicFallback(ServerRequest request) {
return sayHello(request)
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s))
.onErrorResume(e -> (Mono.just("Hi, I looked around for your name but found: " + e.getMessage()))
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s)));
}
public Mono<ServerResponse> handleWithErrorResumeAndFallbackMethod(ServerRequest request) {
return sayHello(request)
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s))
.onErrorResume(e -> sayHelloFallback()
.flatMap(s -> ServerResponse.ok()
.contentType(MediaType.TEXT_PLAIN)
.bodyValue(s)));
}
public Mono<ServerResponse> handleWithErrorResumeAndCustomException(ServerRequest request) {
return ServerResponse.ok()
.body(sayHello(request)
.onErrorResume(e -> Mono.error(new NameRequiredException( | HttpStatus.BAD_REQUEST,
"please provide a name", e))), String.class);
}
public Mono<ServerResponse> handleWithGlobalErrorHandler(ServerRequest request) {
return ServerResponse.ok()
.body(sayHello(request), String.class);
}
private Mono<String> sayHello(ServerRequest request) {
try {
return Mono.just("Hello, " + request.queryParam("name").get());
} catch (Exception e) {
return Mono.error(e);
}
}
private Mono<String> sayHelloFallback() {
return Mono.just("Hello, Stranger");
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\errorhandling\Handler.java | 2 |
请完成以下Java代码 | public boolean processIt(final String processAction)
{
m_processMsg = null;
return Services.get(IDocumentBL.class).processIt(this, processAction);
}
@Override
public boolean reActivateIt()
{
log.info(toString());
// Before reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REACTIVATE);
if (m_processMsg != null)
return false;
setProcessed(false);
setDocAction(DOCACTION_Complete);
// Note:
// setting and saving the doc status here, because the model validator updates an invoice candidate, which in
// term will make sure that this data entry is not completed
setDocStatus(DOCSTATUS_InProgress);
Check.assume(get_TrxName() != null, this + " has trxName!=null");
saveEx();
// After reActivate
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REACTIVATE);
if (m_processMsg != null)
return false;
return true;
} // reActivateIt
@Override
public boolean rejectIt()
{
return true;
}
@Override
public boolean reverseAccrualIt()
{
log.info(toString());
// Before reverseAccrual
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSEACCRUAL);
if (m_processMsg != null)
return false;
// After reverseAccrual
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSEACCRUAL);
if (m_processMsg != null) | return false;
return true;
} // reverseAccrualIt
@Override
public boolean reverseCorrectIt()
{
log.info(toString());
// Before reverseCorrect
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT);
if (m_processMsg != null)
return false;
// After reverseCorrect
m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT);
if (m_processMsg != null)
return false;
return true;
}
/**
* Unlock Document.
*
* @return true if success
*/
@Override
public boolean unlockIt()
{
log.info(toString());
setProcessing(false);
return true;
} // unlockIt
@Override
public boolean voidIt()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateDataEntry.java | 1 |
请完成以下Java代码 | public class SimpleStatusAggregator implements StatusAggregator {
private static final List<String> DEFAULT_ORDER;
static final StatusAggregator INSTANCE;
static {
List<String> defaultOrder = new ArrayList<>();
defaultOrder.add(Status.DOWN.getCode());
defaultOrder.add(Status.OUT_OF_SERVICE.getCode());
defaultOrder.add(Status.UP.getCode());
defaultOrder.add(Status.UNKNOWN.getCode());
DEFAULT_ORDER = Collections.unmodifiableList(getUniformCodes(defaultOrder.stream()));
INSTANCE = new SimpleStatusAggregator();
}
private final List<String> order;
private final Comparator<Status> comparator = new StatusComparator();
public SimpleStatusAggregator() {
this.order = DEFAULT_ORDER;
}
public SimpleStatusAggregator(Status... order) {
this.order = ObjectUtils.isEmpty(order) ? DEFAULT_ORDER
: getUniformCodes(Arrays.stream(order).map(Status::getCode));
}
public SimpleStatusAggregator(String... order) {
this.order = ObjectUtils.isEmpty(order) ? DEFAULT_ORDER : getUniformCodes(Arrays.stream(order));
}
public SimpleStatusAggregator(List<String> order) {
this.order = CollectionUtils.isEmpty(order) ? DEFAULT_ORDER : getUniformCodes(order.stream());
}
@Override
public Status getAggregateStatus(Set<Status> statuses) {
return statuses.stream().filter(this::contains).min(this.comparator).orElse(Status.UNKNOWN);
}
private boolean contains(Status status) {
return this.order.contains(getUniformCode(status.getCode()));
}
private static List<String> getUniformCodes(Stream<String> codes) { | return codes.map(SimpleStatusAggregator::getUniformCode).toList();
}
@Contract("!null -> !null")
private static @Nullable String getUniformCode(@Nullable String code) {
if (code == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < code.length(); i++) {
char ch = code.charAt(i);
if (Character.isAlphabetic(ch) || Character.isDigit(ch)) {
builder.append(Character.toLowerCase(ch));
}
}
return builder.toString();
}
/**
* {@link Comparator} used to order {@link Status}.
*/
private final class StatusComparator implements Comparator<Status> {
@Override
public int compare(Status s1, Status s2) {
List<String> order = SimpleStatusAggregator.this.order;
int i1 = order.indexOf(getUniformCode(s1.getCode()));
int i2 = order.indexOf(getUniformCode(s2.getCode()));
return (i1 < i2) ? -1 : (i1 != i2) ? 1 : s1.getCode().compareTo(s2.getCode());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\SimpleStatusAggregator.java | 1 |
请完成以下Java代码 | public String getClientSoftwareKennung() {
return clientSoftwareKennung;
}
/**
* Sets the value of the clientSoftwareKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSoftwareKennung(String value) {
this.clientSoftwareKennung = value;
}
/**
* Gets the value of the retourenavisAnkuendigungType property.
*
* @return
* possible object is
* {@link RetourenavisAnkuendigungType }
*
*/
public RetourenavisAnkuendigungType getRetourenavisAnkuendigungType() { | return retourenavisAnkuendigungType;
}
/**
* Sets the value of the retourenavisAnkuendigungType property.
*
* @param value
* allowed object is
* {@link RetourenavisAnkuendigungType }
*
*/
public void setRetourenavisAnkuendigungType(RetourenavisAnkuendigungType value) {
this.retourenavisAnkuendigungType = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigen.java | 1 |
请完成以下Java代码 | protected String extractColumnName(final I_AD_ColumnCallout cc)
{
return cc.getColumnName();
}
@Override
// no cache
public List<I_AD_ColumnCallout> retrieveAllColumnCallouts(final Properties ctx, final int adColumnId)
{
return Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_ColumnCallout.class, ctx, ITrx.TRXNAME_None)
.addEqualsFilter(I_AD_ColumnCallout.COLUMNNAME_AD_Column_ID, adColumnId)
//
.orderBy()
.addColumn(I_AD_ColumnCallout.COLUMNNAME_SeqNo)
.addColumn(I_AD_ColumnCallout.COLUMNNAME_AD_ColumnCallout_ID)
.endOrderBy()
//
.create()
.list(I_AD_ColumnCallout.class);
}
@Override | public int retrieveColumnCalloutLastSeqNo(final Properties ctx, final int adColumnId)
{
final Integer lastSeqNo = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_ColumnCallout.class, ctx, ITrx.TRXNAME_None)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_ColumnCallout.COLUMNNAME_AD_Column_ID, adColumnId)
//
.create()
.aggregate(I_AD_ColumnCallout.COLUMNNAME_SeqNo, Aggregate.MAX, Integer.class);
if (lastSeqNo == null || lastSeqNo < 0)
{
return 0;
}
return lastSeqNo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\api\impl\ADColumnCalloutDAO.java | 1 |
请完成以下Java代码 | public Long countByTenantId(TenantId tenantId) {
return customerRepository.countByTenantId(tenantId.getId());
}
@Override
public Customer findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(customerRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public Customer findByTenantIdAndName(UUID tenantId, String name) {
return findCustomerByTenantIdAndTitle(tenantId, name).orElse(null);
}
@Override
public PageData<Customer> findByTenantId(UUID tenantId, PageLink pageLink) {
return findCustomersByTenantId(tenantId, pageLink);
}
@Override
public CustomerId getExternalIdByInternal(CustomerId internalId) {
return Optional.ofNullable(customerRepository.getExternalIdById(internalId.getId()))
.map(CustomerId::new).orElse(null);
}
@Override
public PageData<Customer> findCustomersWithTheSameTitle(PageLink pageLink) {
return DaoUtil.toPageData(
customerRepository.findCustomersWithTheSameTitle(DaoUtil.toPageable(pageLink))
);
}
@Override
public List<Customer> findCustomersByTenantIdAndIds(UUID tenantId, List<UUID> customerIds) {
return DaoUtil.convertDataList(customerRepository.findCustomersByTenantIdAndIdIn(tenantId, customerIds));
}
@Override
public PageData<Customer> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink); | }
@Override
public List<CustomerFields> findNextBatch(UUID id, int batchSize) {
return customerRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) {
return customerRepository.findEntityInfosByNamePrefix(tenantId.getId(), name);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\customer\JpaCustomerDao.java | 1 |
请完成以下Java代码 | public static class Skip {
/**
* Whether to skip in tests.
*/
private boolean inTests = true;
public boolean isInTests() {
return this.inTests;
}
public void setInTests(boolean inTests) {
this.inTests = inTests;
}
}
/**
* Readiness properties.
*/
public static class Readiness {
/**
* Wait strategy to use.
*/
private Wait wait = Wait.ALWAYS;
/**
* Timeout of the readiness checks.
*/
private Duration timeout = Duration.ofMinutes(2);
/**
* TCP properties.
*/
private final Tcp tcp = new Tcp();
public Wait getWait() {
return this.wait;
}
public void setWait(Wait wait) {
this.wait = wait;
}
public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public Tcp getTcp() {
return this.tcp;
}
/**
* Readiness wait strategies.
*/
public enum Wait {
/**
* Always perform readiness checks.
*/
ALWAYS, | /**
* Never perform readiness checks.
*/
NEVER,
/**
* Only perform readiness checks if docker was started with lifecycle
* management.
*/
ONLY_IF_STARTED
}
/**
* TCP properties.
*/
public static class Tcp {
/**
* Timeout for connections.
*/
private Duration connectTimeout = Duration.ofMillis(200);
/**
* Timeout for reads.
*/
private Duration readTimeout = Duration.ofMillis(200);
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\DockerComposeProperties.java | 1 |
请完成以下Java代码 | private int waitForProcess(Process process) {
try {
return process.waitFor();
}
catch (InterruptedException ex) {
throw new IllegalStateException("Interrupted waiting for %s".formatted(process));
}
}
/**
* Thread used to read stream input from the process.
*/
private static class ReaderThread extends Thread {
private final InputStream source;
private final @Nullable Consumer<String> outputConsumer;
private final StringBuilder output = new StringBuilder();
private final CountDownLatch latch = new CountDownLatch(1);
ReaderThread(InputStream source, String name, @Nullable Consumer<String> outputConsumer) {
this.source = source;
this.outputConsumer = outputConsumer;
setName("OutputReader-" + name);
setDaemon(true);
start();
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(this.source, StandardCharsets.UTF_8))) { | String line = reader.readLine();
while (line != null) {
this.output.append(line);
this.output.append("\n");
if (this.outputConsumer != null) {
this.outputConsumer.accept(line);
}
line = reader.readLine();
}
this.latch.countDown();
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to read process stream", ex);
}
}
@Override
public String toString() {
try {
this.latch.await();
return this.output.toString();
}
catch (InterruptedException ex) {
return "";
}
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\ProcessRunner.java | 1 |
请完成以下Java代码 | private Map<HuId, Optional<HUReservationEntry>> retrieveEntriesByVHUId(@NonNull final Collection<HuId> vhuIds)
{
if (vhuIds.isEmpty())
{
return ImmutableMap.of();
} // shall not happen
final HashMap<HuId, Optional<HUReservationEntry>> result = new HashMap<>(vhuIds.size());
vhuIds.forEach(huId -> result.put(huId, Optional.empty()));
queryBL.createQueryBuilder(I_M_HU_Reservation.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuIds)
.create()
.stream()
.map(HUReservationRepository::toHUReservationEntry)
.forEach(entry -> result.put(entry.getVhuId(), Optional.of(entry)));
return ImmutableMap.copyOf(result);
}
public Optional<OrderLineId> getOrderLineIdByReservedVhuId(@NonNull final HuId vhuId)
{
return getEntryByVhuId(vhuId)
.map(entry -> entry.getDocumentRef().getSalesOrderLineId());
}
private Optional<HUReservationEntry> getEntryByVhuId(@NonNull final HuId vhuId)
{
return entriesByVhuId.getOrLoad(vhuId, this::retrieveEntryByVhuId);
}
private Optional<HUReservationEntry> retrieveEntryByVhuId(@NonNull final HuId vhuId)
{
return queryBL.createQueryBuilder(I_M_HU_Reservation.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_HU_Reservation.COLUMN_VHU_ID, vhuId) // we have a UC constraint on VHU_ID
.create()
.firstOnlyOptional(I_M_HU_Reservation.class)
.map(HUReservationRepository::toHUReservationEntry);
}
private static HUReservationDocRef extractDocumentRef(@NonNull final I_M_HU_Reservation record)
{
return HUReservationDocRef.builder()
.salesOrderLineId(OrderLineId.ofRepoIdOrNull(record.getC_OrderLineSO_ID()))
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
.pickingJobStepId(PickingJobStepId.ofRepoIdOrNull(record.getM_Picking_Job_Step_ID()))
.ddOrderLineId(DDOrderLineId.ofRepoIdOrNull(record.getDD_OrderLine_ID()))
.build();
} | public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> onlyVHUIds)
{
if (from.size() == 1 && Objects.equals(from.iterator().next(), to))
{
return;
}
final List<I_M_HU_Reservation> records = retrieveRecordsByDocumentRef(from, onlyVHUIds);
if (records.isEmpty())
{
return;
}
for (final I_M_HU_Reservation record : records)
{
updateRecordFromDocumentRef(record, to);
saveRecord(record);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationRepository.java | 1 |
请完成以下Java代码 | protected static void fillExecutionTree(
ExecutionTree executionTree,
Map<String, List<ExecutionEntity>> parentMapping
) {
if (executionTree.getRoot() == null) {
throw new ActivitiException(
"Programmatic error: the list of passed executions in the argument of the method should contain the process instance execution"
);
}
// Now build the tree, top-down
LinkedList<ExecutionTreeNode> executionsToHandle = new LinkedList<ExecutionTreeNode>();
executionsToHandle.add(executionTree.getRoot());
while (!executionsToHandle.isEmpty()) {
ExecutionTreeNode parentNode = executionsToHandle.pop();
String parentId = parentNode.getExecutionEntity().getId();
if (parentMapping.containsKey(parentId)) {
List<ExecutionEntity> childExecutions = parentMapping.get(parentId); | List<ExecutionTreeNode> childNodes = new ArrayList<ExecutionTreeNode>(childExecutions.size());
for (ExecutionEntity childExecutionEntity : childExecutions) {
ExecutionTreeNode childNode = new ExecutionTreeNode(childExecutionEntity);
childNode.setParent(parentNode);
childNodes.add(childNode);
executionsToHandle.add(childNode);
}
parentNode.setChildren(childNodes);
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTreeUtil.java | 1 |
请完成以下Java代码 | private void findByPartialName() {
Author author1 = this.authorRepository.findByNameContainingIgnoreCase("sh lo").orElse(null);
Author author2 = this.authorRepository.findByNameContainingIgnoreCase("in kl").orElse(null);
System.out.printf("findByPartialName(): author1 = %s%n", author1);
System.out.printf("findByPartialName(): author2 = %s%n", author2);
}
private void findById() {
Author author1 = this.authorRepository.findById(1L).orElse(null);
Author author2 = this.authorRepository.findById(2L).orElse(null);
System.out.printf("findById(): author1 = %s%n", author1);
System.out.printf("findById(): author2 = %s%n", author2);
}
private void listAllAuthors() {
List<Author> authors = this.authorRepository.findAll();
for (Author author : authors) {
System.out.printf("listAllAuthors(): author = %s%n", author); | for (Book book : author.getBooks()) {
System.out.printf("\t%s%n", book);
}
}
}
private void insertAuthors() {
Author author1 = this.authorRepository.save(new Author(null, "Josh Long",
Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java"))));
Author author2 = this.authorRepository.save(
new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications"))));
System.out.printf("insertAuthors(): author1 = %s%n", author1);
System.out.printf("insertAuthors(): author2 = %s%n", author2);
}
} | repos\spring-data-examples-main\jdbc\graalvm-native\src\main\java\example\springdata\jdbc\graalvmnative\CLR.java | 1 |
请完成以下Java代码 | public class IntegrationGraphEndpoint {
private final IntegrationGraphServer graphServer;
/**
* Create a new {@code IntegrationGraphEndpoint} instance that exposes a graph
* containing all the Spring Integration components in the given
* {@link IntegrationGraphServer}.
* @param graphServer the integration graph server
*/
public IntegrationGraphEndpoint(IntegrationGraphServer graphServer) {
this.graphServer = graphServer;
}
@ReadOperation
public GraphDescriptor graph() {
return new GraphDescriptor(this.graphServer.getGraph());
}
@WriteOperation
public void rebuild() {
this.graphServer.rebuild();
}
/**
* Description of a {@link Graph}.
*/
public static class GraphDescriptor implements OperationResponseBody {
private final Map<String, Object> contentDescriptor; | private final Collection<IntegrationNode> nodes;
private final Collection<LinkNode> links;
GraphDescriptor(Graph graph) {
this.contentDescriptor = graph.contentDescriptor();
this.nodes = graph.nodes();
this.links = graph.links();
}
public Map<String, Object> getContentDescriptor() {
return this.contentDescriptor;
}
public Collection<IntegrationNode> getNodes() {
return this.nodes;
}
public Collection<LinkNode> getLinks() {
return this.links;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\actuate\endpoint\IntegrationGraphEndpoint.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (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 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_C_LandedCost.java | 1 |
请完成以下Java代码 | private DestinationTopic getNextDestinationTopic(List<DestinationTopic> destinationList, int index) {
return index != destinationList.size() - 1
? destinationList.get(index + 1)
: new DestinationTopic(destinationList.get(index).getDestinationName() + NO_OPS_SUFFIX,
destinationList.get(index), NO_OPS_SUFFIX, DestinationTopic.Type.NO_OPS);
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (Objects.equals(event.getApplicationContext(), this.applicationContext)) {
this.contextRefreshed = true;
}
}
/**
* Return true if the application context is refreshed.
* @return true if refreshed.
* @since 2.7.8
*/
public boolean isContextRefreshed() {
return this.contextRefreshed;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { | this.applicationContext = applicationContext;
}
public static class DestinationTopicHolder {
private final DestinationTopic sourceDestination;
private final DestinationTopic nextDestination;
DestinationTopicHolder(DestinationTopic sourceDestination, DestinationTopic nextDestination) {
this.sourceDestination = sourceDestination;
this.nextDestination = nextDestination;
}
protected DestinationTopic getNextDestination() {
return this.nextDestination;
}
protected DestinationTopic getSourceDestination() {
return this.sourceDestination;
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DefaultDestinationTopicResolver.java | 1 |
请完成以下Java代码 | protected void registerTransactionHandler(SetRemovalTimeBatchConfiguration configuration,
Map<Class<? extends DbEntity>, DbOperation> operations,
Integer chunkSize,
MessageEntity currentJob,
CommandContext commandContext) {
CommandExecutor newCommandExecutor = commandContext.getProcessEngineConfiguration().getCommandExecutorTxRequiresNew();
TransactionListener transactionResulthandler = createTransactionHandler(configuration, operations, chunkSize,
currentJob, newCommandExecutor);
commandContext.getTransactionContext().addTransactionListener(TransactionState.COMMITTED, transactionResulthandler);
}
protected int getUpdateChunkSize(SetRemovalTimeBatchConfiguration configuration, CommandContext commandContext) {
return configuration.getChunkSize() == null
? commandContext.getProcessEngineConfiguration().getRemovalTimeUpdateChunkSize()
: configuration.getChunkSize();
}
protected TransactionListener createTransactionHandler(SetRemovalTimeBatchConfiguration configuration,
Map<Class<? extends DbEntity>, DbOperation> operations,
Integer chunkSize,
MessageEntity currentJob,
CommandExecutor newCommandExecutor) {
return new ProcessSetRemovalTimeResultHandler(configuration, chunkSize, newCommandExecutor, this,
currentJob.getId(), operations);
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override
protected SetRemovalTimeBatchConfiguration createJobConfiguration(SetRemovalTimeBatchConfiguration configuration,
List<String> processInstanceIds) {
return new SetRemovalTimeBatchConfiguration(processInstanceIds)
.setRemovalTime(configuration.getRemovalTime()) | .setHasRemovalTime(configuration.hasRemovalTime())
.setHierarchical(configuration.isHierarchical())
.setUpdateInChunks(configuration.isUpdateInChunks())
.setChunkSize(configuration.getChunkSize());
}
@Override
protected SetRemovalTimeJsonConverter getJsonConverterInstance() {
return SetRemovalTimeJsonConverter.INSTANCE;
}
@Override
public int calculateInvocationsPerBatchJob(String batchType, SetRemovalTimeBatchConfiguration configuration) {
if (configuration.isUpdateInChunks()) {
return 1;
}
return super.calculateInvocationsPerBatchJob(batchType, configuration);
}
@Override
public String getType() {
return Batch.TYPE_PROCESS_SET_REMOVAL_TIME;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\ProcessSetRemovalTimeJobHandler.java | 1 |
请完成以下Java代码 | public void configure(Map<String, ?> configs, boolean isKey) {
super.configure(configs, isKey);
}
@Override
protected Serializer<?> configureDelegate(Map<String, ?> configs, boolean isKey, Serializer<?> delegate) {
delegate.configure(configs, isKey);
return delegate;
}
@Override
protected boolean isInstance(Object instance) {
return instance instanceof Serializer;
} | @Override
public byte[] serialize(String topic, Object data) {
throw new UnsupportedOperationException();
}
@SuppressWarnings({"unchecked", "NullAway"}) // Dataflow analysis limitation
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
if (data == null) {
return null;
}
return ((Serializer<Object>) findDelegate(topic)).serialize(topic, headers, data);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTopicSerializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserRoleId implements RepoIdAware
{
int repoId;
@JsonCreator
public static UserRoleId ofRepoId(final int repoId)
{
return new UserRoleId(repoId);
}
@Nullable
public static UserRoleId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new UserRoleId(repoId) : null;
}
public static int toRepoId(@Nullable final UserRoleId userRoleId) | {
return userRoleId != null ? userRoleId.getRepoId() : -1;
}
private UserRoleId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, I_C_User_Role.COLUMNNAME_C_User_Role_ID);
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\user\role\UserRoleId.java | 2 |
请完成以下Java代码 | public HistoricVariableInstanceQuery orderByCreationTime() {
orderBy(HistoricVariableInstanceQueryProperty.CREATE_TIME);
return this;
}
// getters and setters //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseActivityIds() {
return caseActivityIds;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public String getVariableName() {
return variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public QueryVariableValue getQueryVariableValue() {
return queryVariableValue; | }
public Boolean getVariableNamesIgnoreCase() {
return variableNamesIgnoreCase;
}
public Boolean getVariableValuesIgnoreCase() {
return variableValuesIgnoreCase;
}
@Override
public HistoricVariableInstanceQuery includeDeleted() {
includeDeleted = true;
return this;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public List<String> getVariableNameIn() {
return variableNameIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricVariableInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
final RequestId requestId = RequestId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
if (requestId == null)
{
return ProcessPreconditionsResolution.reject();
}
final I_R_Request request = requestBL.getById(requestId);
final ProjectId projectId = ProjectId.ofRepoIdOrNull(request.getC_Project_ID());
if (projectId != null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("project already created");
}
// TODO: check if it's an Service/Repair Request
return ProcessPreconditionsResolution.accept(); | }
@Override
protected String doIt()
{
final RequestId requestId = RequestId.ofRepoId(getRecord_ID());
final ProjectId projectId = serviceRepairProjectService.createProjectFromRequest(requestId);
getResult().setRecordToOpen(ProcessExecutionResult.RecordsToOpen.builder()
.record(TableRecordReference.of(I_C_Project.Table_Name, projectId))
.adWindowId(String.valueOf(ServiceRepairProjectService.AD_WINDOW_ID.getRepoId()))
.target(ProcessExecutionResult.RecordsToOpen.OpenTarget.SingleDocument)
.targetTab(ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB)
.build());
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\request\process\R_Request_StartProject.java | 2 |
请完成以下Java代码 | public void deleteCalibrations(@NonNull final HardwarePrinterId printerId) {printingDAO.deleteCalibrations(printerId);}
public void deleteMediaTrays(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaTrays(hardwarePrinterId);}
public void deleteMediaSizes(@NonNull final HardwarePrinterId hardwarePrinterId) {printingDAO.deleteMediaSizes(hardwarePrinterId);}
//
//
//
//
//
private static class HardwarePrinterMap
{
private final ImmutableMap<HardwarePrinterId, HardwarePrinter> byId;
private HardwarePrinterMap(final List<HardwarePrinter> list)
{
this.byId = Maps.uniqueIndex(list, HardwarePrinter::getId);
}
public HardwarePrinter getById(@NonNull final HardwarePrinterId id)
{
final HardwarePrinter hardwarePrinter = byId.get(id);
if (hardwarePrinter == null)
{
throw new AdempiereException("No active hardware printer found for id " + id);
}
return hardwarePrinter; | }
public Collection<HardwarePrinter> getByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
return streamByIds(ids).collect(ImmutableList.toImmutableList());
}
public Stream<HardwarePrinter> streamByIds(final @NonNull Collection<HardwarePrinterId> ids)
{
if (ids.isEmpty())
{
return Stream.empty();
}
return ids.stream()
.map(byId::get)
.filter(Objects::nonNull);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\HardwarePrinterRepository.java | 1 |
请完成以下Java代码 | public class ActivitiActivityEventImpl extends ActivitiEventImpl implements ActivitiActivityEvent {
protected String activityId;
protected String activityName;
protected String activityType;
protected String behaviorClass;
public ActivitiActivityEventImpl(ActivitiEventType type) {
super(type);
}
@Override
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName; | }
@Override
public String getActivityType() {
return activityType;
}
public void setActivityType(String activityType) {
this.activityType = activityType;
}
public String getBehaviorClass() {
return behaviorClass;
}
public void setBehaviorClass(String behaviorClass) {
this.behaviorClass = behaviorClass;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiActivityEventImpl.java | 1 |
请完成以下Java代码 | public class ConditionQueryParameterDto {
public ConditionQueryParameterDto() {
}
public static final String EQUALS_OPERATOR_NAME = "eq";
public static final String NOT_EQUALS_OPERATOR_NAME = "neq";
public static final String GREATER_THAN_OPERATOR_NAME = "gt";
public static final String GREATER_THAN_OR_EQUALS_OPERATOR_NAME = "gteq";
public static final String LESS_THAN_OPERATOR_NAME = "lt";
public static final String LESS_THAN_OR_EQUALS_OPERATOR_NAME = "lteq";
public static final String LIKE_OPERATOR_NAME = "like";
public static final String NOT_LIKE_OPERATOR_NAME = "notLike";
protected static final Map<String, QueryOperator> NAME_OPERATOR_MAP = new HashMap<>();
static {
NAME_OPERATOR_MAP.put(EQUALS_OPERATOR_NAME, QueryOperator.EQUALS);
NAME_OPERATOR_MAP.put(NOT_EQUALS_OPERATOR_NAME, QueryOperator.NOT_EQUALS);
NAME_OPERATOR_MAP.put(GREATER_THAN_OPERATOR_NAME, QueryOperator.GREATER_THAN);
NAME_OPERATOR_MAP.put(GREATER_THAN_OR_EQUALS_OPERATOR_NAME, QueryOperator.GREATER_THAN_OR_EQUAL);
NAME_OPERATOR_MAP.put(LESS_THAN_OPERATOR_NAME, QueryOperator.LESS_THAN);
NAME_OPERATOR_MAP.put(LESS_THAN_OR_EQUALS_OPERATOR_NAME, QueryOperator.LESS_THAN_OR_EQUAL);
NAME_OPERATOR_MAP.put(LIKE_OPERATOR_NAME, QueryOperator.LIKE);
NAME_OPERATOR_MAP.put(NOT_LIKE_OPERATOR_NAME, QueryOperator.NOT_LIKE);
};
protected static final Map<QueryOperator, String> OPERATOR_NAME_MAP = new HashMap<>();
static {
OPERATOR_NAME_MAP.put(QueryOperator.EQUALS, EQUALS_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.NOT_EQUALS, NOT_EQUALS_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.GREATER_THAN, GREATER_THAN_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.GREATER_THAN_OR_EQUAL, GREATER_THAN_OR_EQUALS_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.LESS_THAN, LESS_THAN_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.LESS_THAN_OR_EQUAL, LESS_THAN_OR_EQUALS_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.LIKE, LIKE_OPERATOR_NAME);
OPERATOR_NAME_MAP.put(QueryOperator.NOT_LIKE, NOT_LIKE_OPERATOR_NAME);
}; | protected String operator;
protected Object value;
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public Object resolveValue(ObjectMapper objectMapper) {
if (value instanceof String && objectMapper != null) {
try {
return objectMapper.readValue("\"" + value + "\"", Date.class);
} catch (Exception e) {
// ignore the exception
}
}
return value;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public static QueryOperator getQueryOperator(String name) {
return NAME_OPERATOR_MAP.get(name);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ConditionQueryParameterDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void doPersist(CalculatedFieldEntityCtxId stateId, CalculatedFieldStateProto stateMsgProto, TbCallback callback) {
TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_RULE_ENGINE, DataConstants.CF_STATES_QUEUE_NAME, stateId.tenantId(), stateId.entityId());
TbProtoQueueMsg<CalculatedFieldStateProto> msg = new TbProtoQueueMsg<>(stateId.entityId().getId(), stateMsgProto);
if (stateMsgProto == null) {
putStateId(msg.getHeaders(), stateId);
}
stateProducer.send(tpi, stateId.toKey(), msg, new TbQueueCallback() {
@Override
public void onSuccess(TbQueueMsgMetadata metadata) {
}
@Override
public void onFailure(Throwable t) {
log.error("Failed to send state message: {}", stateId, t);
}
});
callback.onSuccess();
}
@Override
protected void doRemove(CalculatedFieldEntityCtxId stateId, TbCallback callback) {
doPersist(stateId, null, callback); | }
private void putStateId(TbQueueMsgHeaders headers, CalculatedFieldEntityCtxId stateId) {
headers.put("tenantId", uuidToBytes(stateId.tenantId().getId()));
headers.put("cfId", uuidToBytes(stateId.cfId().getId()));
headers.put("entityId", uuidToBytes(stateId.entityId().getId()));
headers.put("entityType", stringToBytes(stateId.entityId().getEntityType().name()));
}
private CalculatedFieldEntityCtxId getStateId(TbQueueMsgHeaders headers) {
TenantId tenantId = TenantId.fromUUID(bytesToUuid(headers.get("tenantId")));
CalculatedFieldId cfId = new CalculatedFieldId(bytesToUuid(headers.get("cfId")));
EntityId entityId = EntityIdFactory.getByTypeAndUuid(bytesToString(headers.get("entityType")), bytesToUuid(headers.get("entityId")));
return new CalculatedFieldEntityCtxId(tenantId, cfId, entityId);
}
@Override
public void stop() {
super.stop();
stateProducer.stop();
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\ctx\state\KafkaCalculatedFieldStateService.java | 2 |
请完成以下Java代码 | public class EventLogEntryCollector implements IAutoCloseable
{
private static final Logger logger = LogManager.getLogger(EventLogEntryCollector.class);
private static final ThreadLocal<EventLogEntryCollector> threadLocalCollector = new ThreadLocal<>();
@Getter
private final Event event;
@Getter(AccessLevel.PACKAGE)
@VisibleForTesting
private final EventLogEntryCollector previousEntryCollector;
private final List<EventLogEntry> eventLogEntries = new ArrayList<>();
private EventLogEntryCollector(
@NonNull final Event event,
@Nullable final EventLogEntryCollector previousEntryCollector)
{
this.event = event;
this.previousEntryCollector = previousEntryCollector;
}
/**
* Called by the event-bus to create and register a log entry collector for the duration of the event-processing.
*/
public static EventLogEntryCollector createThreadLocalForEvent(@NonNull final Event event)
{
final EventLogEntryCollector previousEntryCollector = threadLocalCollector.get();
final EventLogEntryCollector entryCollector = new EventLogEntryCollector(event, previousEntryCollector);
threadLocalCollector.set(entryCollector);
return entryCollector;
}
public static EventLogEntryCollector getThreadLocal()
{
final EventLogEntryCollector eventLogCollector = threadLocalCollector.get();
Check.errorIf(eventLogCollector == null,
"Missing thread-local EventLogEntryCollector instance. It is expected that one was created using createThreadLocalForEvent().");
return eventLogCollector;
}
public void addEventLog(@NonNull final EventLogEntryRequest eventLogRequest)
{
final EventLogEntry eventLogEntry = EventLogEntry.builder()
.uuid(event.getUuid())
.clientId(eventLogRequest.getClientId())
.orgId(eventLogRequest.getOrgId())
.processed(eventLogRequest.isProcessed())
.error(eventLogRequest.isError())
.adIssueId(eventLogRequest.getAdIssueId())
.message(eventLogRequest.getMessage())
.eventHandlerClass(eventLogRequest.getEventHandlerClass()) | .build();
eventLogEntries.add(eventLogEntry);
}
@Override
public void close()
{
// Restore previous entry collector
// or clear the current one
if (previousEntryCollector != null)
{
threadLocalCollector.set(previousEntryCollector);
}
else
{
threadLocalCollector.remove();
}
// Avoid throwing exception because EventLogService is not available in unit tests
if (Adempiere.isUnitTestMode())
{
return;
}
try
{
final EventLogService eventStoreService = SpringContextHolder.instance.getBean(EventLogService.class);
eventStoreService.saveEventLogEntries(eventLogEntries);
}
catch (final Exception ex)
{
logger.warn("Failed saving {}. Ignored", eventLogEntries, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogEntryCollector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SimpleReportFiller {
private String reportFileName;
private JasperReport jasperReport;
private JasperPrint jasperPrint;
@Autowired
private DataSource dataSource;
private Map<String, Object> parameters;
public SimpleReportFiller() {
parameters = new HashMap<>();
}
public void prepareReport() {
compileReport();
fillReport();
}
public void compileReport() {
try {
InputStream reportStream = getClass().getResourceAsStream("/".concat(reportFileName));
jasperReport = JasperCompileManager.compileReport(reportStream);
JRSaver.saveObject(jasperReport, reportFileName.replace(".jrxml", ".jasper"));
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void fillReport() {
try {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection()); | } catch (JRException | SQLException ex) {
Logger.getLogger(SimpleReportFiller.class.getName()).log(Level.SEVERE, null, ex);
}
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public String getReportFileName() {
return reportFileName;
}
public void setReportFileName(String reportFileName) {
this.reportFileName = reportFileName;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
} | repos\tutorials-master\libraries-reporting\src\main\java\com\baeldung\jasperreports\SimpleReportFiller.java | 2 |
请完成以下Java代码 | public UpdateJobDefinitionSuspensionStateBuilderImpl byJobDefinitionId(String jobDefinitionId) {
ensureNotNull("jobDefinitionId", jobDefinitionId);
this.jobDefinitionId = jobDefinitionId;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl byProcessDefinitionId(String processDefinitionId) {
ensureNotNull("processDefinitionId", processDefinitionId);
this.processDefinitionId = processDefinitionId;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl byProcessDefinitionKey(String processDefinitionKey) {
ensureNotNull("processDefinitionKey", processDefinitionKey);
this.processDefinitionKey = processDefinitionKey;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl processDefinitionWithoutTenantId() {
this.processDefinitionTenantId = null;
this.isProcessDefinitionTenantIdSet = true;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl processDefinitionTenantId(String tenantId) {
ensureNotNull("tenantId", tenantId);
this.processDefinitionTenantId = tenantId;
this.isProcessDefinitionTenantIdSet = true;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl includeJobs(boolean includeJobs) {
this.includeJobs = includeJobs;
return this;
}
@Override
public UpdateJobDefinitionSuspensionStateBuilderImpl executionDate(Date executionDate) {
this.executionDate = executionDate;
return this;
}
@Override
public void activate() {
validateParameters();
ActivateJobDefinitionCmd command = new ActivateJobDefinitionCmd(this);
commandExecutor.execute(command); | }
@Override
public void suspend() {
validateParameters();
SuspendJobDefinitionCmd command = new SuspendJobDefinitionCmd(this);
commandExecutor.execute(command);
}
protected void validateParameters() {
ensureOnlyOneNotNull("Need to specify either a job definition id, a process definition id or a process definition key.",
jobDefinitionId, processDefinitionId, processDefinitionKey);
if (isProcessDefinitionTenantIdSet && (jobDefinitionId != null || processDefinitionId != null)) {
throw LOG.exceptionUpdateSuspensionStateForTenantOnlyByProcessDefinitionKey();
}
ensureNotNull("commandExecutor", commandExecutor);
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isProcessDefinitionTenantIdSet() {
return isProcessDefinitionTenantIdSet;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public boolean isIncludeJobs() {
return includeJobs;
}
public Date getExecutionDate() {
return executionDate;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\management\UpdateJobDefinitionSuspensionStateBuilderImpl.java | 1 |
请完成以下Java代码 | public boolean isActive()
{
return getProductDetails().isActive();
}
public boolean isFraud()
{
return getProductDetails().isFraud();
}
public boolean isDecommissioned()
{
return getProductDetails().isDecommissioned();
} | public String getDecommissionServerTransactionId()
{
return getProductDetails().getDecommissionedServerTransactionId();
}
public void productDecommissioned(@NonNull final String decommissionedServerTransactionId)
{
getProductDetails().productDecommissioned(decommissionedServerTransactionId);
}
public void productDecommissionUndo(@NonNull final String undoDecommissionedServerTransactionId)
{
getProductDetails().productDecommissionUndo(undoDecommissionedServerTransactionId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\product\SecurPharmProduct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable String getContextPath() {
return this.contextPath;
}
public void setContextPath(@Nullable String contextPath) {
this.contextPath = cleanContextPath(contextPath);
}
private @Nullable String cleanContextPath(@Nullable String contextPath) {
String candidate = null;
if (StringUtils.hasLength(contextPath)) {
candidate = contextPath.strip();
}
if (StringUtils.hasText(candidate) && candidate.endsWith("/")) {
return candidate.substring(0, candidate.length() - 1);
}
return candidate;
}
public String getApplicationDisplayName() {
return this.applicationDisplayName;
}
public void setApplicationDisplayName(String displayName) {
this.applicationDisplayName = displayName;
}
public boolean isRegisterDefaultServlet() {
return this.registerDefaultServlet;
}
public void setRegisterDefaultServlet(boolean registerDefaultServlet) {
this.registerDefaultServlet = registerDefaultServlet;
}
public Map<String, String> getContextParameters() {
return this.contextParameters;
}
public Encoding getEncoding() {
return this.encoding;
}
public Jsp getJsp() {
return this.jsp;
}
public Session getSession() {
return this.session;
}
}
/**
* Reactive server properties.
*/
public static class Reactive {
private final Session session = new Session();
public Session getSession() {
return this.session;
}
public static class Session {
/**
* Session timeout. If a duration suffix is not specified, seconds will be
* used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration timeout = Duration.ofMinutes(30);
/**
* Maximum number of sessions that can be stored.
*/
private int maxSessions = 10000;
@NestedConfigurationProperty
private final Cookie cookie = new Cookie(); | public Duration getTimeout() {
return this.timeout;
}
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
public int getMaxSessions() {
return this.maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
public Cookie getCookie() {
return this.cookie;
}
}
}
/**
* Strategies for supporting forward headers.
*/
public enum ForwardHeadersStrategy {
/**
* Use the underlying container's native support for forwarded headers.
*/
NATIVE,
/**
* Use Spring's support for handling forwarded headers.
*/
FRAMEWORK,
/**
* Ignore X-Forwarded-* headers.
*/
NONE
}
public static class Encoding {
/**
* Mapping of locale to charset for response encoding.
*/
private @Nullable Map<Locale, Charset> mapping;
public @Nullable Map<Locale, Charset> getMapping() {
return this.mapping;
}
public void setMapping(@Nullable Map<Locale, Charset> mapping) {
this.mapping = mapping;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java | 2 |
请完成以下Java代码 | private final String valueToString(final E value)
{
if (value == null)
{
return "";
}
final ListCellRenderer<? super E> renderer = comboBox.getRenderer();
if (renderer == null)
{
return value.toString();
}
final JList<E> list = getJList();
if (list == null)
{
return value.toString();
}
final int index = 0; // NOTE: most of the renderers are not using it. Also it is known that is not correct.
final Component valueComp = renderer.getListCellRendererComponent(list, value, index, false, false);
if (valueComp instanceof JLabel)
{
return ((JLabel)valueComp).getText();
}
return value.toString();
}
/** @return combobox's inner JList (if available) */
private JList<E> getJList()
{
final ComboPopup comboPopup = AdempiereComboBoxUI.getComboPopup(comboBox);
if (comboPopup == null)
{
return null;
}
@SuppressWarnings("unchecked")
final JList<E> list = (JList<E>)comboPopup.getList();
return list;
}
private final class EditingCommand
{
private boolean doSelectItem = false;
private E itemToSelect = null;
private boolean doSetText = false;
private String textToSet = null;
private boolean doHighlightText = false;
private int highlightTextStartPosition = 0;
public void setItemToSelect(final E itemToSelect)
{
this.itemToSelect = itemToSelect;
this.doSelectItem = true;
} | public boolean isDoSelectItem()
{
return doSelectItem;
}
public E getItemToSelect()
{
return itemToSelect;
}
public void setTextToSet(String textToSet)
{
this.textToSet = textToSet;
this.doSetText = true;
}
public boolean isDoSetText()
{
return doSetText;
}
public String getTextToSet()
{
return textToSet;
}
public void setHighlightTextStartPosition(int highlightTextStartPosition)
{
this.highlightTextStartPosition = highlightTextStartPosition;
this.doHighlightText = true;
}
public boolean isDoHighlightText()
{
return doHighlightText;
}
public int getHighlightTextStartPosition()
{
return highlightTextStartPosition;
}
};
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\ComboBoxAutoCompletion.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder enableDuplicateFiltering() {
return enableDuplicateFiltering(false);
}
public DeploymentBuilder enableDuplicateFiltering(boolean deployChangedOnly) {
this.isDuplicateFilterEnabled = true;
this.deployChangedOnly = deployChangedOnly;
return this;
}
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
public DeploymentBuilder source(String source) {
deployment.setSource(source);
return this;
}
public DeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
public Deployment deploy() {
return deployWithResult();
}
public DeploymentWithDefinitions deployWithResult() {
return repositoryService.deployWithResult(this);
}
public Collection<String> getResourceNames() {
if(deployment.getResources() == null) {
return Collections.<String>emptySet();
} else {
return deployment.getResources().keySet(); | }
}
// getters and setters //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public boolean isDeployChangedOnly() {
return deployChangedOnly;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public String getNameFromDeployment() {
return nameFromDeployment;
}
public Set<String> getDeployments() {
return deployments;
}
public Map<String, Set<String>> getDeploymentResourcesById() {
return deploymentResourcesById;
}
public Map<String, Set<String>> getDeploymentResourcesByName() {
return deploymentResourcesByName;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public List<File> getFiles(final String localFolderName)
{
final File localFolder = new File(localFolderName);
if (!localFolder.isDirectory() || !localFolder.canRead())
{
ConfigException.throwNew(ConfigException.LOCALFOLDER_CANT_READ_1P,
null, localFolderName);
}
return Arrays.asList(localFolder.listFiles());
}
public String moveToArchive(final File importedFile,
final String archiveFolder)
{
final File archiveDir = new File(archiveFolder);
checkArchiveDir(archiveDir);
final File destFile = new File(archiveDir, importedFile.getName());
if (!importedFile
.renameTo(destFile)) | {
ConfigException.throwNew(ConfigException.ARCHIVE_RENAME_FAILED_2P,
importedFile.getAbsolutePath(), archiveDir
.getAbsolutePath());
}
return null;
}
private void checkArchiveDir(final File archiveDir)
{
if (!archiveDir.isDirectory())
{
ConfigException.throwNew(ConfigException.ARCHIVE_NOT_A_DIR_1P,
archiveDir.getAbsolutePath());
}
if (!archiveDir.canWrite())
{
ConfigException.throwNew(ConfigException.ARCHIVE_CANT_WRITE_1P,
archiveDir.getAbsolutePath());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\api\impl\InboundProcessorBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
FileEvidence fileEvidence = (FileEvidence)o;
return Objects.equals(this.fileId, fileEvidence.fileId);
}
@Override
public int hashCode()
{
return Objects.hash(fileId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class FileEvidence {\n");
sb.append(" fileId: ").append(toIndentedString(fileId)).append("\n");
sb.append("}");
return sb.toString(); | }
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\FileEvidence.java | 2 |
请完成以下Java代码 | public void objectDeleted(ObjectDeletedEvent event) {
System.out.println("Object retracted \n"
+ event.getOldObject().toString());
}
});
return kieSession;
}
@Bean
public KieContainer getKieContainer() throws IOException {
LOGGER.info("Container created...");
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
kb.buildAll();
KieModule kieModule = kb.getKieModule();
return kieServices.newKieContainer(kieModule.getReleaseId());
} | private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(new KieModule() {
@Override
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
}
private KieFileSystem getKieFileSystem() throws IOException {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("order.drl"));
return kieFileSystem;
}
} | repos\springboot-demo-master\drools\src\main\java\com\et\drools\DroolsConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void validate(String name) {
if (EntityCoordinates.ENTITY_ID_LATITUDE_ARGUMENT_KEY.equals(name) || EntityCoordinates.ENTITY_ID_LONGITUDE_ARGUMENT_KEY.equals(name)) {
throw new IllegalArgumentException("Name '" + name + "' is reserved and cannot be used for zone group!");
}
if (refDynamicSourceConfiguration != null) {
refDynamicSourceConfiguration.validate();
}
if (!createRelationsWithMatchedZones) {
return;
}
if (StringUtils.isBlank(relationType)) {
throw new IllegalArgumentException("Relation type must be specified for '" + name + "' zone group!");
}
if (direction == null) {
throw new IllegalArgumentException("Relation direction must be specified for '" + name + "' zone group!");
}
}
public boolean hasRelationQuerySource() {
return toArgument().hasRelationQuerySource();
}
public boolean hasCurrentOwnerSource() {
return toArgument().hasOwnerSource(); | }
@JsonIgnore
public boolean isCfEntitySource(EntityId cfEntityId) {
if (refEntityId == null && refDynamicSourceConfiguration == null) {
return true;
}
return refEntityId != null && refEntityId.equals(cfEntityId);
}
@JsonIgnore
public boolean isLinkedCfEntitySource(EntityId cfEntityId) {
return refEntityId != null && !refEntityId.equals(cfEntityId);
}
public Argument toArgument() {
var argument = new Argument();
argument.setRefEntityId(refEntityId);
argument.setRefDynamicSourceConfiguration(refDynamicSourceConfiguration);
argument.setRefEntityKey(new ReferencedEntityKey(perimeterKeyName, ArgumentType.ATTRIBUTE, AttributeScope.SERVER_SCOPE));
return argument;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\geofencing\ZoneGroupConfiguration.java | 2 |
请完成以下Java代码 | public static void train(Options options) throws IOException, ExecutionException, InterruptedException
{
if (options.inputFile.equals("") || options.modelFile.equals(""))
{
Options.showHelp();
}
else
{
IndexMaps maps = CoNLLReader.createIndices(options.inputFile, options.labeled, options.lowercase, options.clusterFile);
CoNLLReader reader = new CoNLLReader(options.inputFile);
ArrayList<Instance> dataSet = reader.readData(Integer.MAX_VALUE, false, options.labeled, options.rootFirst, options.lowercase, maps);
// System.out.println("读取CoNLL文件结束。");
ArrayList<Integer> dependencyLabels = new ArrayList<Integer>();
dependencyLabels.addAll(maps.getLabels().keySet());
int featureLength = options.useExtendedFeatures ? 72 : 26;
if (options.useExtendedWithBrownClusterFeatures || maps.hasClusters())
featureLength = 153;
System.out.println("训练集句子数量: " + dataSet.size());
HashMap<String, Integer> labels = new HashMap<String, Integer>();
labels.put("sh", labels.size());
labels.put("rd", labels.size());
labels.put("us", labels.size());
for (int label : dependencyLabels)
{
if (options.labeled)
{ | labels.put("ra_" + label, 3 + label);
labels.put("la_" + label, 3 + dependencyLabels.size() + label);
}
else
{
labels.put("ra_" + label, 3);
labels.put("la_" + label, 4);
}
}
ArcEagerBeamTrainer trainer = new ArcEagerBeamTrainer(options.useMaxViol ? "max_violation" : "early",
new AveragedPerceptron(featureLength, dependencyLabels.size()),
options, dependencyLabels, featureLength, maps);
trainer.train(dataSet, options.devPath, options.trainingIter, options.modelFile, options.lowercase, options.punctuations, options.partialTrainingStartingIteration);
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\parser\Main.java | 1 |
请完成以下Java代码 | public class GravitySort {
public static int findMax(int[] A) {
int max = A[0];
for (int i = 1; i< A.length; i++) {
if (A[i] > max) {
max = A[i];
}
}
return max;
}
public static boolean[][] setupAbacus(int[] A, int m) {
boolean[][] abacus = new boolean[A.length][m];
for (int i = 0; i < abacus.length; i++) {
int number = A[i];
for (int j = 0; j < abacus[0].length && j < number; j++) {
abacus[A.length - 1 - i][j] = true;
}
}
return abacus;
}
public static void dropBeads(boolean[][] abacus, int[] A, int m) {
for (int i = 1; i < A.length; i++) {
for (int j = m - 1; j >= 0; j--) {
if (abacus[i][j] == true) {
int x = i;
while (x > 0 && abacus[x - 1][j] == false) {
boolean temp = abacus[x - 1][j];
abacus[x - 1][j] = abacus[x][j];
abacus[x][j] = temp;
x--; | }
}
}
}
}
public static void transformToList(boolean[][] abacus, int[] A) {
int index = 0;
for (int i = abacus.length - 1; i >= 0; i--) {
int beads = 0;
for (int j = 0; j < abacus[0].length && abacus[i][j] == true; j++) {
beads++;
}
A[index++] = beads;
}
}
public static void sort(int[] A) {
int m = findMax(A);
boolean[][] abacus = setupAbacus(A, m);
dropBeads(abacus, A, m);
// transform abacus into sorted list
transformToList(abacus, A);
}
} | repos\tutorials-master\algorithms-modules\algorithms-sorting-3\src\main\java\com\baeldung\algorithms\gravitysort\GravitySort.java | 1 |
请完成以下Java代码 | public void pushDown()
{
// nothing
}
@Override
public void saveChangesIfNeeded()
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public void setSaveOnChange(final boolean saveOnChange)
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public IAttributeStorageFactory getAttributeStorageFactory()
{
throw new UnsupportedOperationException();
}
@Nullable
@Override
public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{
return "NullAttributeStorage []";
} | @Override
public BigDecimal getStorageQtyOrZERO()
{
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/
@Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java | 1 |
请完成以下Java代码 | public String getName() {
return this.name;
}
@Override
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder for {@link JwtAuthenticationToken} instances
*
* @since 7.0
* @see Authentication.Builder
*/
public static class Builder<B extends Builder<B>> extends AbstractOAuth2TokenAuthenticationBuilder<Jwt, B> {
private String name;
protected Builder(JwtAuthenticationToken token) {
super(token);
this.name = token.getName();
}
/**
* A synonym for {@link #token(Jwt)}
* @return the {@link Builder} for further configurations
*/
@Override
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(Jwt.class, principal, "principal must be of type Jwt");
return token((Jwt) principal);
}
/**
* A synonym for {@link #token(Jwt)}
* @return the {@link Builder} for further configurations
*/
@Override
public B credentials(@Nullable Object credentials) {
Assert.isInstanceOf(Jwt.class, credentials, "credentials must be of type Jwt");
return token((Jwt) credentials); | }
/**
* Use this {@code token} as the token, principal, and credentials. Also sets the
* {@code name} to {@link Jwt#getSubject}.
* @param token the token to use
* @return the {@link Builder} for further configurations
*/
@Override
public B token(Jwt token) {
super.principal(token);
super.credentials(token);
return super.token(token).name(token.getSubject());
}
/**
* The name to use.
* @param name the name to use
* @return the {@link Builder} for further configurations
*/
public B name(String name) {
this.name = name;
return (B) this;
}
@Override
public JwtAuthenticationToken build() {
return new JwtAuthenticationToken(this);
}
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\authentication\JwtAuthenticationToken.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected DataResponse<HistoricActivityInstanceResponse> getQueryResponse(HistoricActivityInstanceQueryRequest queryRequest, Map<String, String> allRequestParams) {
HistoricActivityInstanceQuery query = historyService.createHistoricActivityInstanceQuery();
// Populate query based on request
if (queryRequest.getActivityId() != null) {
query.activityId(queryRequest.getActivityId());
}
if (queryRequest.getActivityInstanceId() != null) {
query.activityInstanceId(queryRequest.getActivityInstanceId());
}
if (queryRequest.getActivityName() != null) {
query.activityName(queryRequest.getActivityName());
}
if (queryRequest.getActivityType() != null) {
query.activityType(queryRequest.getActivityType());
}
if (queryRequest.getExecutionId() != null) {
query.executionId(queryRequest.getExecutionId());
}
if (queryRequest.getFinished() != null) {
Boolean finished = queryRequest.getFinished();
if (finished) {
query.finished();
} else {
query.unfinished();
}
}
if (queryRequest.getTaskAssignee() != null) {
query.taskAssignee(queryRequest.getTaskAssignee());
}
if (queryRequest.getProcessInstanceId() != null) {
query.processInstanceId(queryRequest.getProcessInstanceId());
}
if (queryRequest.getProcessInstanceIds() != null && !queryRequest.getProcessInstanceIds().isEmpty()) {
query.processInstanceIds(queryRequest.getProcessInstanceIds());
}
if (queryRequest.getProcessDefinitionId() != null) {
query.processDefinitionId(queryRequest.getProcessDefinitionId());
} | if (queryRequest.getCalledProcessInstanceIds() != null && !queryRequest.getCalledProcessInstanceIds().isEmpty()) {
query.calledProcessInstanceIds(queryRequest.getCalledProcessInstanceIds());
}
if (queryRequest.getTenantId() != null) {
query.activityTenantId(queryRequest.getTenantId());
}
if (queryRequest.getTenantIdLike() != null) {
query.activityTenantIdLike(queryRequest.getTenantIdLike());
}
if (Boolean.TRUE.equals(queryRequest.getWithoutTenantId())) {
query.activityWithoutTenantId();
}
if (restApiInterceptor != null) {
restApiInterceptor.accessHistoryActivityInfoWithQuery(query, queryRequest);
}
return paginateList(allRequestParams, queryRequest, query, "startTime", allowedSortProperties,
restResponseFactory::createHistoricActivityInstanceResponseList);
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceBaseResource.java | 2 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
final OrderId orderId = OrderId.ofRepoId(context.getSingleSelectedRecordId());
final I_C_Order order = orderBL.getById(orderId);
if (order.isSOTrx())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("is sales order");
}
final DocStatus docStatus = DocStatus.ofCode(order.getDocStatus());
if (!docStatus.isCompletedOrClosed())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not completed or closed");
}
if (!orderToShipperTransportationService.anyMatch(ShippingPackageQuery.builder().orderId(orderId).build())) | {
return ProcessPreconditionsResolution.rejectWithInternalReason("has no packages");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final ReportResultData report = orderToShipperTransportationService.printSSCC18_Labels(OrderId.ofRepoId(getRecord_ID()));
getResult().setReportData(report);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\process\C_Order_SSCC_Print.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String make;
private String model;
public Car() {
}
public Car(Long id, String make, String model) {
this.id = id;
this.make = make;
this.model = model;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
} | public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", make='" + make + '\'' +
", model='" + model + '\'' +
'}';
}
} | repos\tutorials-master\persistence-modules\spring-persistence\src\main\java\com\baeldung\spring\transactional\Car.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.